foreach loop List performance difference

Question: While working on a project I ran into the following piece of code, which raised a performance flag.
foreach (var sample in List.Where(x => !x.Value.Equals("Not Reviewed")))
{
    //do other work here
    count++;
}

I decided to run a couple of quick tests comparing the original loop to the following loop:
foreach (var sample in List)
{
    if (!sample.Value.Equals("Not Reviewed"))
    {
        //do other work here
        count++;
    }
}

and threw this loop in too to see what happens:
var tempList = List.Where(x => !x.Value.Equals("Not Reviewed"));
foreach (var sample in tempList)
{
    //do other work here
    count++;
}

I also populated the original list 3 different ways: 50-50 (so 50% of values where "Not Reviewed" and the rest other), 10-90 and 90-10. These are my results, the first and last loops
are mostly the same but the second one is much faster, especially on 10-90 case. Why exactly? I always thought Lambda had good performance.
EDIT
The count++ is not actually what's inside the loop, I just added that here for demonstration purposes, I guess I should've used "//do something here"

EDIT 2
Results running each one 1000 times:
Comment: @MikePrecup: Or even better, `List.Count(x => !x.Value.Equals("Not Reviewed"))`
Comment: It'd be interesting to see how `List.Where(x => !x.Value.Equals("Not Reviewed")).Count()` performs compared to those.
Comment: Have you made sure you didn't make any of these [Performance Benchmark Mistakes](http://tech.pro/blog/1293/c-performance-benchmark-mistakes-part-one)?
Comment: I'd be surprised if #1 and #3 don't compile to the exact same thing...
Comment: 1 ms is not significant enough here to be _different_ (especially on single runs)...
Comment: @AustinSalonen I think they are not, why else would their performance be different?
Comment: @SOfanatic: Because of noise in benchmarking, basically. You can see that you're not getting the exact same results every run anyway.
Comment: @JonSkeet I thought the difference in all three cases was because of the data distribution (50% "Not Reviewed", 10% "Not Reviewed", and 90% "Not Reviewed")
Comment: @SOfanatic:  Run each one a 1000 times and report the distributions -- you're not working with enough data points to make a good assessment.
Comment: @SOfanatic: Ah, forgot that - but try running it many times on the same data set and I'm sure you'll see the results vary over time.
Comment: @AustinSalonen ok I added the results for 1000 times and it seems to produce the same results.
Comment: @SOfanatic: It doesn't help that apparently you haven't presented the results in the same order both times. I suspect the bottom screenshot of the second set is equivalent to the *middle* screenshot in the first set.
Comment: @JonSkeet it's the same order. The 1st in both is 50-50, 2nd is 10-90 ( not reviewed/review) and 90-10
Answer: Basically, there's a small amount of extra indirection - both for the test via a delegate, and for the iterating part. Given just how little work is being done per iteration, that extra indirection is relatively expensive.
That's neither surprising nor worrying, in my view. It's the kind of micro-optimization you can easily perform if you're in the rare situation of it being significant in your real-world application. In my experience it's pretty rare for this sort of loop to be a significant bottleneck in the app. The normal approach should be:

Define performance requirements
Implement the functional requirements in the clearest, simplest way you can
Measure your performance against the requirements
If performance is found wanting, investigate why and only move away from clarity as little as you can, getting the biggest "bang for buck" that you can
Repeat until you're done

Responding to an edit:

The count++ is not actually what's inside the loop, I just added that here for demonstration purposes, I guess I should've used "//do something here"

Well that's the important bit - the more work that is done there, the less significant anything else will be. Just counting is pretty darned fast, so I'd expect to see a large discrepancy. Do any amount of real work, and the difference will be smaller.


Double limit of Riemann integrals

Question: Let $\{f_n(x)\}_{n\in\mathbb{N}}$ a family of infinitely differentiable functions, defined on the entire real line, vanishing outside $[a,b]$. Let $F(x)$ be any function defined on $\mathbb{R}$ with the property that $F$ and all its derivatives are $O(|x|^{-N})$ as $|x|\to\infty$, for every $N$.
By hypothesis, the following limit:
$$\lim_{n\to\infty}\int_{x=a}^b f_n(x)F(x)\mathrm{d}x$$
exists for any $F$ of the type specified above.
Is it true or false that $\lim_{|\xi|\to\infty}\left(\lim_{n\to\infty}\int_{x=a}^b f_n(x)F(x-\xi)\mathrm{d}x\right)=0$ ?
For me it is intuitively true, because $F(x-\xi)$ 'slip away' to infinity as $|\xi|\to\infty$, leaving inside $[a,b]$ a smaller and smaller contribution, but I can't formalize this argument.
Comment: You can probably view the expression in question as a convolution, look at its Fourier transform and look up theorems on how asymptotics influence the Fourier transform of a function.
Answer: We make use of the theorem below.

Theorem. Let $(T_n)_{n\in\mathbb{N}} \subset \mathcal{D}'(\mathbb{R})$ be a sequence of distributions on $\mathbb{R}$ such that the following conditions hold:

There exists a compact interval $K \subset \mathbb{R}$ such that each $T_n$ is supported on $K$.
$(T_n)_{n\in\mathbb{N}}$ converges to a linear functional $T$ on $C^{\infty}_c(\mathbb{R})$ under weak*-topology, that is, $$ \lim_{n\to\infty} \langle T_n, \varphi \rangle = \langle T, \varphi \rangle $$ holds for any $\varphi \in C^{\infty}_c(\mathbb{R})$.

Then $T$ is also a distribution on $\mathbb{R}$ that is supported on $K$.
Proof. We may regard each $T_n$ as a linear functional on $C^{\infty}(K)$ and we do so. Since $K$ is compact, $C^{\infty}(K)$ is a Fréchet space with respect to the topology induced by seminorms $\varphi \mapsto \sup_{x\in K}|\varphi^{(m)}(x)|$, $m\geq 0$. Then a version of uniform boundedness principle ([1], [2]) shows that the family $(T_n)_{n\in\mathbb{N}}$ is equicontinuous, hence the pointwise limit $T$ is also continuous. $\square$

Now let $(f_n)_{n\in\mathbb{N}}$ be the sequence of smooth functions as in OP's hypothesis, and let $T$ be the linear functional on $C^{\infty}_c(\mathbb{R})$ defined by the relation
$$ \langle T, \varphi \rangle = \lim_{n\to\infty} \int_{a}^{b} f_n(x) \varphi(x) \, \mathrm{d}x $$
for all $\varphi \in C^{\infty}_c(\mathbb{R})$. Then the theorem tells that $T$ is a distribution supported on the compact interval $[a, b]$. Since every compactly supported distribution had finite order, this implies that there exist an integer $k \geq 0$ and a finite constant $C \geq 0$ satisfying
$$ |\langle T, \varphi \rangle| \leq C \sup_{x \in K} |\varphi^{(k)}(x)| $$
for any $\varphi \in C^{\infty}(\mathbb{R})$. Consequently, for any $F$ satisfying OP's condition,
\begin{align*}
\lim_{n\to\infty} \int_{a}^{b} f_n(x)F(x-\xi) \, \mathrm{d}x
&= \langle T, F(\cdot - \xi) \rangle
= \mathcal{O}\left( \sup_{x \in K} |F^{(k)}(x - \xi)|  \right)
\end{align*}
Now it is easy to check that this vanishes as $|\xi| \to \infty$.
Comment: @Nameless, No problem. For example, you can refer to Theorem 8.3.1 of G. Friedlander and M. Joshi. *Introduction to the Theory of Distributions.* Cambridge University Press, 1998.
Comment: @Nameless, That's a good point, and my original argument did not properly verify that the limiting functional is continuous. Now I revamped my answer accordingly.
Comment: I see that for proving continuity there is a lot of extra theory to know. For example, I don't know what a Frechét space is or what seminorms are. I will try to study, meanwhile... thank you very much.
Comment: @Nameless, No problem :) If you already know a bit about Banach spaces (a.k.a. complete normed spaces) and the uniform boundedness principle on then, then you won't have much trouble understanding what a Frechét space is and how UBP generalizes to then. Here is a quick summary: Seminorms are just "degenerate norms", no longer requiring non-zero elements to have positive norm. This means that a single seminorm may not have enough resolution for distinguishing two elements, so we need a family of seminorms to have enough resolution for that. Frechét spaces are defined based on this idea.
Comment: Sorry for my ignorance. Could you link me a proof of this theorem, please? In such a way I can study.
Comment: It seems to me that the proof is based on an additional hypothesis that I don't have: the continuity. Is that right or am I wrong?
If I am wrong, where can I see that my functional $L(F)=\lim_{n\to\infty}\int_{x=a}^b f_n(x)F(x)\mathrm{d}x$ is continuous?
Answer: You can start by proving that $$\lim_{n\to \infty} \int_{a}^{b} f_n(x)\mathrm d x$$ is finite. For that let
$$h(x) = \begin{cases}
\exp\left({-\frac{1}{\left(e^x - 1\right)^2}}\right) & \text{if $x > 0$}\\
0 & \text{if $x \le 0$}
\end{cases}$$
This $h$ function is infinitly differentiate function such that $$\lim_{x\to \infty} e^x \left(1-h(x)\right) = 0$$
Let $$F(x) = \begin{cases}
1-h(a-x) & \text{if $a < x$}\\
1 & \text{if $a \le x \le b$}\\
1-h(b-x) & \text{if $b < x$}
\end{cases}$$
It is easy to prove that $F$ satisfy the conditions mentionned in the OP so you have that the limit $$\lim_{n\to \infty} \int_a^bf_n(x)F(x)\mathrm d x$$ exists.

Double limit of Riemann integrals


How many times larger is 5 × 106 than 5 × 102?"How much is it more/small than" calculator.

Question: I need to find a calculator that will essentially give me how ever much a number is smaller/bigger than another number.
Example:
If I enter the two numbers '1' and '4'.
It will tell me, '4' is x4 times larger than '1'
This should also work with floatation point numbers, in the case that there is not such a calculator, the number that I need to calculate is 0.6 and 1.0.
Thank you very much, and sorry for the lack of research, but I really do not know how to word this correctly, I hope anyone reading understands.
Comment: Have you tried, ehm, dividing the numbers?
Comment: @ajotatxe I am so sorry for being so stupid, I have no idea how I literally managed to not realize that.. Thank you so much
Comment: 4 is [three times larger](https://math.stackexchange.com/a/4722720/21813) than 1; 4 is zero times larger than 4; 4 is one time larger than 2.
Answer: The term you are looking for is division, which (thankfully) is already on most calculators.
Comment: Your answer reminded me of [this one](http://cooking.stackexchange.com/a/14596).
Answer: Divide the largest one by the smallest one : for example, the number $4$ is $\frac{4}{2}=2\times$ larger than the number $2$.
Indeed, If you multiply $2$ by $\frac{4}{2}$ you'll get 4.
Of course, if a number is $n\times$ larger than another, then this other is $n\times$ smaller than the first one.
It will of course work with floating point :
$0.6\times\frac{1}{0.6}≈0.6\times 1.6667 = 1$ so $1$ is $\text{~}1.6667$ times larger than $0.6$ while $0.6$ is $\text{~}1.6667$ smaller than $1$.


How to add multiple IPv4 Subnets to a VLAN using Allied Telesyn at9924 Switch?

Question: I cannot figure out adding more than one IPv4 subnets on a VLAN using Allied Telesyn at9924 Switch
I've added the first IP using this command:
add ip int=vlan15 ip=xxx.243.117.193 mask=255.255.255.248
Now, I want to add another /29 subnets on the same VLAN (15). When I try the same command, I get this:
add ip int=vlan15 ip=xxx.79.99.17 mask=255.255.255.248
Error (3005263): Interface is already attached to IP module.
Comment: Alliedware seems to protect their core manual. What you're after is called a "secondary" ip address in Cisco terms. They might allow you to create subinterfaces ie... int vlan15.2 wish I could give you more but without documentation I can't.
Answer: Only a single ip can be assigned per interface, but I believe you can have up to 16 logical interfaces per interface (ie. vlan1, ppp0, etc).
Just append -# to the interface name, like so:
Manager switch1> show ip int

Interface     Type     IP Address       Bc Fr PArp  Filt RIP Met.   SAMode  IPSc
Pri. Filt     Pol.Filt Network Mask     MTU   VJC   GRE  OSPF Met.  DBcast  Mul.
GArp   NotifyOSPFDown
--------------------------------------------------------------------------------
LOCAL         ---      Not set          -  -  -     ---  --         Pass    --
---           ---      Not set          1500  -     ---  --         ---     ---
On
vlan1         Remote   10.1.1.113       1  n  Off   ---  01         Pass    No
---           ---      255.255.255.0    1500  -     ---  0000000001 No      Rec
On     Yes
--------------------------------------------------------------------------------

Manager switch1> add ip int=vlan1-1 ip=192.168.55.1 mask=255.255.255.0

Info (1005275): interface successfully added.

Manager switch1> show ip int

Interface     Type     IP Address       Bc Fr PArp  Filt RIP Met.   SAMode  IPSc
Pri. Filt     Pol.Filt Network Mask     MTU   VJC   GRE  OSPF Met.  DBcast  Mul.
GArp   NotifyOSPFDown
--------------------------------------------------------------------------------
LOCAL         ---      Not set          -  -  -     ---  --         Pass    --
---           ---      Not set          1500  -     ---  --         ---     ---
On
vlan1-0       Remote   10.1.1.113       1  n  Off   ---  01         Pass    No
---           ---      255.255.255.0    1500  -     ---  0000000001 No      Rec
On     Yes
vlan1-1       Static   192.168.55.1     1  n  Off   ---  01         Pass    No
---           ---      255.255.255.0    1500  -     ---  0000000001 No      Rec
On     Yes
--------------------------------------------------------------------------------

The vlan1 interface is automatically changed to vlan1-0 to indicate there are logical interfaces.
Answer: You don't need to make a switch aware of all the subnets on the VLAN.
It will switch traffic perfectly fine without this knowledge.
Comment: Yes, but it won't route it.


Which two football clubs are competing in this YouTube video billed as the first ever filmed football match in 1897?

Question: Footage from the first filmed football match in 1897 can be found on YouTube here.
I was just wondering, who are the two football clubs in action?
Comment: The [IMDB entry for the short](https://www.imdb.com/title/tt0350952/) notes the filming location as "London, England". Rules it down a little bit, but not much.
Answer: According the The Belfast Telegraph, this is a match between Glentoran FC and Cliftonville FC on Mersey Street in Belfast, Northern Ireland, and is indeed thought to be the first known video of a football match:

Archive footage of a football match in east Belfast dating back to 1897 has been brought to life with a stunning new colourised version appearing online.
The footage of Glentoran v Cliftonville was taken in Mersey Street and is thought to be the oldest available in the world of any football match.
It was captured by Frenchman Alexandre Promio for the Lumiere Brothers company at the time and later screened at the Belfast Empire to amazed crowds.

From the article - there is now even a colourised, speed-corrected version:
Comment: I am just looking at that skyline. Just to the right of the skyscrapers (tall buildings) in the horizon, is that a crane I can see? If so, that is likely Belfast docks, and that crane could well be the crane that built the Titanic. If so, then, wow!! I will likely accept this answer shortly. Just going to give it a bit more time.
Comment: So, the filming location being listed as London is in error then?  Wonder where they got that idea from?  Stranger still is the country of origin is listed as "France"...
Comment: @DarrelHoffman - The "France" is easy to explain in that the Lumière brothers were French...


Property initialization before constructor execution

Question: I am using an object initializer to create an object with a Position property like this:
var control = new HtmlTextbox(browser)
{
    Position = position;
};

As I know it's the same as:
var control = new HtmlTextbox(browser);
control.Position = position;

But I want to use initializated Position property in my constructor method.
Is there any way to do it without providing the Position as an argument for constructor?
Comment: No, there isn't. But if `Position` is so important for the initialization process you should provide a constructor that takes it anyway.
Comment: "_But I want to use initializated Position property in my constructor method_" ... Sorry didn't understand what you said at all
Comment: @yolosora How do you expect the constructor to set a value when it isn't provided the value to be set?
Comment: Looks like [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). What is your ultimate goal here?
Comment: How would you intend to take the code you know it is transformed into, `var control = new HtmlTextbox(browser);
control.Position = position;` and use the position in the constructor?
Comment: If you need the information available to the constructor, then *pass it into the constructor as an argument*. It doesn't make sense any other way.
Comment: @Servy I'm intrested if there is any ways to force constructor to set property value without puting that value into constructor paremeters.
Comment: if the value for position is a readonly or const, you can set the class Position member to that value in the constructor, or just use the literal value in the constructor, is that what you are looking for?
Comment: @Servy by magic!! >:D
Comment: @stackuser83 You cannot in fact set a `const` variable in a constructor.  You can only ever assign it when declaring the variable.  That's what it means for it to be constant.
Comment: @Servy: You can let the constructor see other data, but only if you have something global / static for it to see. You could set a public static property on the class from the outside, for example, before invoking the constructor, then read that. But that's pretty horrible...
Comment: @yolosora: what you want is possible, but only once. It's the default value
Comment: @Servy also consider things like static globals, depending on situation needs
Comment: @TimSchmelter yeah, i was using the default value before, but in some cases it provided wierd behaviour, so i wanted to make opportunity for  setting  propery value without global changes in my classes. Well, looks like that's impossible :(
Comment: @Servy you can declare a local scope variable as a const in a class constructor
Comment: @stackuser83 Yes, you can, but you could never assign the value of a variable to said local.
Answer: What you want to achieve is not possible.
It seems to me you want to make some parameters to the constructor optional. You may want to look into this pattern:
//Your constructor
public HtmlTextbox(TextboxConfiguration config)
{
    //config.Position
}

//A Transfer class
public class TextboxConfiguration
{
    public T Browser { get; set; }
    public T Position { get; set; }
}

//Your code
var config = new TextboxConfiguration
{
    Browser = browser;
    Position = position;
}
var textbox = new HtmlTextbox(config);

Answer: Another way you can approach this is using inheritance and initialize the value from there, as the most-derived class' constructor gets called last, but its values are initialized first.


Custom spray json format of Either[TimeSlot,DateSlot] stuck in some kind of type-inference loop

Question:
My spray json serialization does not seem to work, as my tests just keeps running, when i am trying to serialize an Either[TimeSlot, DateSlot] object to JsValue, and vice-versa when i am trying to parse a json string and convert it to Either[TimeSlot,DateSlot] object.

I have been reading some others with same issues, just with a Seq[Either[int,String], but the solution was hardly understood. Furthermore i have tried using the standardized Either json format, but problem is, that i need to define it with names and types, to make it more intuitive.

TimeSlot and DateSlot, is working fine.

<code>implicit object eitherDateOrTimeSlotFormat
  extends RootJsonFormat[Either[TimeSlot, DateSlot]] {

private val timeSlotTypeKey = "timeSlotType"
private val timeSlotValueKey = "timeSlotValue"

override def write(obj: Either[TimeSlot, DateSlot]): JsValue = obj match {
  case Left(timeSlot) ⇒
    JsObject(
      timeSlotTypeKey → JsString("timeSlot"),
      timeSlotValueKey → timeSlot.toJson
    )
  case Right(dateSlot) =>
    JsObject(
      timeSlotTypeKey → JsString("dateSlot"),
      timeSlotValueKey → dateSlot.toJson
    )
}

override def read(json: JsValue): Either[TimeSlot, DateSlot] = json match {
  case JsObject(fields)
      if fields.isDefinedAt("timeSlotType") && fields
        .isDefinedAt("timeSlotValue") ⇒
    fields("timeSlotType") match {
      case JsString(slotType) ⇒
        slotType match {
          case "timeSlot" ⇒
            Left(fields("timeSlotValue").convertTo[TimeSlot])
          case "dateSlot" ⇒
            Right(fields("timeSlotValue").convertTo[DateSlot])
          case _ ⇒
            throw DeserializationException(
              s"${json.compactPrint} did not match protocol"
            )
        }
      case _ ⇒
        throw DeserializationException(
          s"${json.compactPrint} did not match protocol"
        )
    }
}
</code>
}
It seems the tests is running forever, like if they were stuck in some kind of infinity-loop, and would of course be expected to just serialize, so my tests would assert the results.
Answer: This was not a programmatically error, it seems there is a problem with either Idea Intellij community, Sbt test or scalac. But I manually tested the code instead of running inside the test-environment, and everything was fine.
What i thought was Infinte-loop test


text input alignment wrong on mobile devices (possibly only iOS, haven't tried Android)

Question: I got 2 forms at my webpage and they are wrongly aligned on iOS devices (iPhone, iPad Safari). On computers it displays correctly (Windows and actually even Mac with Safari) but on mobile devices for some reason the inputs are not centered. Interesting thing is that it's not the whole form but just the input element.
1st picture is how it looks in developer tools in Chrome for example and 2nd picture is how it looks on iphone.
HTML
<form class="newsletter-form">

      <input id="newsletter" type="email" placeholder="email@example.com" />
      <button id="newsletter-send" type="button">chevron_right</button>

</form>

CSS
.newsletter-form-container {
  position: relative;
  width: 40%;
  margin: 0 auto;
}

.newsletter-form {
  position: absolute;
  height: auto;
  bottom: -38px;
  left: 0;
  z-index: 50;
  width: 100%;
  -webkit-appearance: none;
}

.newsletter-form input {
  border: none;
  border-radius: 15px;
  font-family: 'Open Sans', sans-serif;
  font-size: 18px;
  font-weight: 300;
  height: 76px;
  text-align: center;
  width: 100%;
  -webkit-appearance: none;
}

there is one more form and that one is positioned static and the inputs are display: block and also displays wrongly. Is this just some iOS thing that I can fix with -webkit something? Couldn't find the answer on google, so I'm trying here.
PS: sorry for different picture sizes, one was taken as phone screenshot and other one is snip from PC.
Answer: So, I found out that, iOS just adds padding to the input element by default and since the default setting for the input is box-sizing: content-box; all you have to do is:
a) set padding to the input element to 0 padding: 0;
or
b) set box-sizing: border-box; and then the padding goes inside the element basically.
final CSS for the element then looks like this:
.newsletter-form input {
  border: none;
  border-radius: 15px;
  font-family: 'Open Sans', sans-serif;
  font-size: 18px;
  font-weight: 300;
  height: 76px;
  text-align: center;
  width: 100%;
  -webkit-appearance: none;
  padding: 0;
}


Javascript set variable value in string

Question: var f = "world!";
var b = `hello  ${f}`;

b now == hello world!

I want function like this below set all value to string variable I know this function its fail and will give undefined f
Why i need this function... I will pass some data from PHP and I want in Javascript save this data
AND
Render some HTML with this data
var p =`hello ${f}`;
var b = 'world!';

function render(x,f){
console.log(x);
}

render(p,b);

Any ideas for function like this
Comment: A plugin that somewhat does what you're after: https://github.com/alexei/sprintf.js
Answer: This is impossible because of how JS works.
In theory, templates are very powerful in JS and you can use tagged templates and get really nifty stuff. However, in your case you want to not error in the case f is not defined.
The reference of f is evaluated before the function is - and when an unknown identifier is found JavaScript will throw a ReferenceError.
You can use a regular templating engine like Mustache though or use a simple helper function and a regex - just not with backtick template syntax.
Alternatively, pass a function in like:
var p = o => `hello ${o.f}`;
var b = 'world!';

function render(x,f){
    console.log(x({f}));
}

Or if you're really noughty, with and dynamic scoping can let you omit the o. before properties like libraries like KnockoutJS do.
Comment: MDN reference for the second bit?: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings

Javascript set variable value in string


Is ARIMAX suitable for time series with exogenous variables?

Question: I have the following data:
<code>Date          Fruit    Color    y
01/01/2018    apples   red      0.435
02/01/2018    oranges  green    0.234
...
01/01/2019    bananas  purple   0.234
</code>
I want to predict y for future dates. I have used linear and logistic regression but never worked with dates. So I have three "regressors": date, fruit and color. I have read about ARIMAX, but I don't quite understand if this is the technique suitable for this problem. I have also read about seasonality, but I am no expert in this topic, so how can I tell if my data has seasonality?
Comment: You would need to read at least one book or take at least one course on time series analysis.
Answer: Foe each fruit and color combination SEPARETLY you want to form a predictive model. Apparently you have no predictor/exogenous series thus ARMAX Becomes ARMA . Simply follow the paradigm presented here https://autobox.com/pdfs/ARIMA%20FLOW%20CHART.pdf and you will be good to go . If the software you select assumes 1) no deterministic structure OR constant parameters over time OR constant error variance over time be VERY wary !
If you have seasonality (which is to  be expected for fruits) the data will tell you that via analytics.
Comment: Why fruits and color can't be predictors?


Pegar sempre os três últimos caracteres sem saber o tamanho da String

Question: Eu quero pegar os três últimos caracteres de uma String. Exemplo:
String x = "OlaMundo"

Saída:

ndo

Eu até consigo fazer isso usando substring, o problema é que eu não sei o tamanho da String, eu não sei qual é a palavra.
Existe alguma forma de fazer isso sem saber o tamanho específico da String?
Comment: O tamanho da String é sempre determinável através do método `length()`
Comment: Pela *tag* usada anteriormente deve ler isto: https://pt.stackoverflow.com/q/101691/101. A sua pergunta é sobre Java e não tinha a *tag*. Não era sobre o Android Studio.
Answer: A forma mais básica seria pegando o tamanho:
x.substring(x.length() - 3);

O único problema é se a string for menor que 3, aí teria que verificar antes. Se for usar assim é mais simples que usar uma biblioteca. Se quiser fazer o tratamento aconselho criar uma função, assim:
class Program {
    public static void main (String[] args) {
        System.out.println(Right("OlaMundo", 3));
    }

    public static String Right(String text, int length) {
        if (text.length() <= length) return null;
        return text.substring(text.length() - length);
    }
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: com isso é possível eu fazer uma comparação com uma outra String? saída = and?
Comment: @LuccasBarrosTavares Comparação de `Strings` em Java é sempre como o método `equals` e não `==`
Comment: opa, acho que respondi na pressa rsrs, mas eae? como eu faria a comparação? to tentando comparar, mas sem sucesso
Answer: Se você não quiser se preocupar fazendo validação de tamanho da string, pode usar a classe StringUtils do pacote import org.apache.commons.lang3.StringUtils; (link da biblioteca), ficaria assim:
String x = StringUtils.right("MinhaString", 3);

Answer: Você pode pegar o tamanho dela usando
suaString.substring(suaString.length() - 3);

Você só terá problemas se sua String tiver menos que três caracteres
Como o método .length() retorna um número (tipo inteiro), você pode fazer algo do tipo para pode comparar antes de usar:
if (suaString.length() >= 3) {
//Implanta o código
} else {
System.out.println("Sua String é menor que três caracteres!")
}


Create an id array from mysql results

Question: How do I create an id array from a mysql query that only selects the ID.
So I want to get the array(id, id, id);
Here is my code:
$group = User::find($user)->group()->get(array('group.jid'));

The current return of the code:
[

   {
    "jid": 1
   },
   {
    "jid": 3
   }

]

What do I do so I can get jid: 1,3? So I can add it to a where in query?
WhereIn('id', $group)->get();

Comment: do you want those numbers in one array or in one string ?
Comment: Try this `User::find($user)->group()->lists('jid');` It should return an array with `jid`
Comment: @Altrim this is promising but I get `Column 'jid' in field list is ambiguous`. So I changed it to `groups.jid`. But still the same error.
Comment: @user3134069 I don't know how you've setup the relations but if you have everything setup correctly and if you read the docs on `selects` http://laravel.com/docs/queries#selects you'll see the `lists` method returns exactly what you want.
Comment: @Altrim I got it. Just added a select before the list. If you would make that an answer i would accept it.
Answer: To retrieve a list of column values you can use the method lists on the query
User::find($user)->group()->lists('jid');
I guess you get the error about the id being ambiguous because you have the same column name on the parent query so you have to explicitly select that.

Create an id array from mysql results


How to add function after the "return data"

Question: I have a problem where my program could run but some of the code didn't work. There was no error but it has a warning sign says that the "code after return will not executed". I would like a help on that. Thank you
@IBAction func newBookTapped(_ sender: Any) {
   guard let uid = Auth.auth().currentUser?.uid,
          let data = bookData() else {
      return
   }

   db.collection("new reading").document(uid).setData(data)
}

func bookData() -> [String: Any]? {
   guard let title = bookTitleTextField.text,
         let author = bookAuthorTextField.text,
         let summary = bookSummaryTextField.text else {
      return nil
   }

   let data: [String: Any] = [
      "bookTitle": title,
      "bookAuthor": author,
      "bookSummary": summary
    ]

    return data

    self.transitionToMenu()
}

func transitionToMenu() {
   let alert = UIAlertController(title: nil, message: "Book has been saved!", preferredStyle:  .alert)
   alert.view.alpha = 0.5
   alert.view.layer.cornerRadius = 15
   self.present(alert, animated: true)
   DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
      if let navController = self.navigationController {
          navController.popViewController(animated: true)
      } else {
          self.dismiss(animated: true, completion: {})
      }
   }
}

My program photo
Comment: Why are you using `[String: Any]` for your data?  As it's being harvested from a text field you know the dictionary's value type is a `String`
Answer: When making a return you end the function and go back to the call so there is no way that anything after a return in a function is being executed.
You have to put the self.transitionToMenu() before the return data.


Reusable Custom Control with Properties

Question: I have built a Custom Control Class that makes it much easier to build a side bar element in my html.
The problem I am running into is that when I set the "Text" property, the last time I set it gets used for every instance of the control on my page.  This is my first time doing this, so I'm assuming I'm missing something basic.
Namespace CustomControl
Public Class SideBarElement : Inherits Literal

    '''
    ''' Create Copyright Label
    '''
    ''' <remarks></remarks>
    Protected Overrides Sub CreateChildControls()
        MyBase.Text = RenderHTML()
        MyBase.CreateChildControls()
    End Sub

    '''
    ''' Set all copyright information.
    '''
    Public Shared Function RenderHTML() As String
        Dim val As String

        val = "
" & _
                  "
" & _
                  "
" & _
                 "
" & _
                 _Text & _
                  "
" & _
                  "
" & _
                  "
" & _
              "
"

        Return val
    End Function

    '''
    ''' Create Text Property
    '''
    ''' <remarks></remarks>
    Private Shared _Text As String = String.Empty
    Public Shadows Property Text() As String
        Get
            Return _Text
        End Get
        Set(ByVal value As String)
            _Text = value
        End Set
    End Property
End Class

End Namespace
Using this control is supposed to look like this.
<sidebar:SideBarElement ID="SideBarElement1" runat="server">
 Bla Bla
My Fun Content.</sidebar:SideBarElement>

Any help will be greatly appreciated.
Answer: Removing the Text and _Text properties solved the problem.  The literal control already has those properties built in, so I don't need to override them.
Namespace CustomControl
Public Class SideBarElement : Inherits Literal

    '''
    ''' Create Copyright Label
    '''
    ''' <remarks></remarks>
    Protected Overrides Sub CreateChildControls()
        MyBase.Text = "
" & _
                            "

" & _
                            "
" & _
                                Text & _
                            "
" & _
                      "
"
        MyBase.CreateChildControls()
    End Sub
End Class

End Namespace
Comment: Also, removing the "Shared" from the properties would have solved it just as well.

Reusable Custom Control with Properties


jQuery selector check for specific text(domain extension)

Question: How can I check if email input contains specific domain extensions like .com, .at, net...?
Is there a jQuery selector that can help me?
Email Address: <input type='text' id='txtEmail'/>

<input type='submit' id='btnValidate' Value='Validate Email' />

body
{
    padding: 10px;
    font-family: Arial;
    Font-size: 10pt;
}

$(document).ready(function(e) {
    $('#btnValidate').click(function() {
        var sEmail = $('#txtEmail').val();
        if ($.trim(sEmail).length == 0) {
            alert('Please enter valid email address');
            e.preventDefault();
        }
        if (validateEmail(sEmail)) {
            alert('Email is valid');
        }
        else {
            alert('Invalid Email Address');
            e.preventDefault();
        }
    });
});

function validateEmail(sEmail) {
    var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    if (filter.test(sEmail)) {
        return true;
    }
    else {
        return false;
    }

http://jsfiddle.net/kUxcz/422/
Comment: A typo, You have to pass event argument in `$('#btnValidate').click(function() {`
Answer: Try this by using negative value to split from last:
sEmail.split('.')[-1]

Answer: split it using
arr =  sEmail.split('.');

domain = arr[arr.length-1];

or
var domain = sEmail.substring(sEmail.lastIndexOf(".") + 1, sEmail.length);

Answer: Try this,
Demo
newemail = sEmail.split('').reverse().join('')
newemail = newemail.split('.')[0].split('').reverse().join('');

Comment: Why get the second element in the array? What if the email address is `email@example.com`?
Comment: what if id is firstname.lastname@example.com??
Comment: @RoryMcCrossan I have updated my answer please check it once.


Imagem (BITMAP) para String

Question: Nunca trabalhei com nada parecido e gostaria de inserir uma imagem numa base de dados e pelo que vi a melhor maneira é transformar uma imagem para string, ja procurei e encontrei algumas maneiras mas fiquei bloqueado. E a única maneira que tenho de armazenar imagens é numa pasta fora da base de dados, mas depois como pretendo fazer uma galeria nao tem como filtrar as imagens atraves do CarType.

public ActionResult Insert(Cars cars, HttpPostedFileBase photo)
    {
        string directory = @"~\Images";

        if (ModelState.IsValid)
        {

            int recordsCreated = CreateCar(
                         cars.Brand,
                         cars.Model,
                         cars.CarType,
                         cars.PlateDate,
                         cars.Image);
        }
        if (photo != null && photo.ContentLength > 0)
        {

            var fileName = Path.GetFileName(photo.FileName);
            photo.SaveAs(Path.Combine(directory, fileName));
            return RedirectToAction("../Rent/Gallery");
        }
        return View();

    }

Comment: Fala amigo, beleza? Seja bem vindo ao SOPT! Quando for fazer alguma pergunta aqui no site, dê preferência a postar seu código ao invés de disponibilizar as imagens. Assim podemos te ajudar de forma mais eficiente e sua pergunta será avaliada de forma mais positiva. Refatore sua pergunta colocando seus códigos e deixe apenas as imagens das telas se realmente for relevante para a pergunta, ok? Abraço!
Comment: Use um [`MemoryStream`](https://docs.microsoft.com/pt-br/dotnet/api/system.io.memorystream?view=netframework-4.7.2) para criar um `byte[]` a partir da imagem e então salve esse `byte[]` no banco de dados como um blob.
Answer: Você pode tentar converter para uma string do tipo Base64, neste caso tente isto :
using (Image image = Image.FromFile(Path))
{
    using (MemoryStream m = new MemoryStream())
    {
        image.Save(m, image.RawFormat);
        byte[] imageBytes = m.ToArray();

        // Convert byte[] to Base64 String
        string base64String = Convert.ToBase64String(imageBytes);
        return base64String;
    }
}

Imagem (BITMAP) para String


Why don't trusted host settings change in my site?

Question: I decided to change the URL of my Drupal site since it's not secure to include the IP address in it. So in my settings.php I have:
$settings['trusted_host_patterns'] = array(
  '^forms\.org$',
  '^www\.forms\.org$',
);

I cleared the cache using drush cr but the trusted host settings in the status report are still not updated. I even checked the permissions and everything is fine.
Comment: You are using probably the wrong settings.php or you have the statement twice in the settings.php file.
Comment: There's an easy way to find out - put some nonsense (i.e. invalid PHP) at the bottom of settings.php and reload the page. If it's not a 500, that settings.php isn't being read. Also check files that you're including via settings.php
Answer: However, the site loads when I use the old URL, which is the ip address one even after I commented it out
When you have commented the trusted host setting out the site works normally for all domains or IPs, you only get a warning if you open the status page.
whereas the new address says "files not found"
This error is not connected to this issue and it's unlikely a Drupal issue at all. Check the VirtualHost of the new address in your web server configuration. You can also test the new domain name with a static HTML file before you start to debug Drupal.
Comment: Thank you for your time to answer. I have "http://forms.org *.forms.org" in ServerAlias of drupal.conf, restarted the httpd and enabled it and still the same. I even tried with https.


How to interpret $x \in \mathbb{R}^n$?

Question: I see  $$ x \in \mathbb{R} ^n$$ in texts a lot for machine learning.  Can someone give me a good interpretation of it?  Specifically, is $n$ equal to the number of observations or number of predictors?  And also, does it suggest that all values within $x$ are real?
Comment: In plain(-ish) English, "x is an element of the n-dimensional real space". See here: https://en.wikipedia.org/wiki/Real_coordinate_space
Answer: In mathematics, a set of notations is used to condense and formalize statements and demonstrations. These notations have gradually emerged throughout the history of mathematics and the emergence of concepts associated with them.
In order to understand $x \in \mathbb{R}^n$, we need to understand the elements involved here. Let's start with the sets.
A set represents a collection of objects. The objects in the collection are the elements of the set. Here is a non-exhaustive list of some sets that you will find regularly:

$\mathbb{N}$, the set of natural integers.
$\mathbb {Z}$, the set of relative integers.
$ \mathbb {D}$, the set of decimal numbers.
$ \mathbb {Q}$, the set of rationals.
$ \mathbb {R}$, the set of real numbers.
$ \mathbb {R}^{+}$, the set of positive or zero real numbers.
$ \mathbb {R}^{-}$, the set of negative or zero real numbers.
$ \mathbb {C} $, the set of complex numbers.

So for example $2$ belongs to $\mathbb{N}$ as it is an integer, but also to $\mathbb{R}$.
Among the relations on the sets there is the notion of membership: $\in$ means "is an element of". Here are some examples:

$x \in \mathbb{N}$ means $x$ is an integer
$x \in \mathbb{Q}$ means $x$ is a rational
$x \in \mathbb{R}$ means $x$ is a real number

Now for the last part, $\mathbb{R}^n$. Here are some examples to understand it:

$(15) \in \mathbb{N^1}$
$(15, 8) \in \mathbb{N^2}$
$(0.75, 22.6, 12.3, 56.4, 102.5) \in \mathbb{R^5}$

Finally, a formal definition is that $\mathbb{R}^n$ consists of all column vectors with $n$ components, all real numbers.
Answer: $x$ is a vector of length $n$, all its elements are real numbers. Example of an element of $\mathbb{R}^4$ is $(-1, 0, 3, 2)$.
In general, the notation $x \in A^n$, means $x$ is a vector of length $n$, all its elements are from the set $A$.
For example if $4$ is the number of features and $x$ is a feature vector. We can write $x \in \mathbb{R}^4$.
Answer: In the notation of $x \in \mathbb{R}^n$, $n$ usually means number of 'predictors' or 'features' in machine learning context*. For example, in IRIS data set, we have 4 features, so, we can say, each data point is a 4 dimensional point, and we can write $x \in \mathbb{R}^4$.
*well, this is not completely true, because usually we add 1 intercept column to data.

The reason we need such notation is that, in many cases, say linear model, we will learn a parameter/weights $\beta$ also in (or related to) $w \in \mathbb{R}^n$.
For example, if we want build a linear model without intercept on IRIS data, the data matrix $X_{m \times n}$ can be $150 \times 4$, where we have 150 points, and 4 features. And the weights we are fitting is $4 \times 1$.
The model is $X\beta$, and the output will be $150\times 1$.

Note that, people also use $X_{n\times p}$ to represent data matrix, in that case, $n$ will be number of data and $p$ will be number of features.
Comment: Much depends on context, but in mainstream statistics, $n$ is much more likely to mean number of observations than number of predictors.
Comment: Thanks, so n is the number of predictors, not examples.  That helps.

How to interpret $x \in \mathbb{R}^n$?


cdk listbox with selection "forced by code" doesn´t show as selection "by hand"

Question: I have a cdk listbox that I use in cascade. So, I must have the possibility of controlling it by code, togheter with the graphical interface.
When I change the selected item (it´s not multiitems), the graphical interface doesn´t reflect the selected item - and the user must see what is selected.
I forked the cdk listbox in the stackblitz ( https://stackblitz.com/edit/ax5jwo-x5o644 ) that reflects the current behavior.
Clicking in the buttons below the listbox, I replicate the behavior that I have in my apllication (clicking in one of the buttons, I can "selected" the wished item "by code"). But then, the listbox doesn´t mark the "selected" item by this way, as when directly clicking over the listbox.
Answer: You should organize your functions as follows;
<code>  clickSprigatitoEvent() {
    this.starter = [this.starters[0]];
  }

  clickFuecocoEvent() {
    this.starter = [this.starters[1]];
  }

  clickQuaxlyEvent() {
    this.starter = [this.starters[2]];
  }
</code>
Comment: Thanks a lot, Mehmet S, I applied your suggestion and it worked !


DAW sounds and sound quality

Question: Background: I have a Roland FP10 digital piano that I'd like to use as a midi controller, ie connected to a laptop running a daw, then out to headphones/speakers.
I'm far from being a serious musician and really just want to play around with an expanded range of tones, rather than restricted to the few instruments built in to the Roland.
This might be a silly question but how does a daw generate its sounds? Does each daw come with its own "samples" of the instruments, with the quality of those sounds dependent on the particular daw? Or do all daws use the Windows GS wavetable synth (and if so, is it possible to replace those sounds with a better quality set)?
The only time I've done anything with midi was with a freeware Windows app (I forget the name), which used the GS wavetable, so sounded very poor,hence wondering if all daws do the same.
On a related note (pardon the pun), if I wanted additional tones, over and above the "general midi" instruments, what should I look for in a daw? Specifically I'm interested in 80s/90s pop/synth sounds.
Comment: Start at https://www.steinberg.net/cubase/ read all the info, watch all the videos. Then do the same for the other DAWs. You're starting from ground zero, you need to gain some background knowledge even if you never touch a DAW as you're researching. The GS Wavetable is to modern music production as the wax cylinder is to Dolby Atmos.
Comment: Which DAW? Protools? Cubase? Regardless, many such might "come with" some virtual instruments, but more can usually be downloaded and added. To your last question: I think the DAW and the "virtual instruments" are less linked than you imagine. DAW is to virtual instrument as workbench in the garage is to drill press: you can't use the tool without the workspace, but the end result has a lot more to do with the tool than the workspace.
Comment: I think it's actually a good question, but writing a good answer would take a long time. Try using a DAW and you'll see why.
Answer: Given how many DAWs there are, I wonder if I would be able to write something general enough to cover all DAWs, but let me try.
The main function of a DAW is to record, edit and mix audio and MIDI tracks. If you want your MIDI tracks to make actual sound, you need a virtual instrument. Some DAWs come with virtual instruments built in or bundled, some come with none. Then most of DAWs allow using plug in instruments in various formats, the most widespread being VST (or VSTi).
There are many kinds of virtual instruments, varying from synthesizers which produce sounds based on algorithms, samplers which focus on playing back samples, and virtual instruments attempting to emulate the sound of real instruments, typically basing on a large library of multiple carefully selected samples.
There is a lot of to choose from, and you can easily spend thousands on software and sample banks. Before you do, I would advise trying the free ones (some of which are very good!), to see what is available and learn what you want to do.
Comment: I'd also add, in case the OP needs it: These "virtual instruments" are just that, virtual. You can operate them using your actual physical keyboard as a "controller," though you could also get sound out of them with other interfaces, like programming in a pattern, perhaps using "piano roll" interface. It's in a sense coincidence that your Roland has its own sounds ("patches"); a MIDI controller just sends information like which key you pressed, how hard, and for how long. The virtual instrument can then use that info, so you can use the physical keyboard to "play" the virtual one.

DAW sounds and sound quality


Ordenação alfabética em ListView igual ao App Pessoas

Question: Estive pesquisando como fazer uma lista igual a lista de contatos do App People (Pessoas) do Windows 10 e encontrei um bom exemplo.
Porém o exemplo não implementa a ordenação alfabética que existe no app Pessoas (imagem abaixo).

Alguém sabe como implementar essa ordenação?
Comment: Se no exemplo citado a questão for somente a ordenação alfabética basta adicionar no final do construtor `public MainPage()` o seguinte `ContactList = new ObservableCollection(ContactList.OrderBy(c => c.FirstName).ThenBy(c => c.LastName));`
Comment: Mas e as Letras que encabeçam cada grupo ordenado, tpico (A) para os contatos que começam com **A**, (B) para os que começam com **B**, etc.?
Answer: O ruim de seguir exemplos prontos é que você esquece de consulta a documentação oficial que resolveria o problema mais rápido. (Caio muito nessas armadilhas)
Para criar uma lista semelhante ao App People (Pessoas) segundo a documentação é necessário utilizar um CollectionViewSource, segundo a Microsoft:
Se você precisar mostrar dados agrupados em sua exibição de lista, deverá associar a um CollectionViewSource. O CollectionViewSource age como um proxy para a classe da coleção em XAML e habilita o suporte a agrupamento.
Segue o código XAML com a implementação:
<Page.Resources>

    //Cvs recebera via code behind uma lista de objetos do tipo IOrderedEnumerable
    <CollectionViewSource x:Key="Cvs" x:Name="Cvs" IsSourceGrouped="True" />
</Page.Resources>

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <ListView Background="White" Foreground="Black" SelectionMode="None"
        ItemsSource="{Binding Source={StaticResource Cvs}}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <Grid Height="56">

                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="56"/>
                        <ColumnDefinition Width="Auto"/>
                    </Grid.ColumnDefinitions>

                    <Ellipse Grid.Column="0"
                             Margin="4"
                             Fill="LightGray"/>

                    <TextBlock Grid.Column="0"
                               Text="{Binding Path=ShortName}"
                               HorizontalAlignment="Center"
                               VerticalAlignment="Center"
                               FontSize="20"/>

                    <TextBlock Grid.Column="1"
                               Text="{Binding Path=FullName}"
                               VerticalAlignment="Center"
                               FontSize="16"/>

                </Grid>
            </DataTemplate>
        </ListView.ItemTemplate>
        <ListView.GroupStyle>
            <GroupStyle>
                <GroupStyle.HeaderTemplate>
                    <DataTemplate>
                        <Grid>
                            <TextBlock Text="{Binding Path=Key}"
                                       Foreground="Black" Margin="20"/>
                        </Grid>
                    </DataTemplate>
                </GroupStyle.HeaderTemplate>
            </GroupStyle>
        </ListView.GroupStyle>
    </ListView>
</Grid>

Classe Contatos:
public class Contact
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FullName
    {
        get { return FirstName + " " + LastName; }
    }
    public string ShortName
    {
        get { return FirstName[0] + LastName[0].ToString(); }
    }

    public string Inicial
    {
        get { return FirstName[0].ToString(); }
    }
}

Criando lista agrupada de Contatos:
public MainPage()
{
    this.InitializeComponent();

    var contactList = new List<Contact>
    {
        new Contact {FirstName = "Abravanel", LastName = "Santos"},
        new Contact {FirstName = "Barbosa", LastName = "Sousa"},
        new Contact {FirstName = "Bruna", LastName = "Maria"},
        new Contact {FirstName = "Bruna", LastName = "Lombardi"},
        new Contact {FirstName = "Carlos", LastName = "Alberto"}

    };

    var grupo = from act in contactList.OrderBy(c => c.FirstName).ThenBy(c => c.LastName)
        group act by act.Inicial
        into grp
        orderby grp.Key
        select grp;

    Cvs.Source = grupo;
}

Resultado:

Código Fonte:

https://github.com/rubgithub/ListGroup-UWP

Referências:

https://msdn.microsoft.com/pt-br/windows/uwp/controls-and-patterns/listview-and-gridview
https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh780627.aspx
https://msdn.microsoft.com/library/windows/apps/xaml/windows.ui.xaml.data.collectionviewsource.aspx


O que quer dizer isto "people[last, first]" em Python?

Question: É a primeira vez que vejo esta sintaxe people[last, first] com a virgula a separar os indexes no Python. Eu nem sei que estrutura de dados é people.
A pergunta é

What does this statement do:

for last, first in people:
    print(last, first, people[last, first])

Be sure you understand the structure of the dictionary and its keys.

Desta ultimo conselho parece que people é o dicionário, mas acho que com um normal dicionário esta sintaxe não é permitida, pois este código:
 person = {"Name": "Barack", "Surname": "Obama"}

 for last, first in person:
   print(person[last, first])

dá-me erro:

ValueError: too many values to unpack (expected 2)

People tem que ter 2 valores, pois esses são salvados em last e first...
Answer: Provavelmente, people é um dicionário que mapeia tuplas para outros dados:
>>> people = {("Obama", "Barack"):"USA", ("Roussef", "Dilma"):"BRA"}
>>> for last, first in people:
...   print(last, first, people[last, first])
...
Roussef Dilma BRA
Obama Barack USA

Caso não esteja familiarizado com tuplas, o tipo de dados tuple é como se fosse uma lista, só que imutável:
x = (10, 20, 30)
y = ()
z = (10,)   # Aqui a vírgula é obrigatória, pra não se confundir com 10 entre parênteses

O que torna as coisas confusas é que a sintaxe do Python aceita que você omita os parênteses caso a tupla tenha 2 ou mais elementos:
x = 10, 20, 30

Ou seja, people[last, first] é o mesmo que people[(last, first)].
Quanto ao tipo de dados people, eu deduzi que fosse um dict pois é a única maneira desse código fazer sentido. Arrays (listas) somente permitem que se indexe por número, não por tuplas, então people não é um array. Já um dict permite tuplas como chaves, e como o for aplicado a um dicionário itera sobre suas chaves, imaginei que essa fosse a estrutura de dados certa.
A propósito, você pode iterar sobre listas/tuplas e seus índices ou dicionários e seus valores usando enumerate e items, respectivamente:
>>> lista = [10, 20, 30]
>>> for indice, valor in enumerate(lista):
...   print(indice, valor)
...
0 10
1 20
2 30
>>> person = {"Name": "Barack", "Surname": "Obama"}
>>> for chave, valor in person.items():
...   print(chave, valor)
...
Name Barack
Surname Obama

Esses exemplos funcionam porque tanto enumerate quanto items retornam tuplas. Desse modo, pode-se fazer um destructuring assignment (ou destructuring bind) dos seus valores a um conjunto de outras variáveis:
x, y = 10, 20   # destructuring assignment: x recebe 10, y recebe 20

for x, y in [(10, 20), (30, 40)]:   # destructuring bind: para cada tupla t da lista
    ...                             #                     x recebe t[0] e y recebe t[1]

Por fim, chegamos à sua "estranha" mensagem de erro: "too many values to unpack" significa que você tentou fazer um destructuring bing onde havia mais valores do lado direito do que do esquerdo:
>>> x, y, z = 10, 20
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 2 values to unpack

>>> x, y, z = 10, 20, 30   # OK

>>> x, y, z = 10, 20, 30, 40
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 3)

E como isso aconteceu? Simples, no seu dict as chaves eram strings, e strings também aceitam destructuring bind!
>>> x, y, z, u, v = "teste"
>>> print(x, y, z)
t e s
>>> print(u, v)
t e

Como Name possui 4 letras, mas a tupla (last, first) só tem 2 elementos, o Python não teve onde colocar as duas últimas letras. Curiosamente, se suas chaves tivessem 2 letras, a mensagem de erro seria diferente:
>>> person = {"FN": "Barack", "SN": "Obama"}
>>> for last, first in person:
...     print(person[last, first])
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
KeyError: ('F', 'N')

Nesse caso ele estaria atribuindo a last o valor "F" e a first o valor "N". E é claro, como as chaves do dicionários são strings e não tuplas, a chave ("F", "N") não foi encontrada no dicionário...


Strategy for Improper Integrals Related to the Beta Function 2

Question: I am looking for the solution of the following integral

$$\int_0^1 y^k \log\left(1+\left(\frac y{1-y}\right)^a\right)dy,\quad a>0 $$

I really appreciate it if any one can help.
Answer: Changing variables $y = \frac{t^{1/a}}{1+t^{1/a}}$ the integral becomes, denoting $\alpha=\frac{1}{a}$:
$$
   \mathcal{I}= \alpha \int_0^\infty \log(1+t) \frac{t^{\alpha(k+1)}}{{(1+t^{\alpha})^{k+2}}} \frac{\mathrm{d}t}{t}
$$
the integral can be thought of as Mellin convolution of two functions $\int_0^\infty G_1(t) G_2(t) \frac{\mathrm{d}t}{t}$, where:
$$
    G_1(t) = \log(1+t)\qquad G_2(t) = \alpha \frac{t^{\alpha(k+1)}}{{(1+t^{\alpha})^{k+2}}}
$$
Use Plancherel theorem the integral $\mathcal{I}$ can be written as inverse Mellin transform of product of Mellin images of $G_1$ and $G_2$:
$$
  \mathcal{I} = \frac{1}{2 \pi i} \int_{\gamma - i\infty}^{\gamma + i \infty} \hat{G}_1(-s) \hat{G}_2(s) \mathrm{d}s
$$
where
$$
    \hat{G}_1(s) = \int_0^\infty t^{s-1} \log(1+t) \,\mathrm{d}t = \frac{\pi}{s} \frac{1}{\sin\left(\pi s\right)} \quad \text{ convergent for } -1 < \Re(s)<0
$$
$$
    \hat{G}_2(s) = \int_0^\infty t^{s-1} \alpha \frac{t^{\alpha(k+1)}}{{(1+t^{\alpha})^{k+2}}} \,\mathrm{d}t = \frac{\Gamma\left(1- a s\right) \Gamma\left(1+k + a s\right)}{\Gamma(k+2)} \,\, \text{ for } -\alpha(k+1) < \Re(s)<\alpha
$$
and $\gamma$ being an arbitrary real constant, subject to $0<\gamma<\min(1,\alpha)$:
$$
    \mathcal{I} = \frac{1}{2 \pi i} \int_{\gamma - i\infty}^{\gamma + i \infty} \frac{\pi}{s} \frac{1}{\sin\left(\pi s\right)}  \frac{\Gamma\left(1- a s\right) \Gamma\left(1+k + a s\right)}{\Gamma(k+2)} \mathrm{d}s
$$
The above integral is known as Fox H-function, using $\frac{\pi}{s} \frac{1}{\sin\left(\pi s\right)} = \Gamma(1-s)\frac{\left(\Gamma(s)\right)^2}{\Gamma(s+1)}$:
$$
  \mathcal{I} = \frac{1}{\Gamma(k+2)} H_{3,3}^{3,2}\left( 1 \left| \begin{array}{ccc}  \left(0,1\right) & \left(0,a\right) & \left(1,1\right) \\ (0,1) & (0,1) & (k+1, a) \end{array} \right. \right)
$$
For $a=1$ the answer is given as
$$
    \mathcal{I}(k,1) = \frac{H_{k+1}}{k+1}
$$
where $H_k$ is the Harmonic number, and for $a=2$, the answer is in terms of the Meijer's G-function:
$$
 \mathcal{I}(k,2) = \frac{2^k }{\pi  (k+1)!} G_{4,4}^{4,3}\left(1\left|
\begin{array}{c}
 0,0,\frac{1}{2},1 \\
 0,0,\frac{k+1}{2},\frac{k+2}{2} \\
\end{array}
\right.\right)
$$
which likely can be simplified further:
$$
   \mathcal{I}(k,2) = \frac{2}{k+1} H_{k+2} - \frac{4}{k+1} \Im \left( \Phi \left( \sqrt{2} \mathrm{e}^{i \pi/4}, 1, k+3 \right) \right)
$$
where $\Phi$ is the Lerch's transcendent.
Comment: @MhenniBenghorbal Thank you. What confused me for some time is that this H-function can not be evaluated as a sum over poles, rather one has to regularize it by introducing modifying the argument of H-function to be $z$, such that $|z|<1$ and then take the limit from inside the unit circle. I also wish there was a convenient way to evaluate the beast.
Comment: (+1) Nice answer. I went this way but I gave up. It is a lot of work.


Why the application crashes when I implements View.OnClickListener on the detail page of a list item?

Question: I am using a list view when I click on each item it shows a detail page. In the detail page I want to have some buttons and also an action-bar for implementing the menu access but the app crashes when I use: implements View.OnClickListener this is the code, can you please tell me what is the problem ?.
This is my Class AgendaDetail :
<code>import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.MenuItem;
import android.view.View;
public class AgendaDetail extends ActionBarActivity
    implements View.OnClickListener {

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

    View btnClick = findViewById(R.id.emergencycall);
    btnClick.setOnClickListener(AgendaDetail.this);
    View btnClick1 = findViewById(R.id.cancel);
    btnClick1.setOnClickListener(AgendaDetail.this);

    String selected_Device = getIntent().getStringExtra("device_name");

    // do whatever on this behalf of selected_Device String
}

public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        startActivity(new Intent(this, SettingActivity.class));
        return true;
    }
    if (id == R.id.action_menu) {
        startActivity(new Intent(this, MainActivity.class));
        return true;
    }
    return super.onOptionsItemSelected(item);
}

@Override
public void onClick(View arg0) {
    if (arg0.getId() == R.id.emergencycall) {

        //define a new Intent for the second Activity
        Intent intent = new Intent(this, EmergencyCall.class);
        //start the second Activity
        this.startActivity(intent);
    } else if (arg0.getId() == R.id.cancel) {
        //define a new Intent for the second Activity
        Intent intent = new Intent(this, Destination.class);
        //start the second Activity
        this.startActivity(intent);
    }
}
}
</code>
Comment: post your error log please
Comment: I am not able to see the error log ,  but as I remove the implements View.OnClickListener it works, the problem is with this line :( and without it I am not able to use buttons in the detail page !
Comment: Did you implement the `onClick(View)` function?
Comment: yes at the end of the code you can see it .
Comment: Anita mail, when you add line implements View.OnClickListener this line becime red? Simple move cursor on it and press add methods
Comment: add your imports to your question
Comment: Try casting View like  View btnClick = (View)findViewById(R.id.emergencycall);   and use View.onClickListener()
Answer: Try
<code>    Intent intent = new Intent(AgendaDetail.this, EmergencyCall.class);
    startActivity(intent);
</code>
instead
<code>        Intent intent = new Intent(this, EmergencyCall.class);
        this.startActivity(intent);
</code>


Index of twisted Dirac operator

Question: I do not understand a step in the proof of the Lemma 11.4.1 in the book "Analytic K-Homology" by Higson, Roe.
Let $S$ be a Dirac bundle over a closed manifold $M$ and $D$ the corresponding Dirac operator. Let $E$ be a Hermitian vector bundle over $M$. Then $S \otimes E$ is again a Dirac bundle, so let $D_E$ be the corresponding twisted Dirac operator.
Let $P \colon M \to M_n(\mathbb{C})$ be the projection-valued function determining $E$. Let $D_n$ be the operator $1 \otimes D$ on $H_n := \mathbb{C}^n \otimes L^2(S)$. Let $\chi$ be a normalizing function.

Then it is claimed that $\operatorname{Index}(\chi(D_E))$ equals the index of the operator $\chi(PD_nP)$ on the space $PH_n$.

What bothers me is that the operator  $PD_nP$ does not depend on the chosen metric / connection on $E$, whereas the operator $D_E$ does depend on it. And it is never mentioned in the book that the index of the twisted operator $D_E$ is independent of this choices.
Answer: Actually, the datum $P : M \to M_n(\mathbb{C})$ defines both a metric $(\cdot,\cdot)^P$ and a connection $\nabla^P$ on $E$:

If $P\xi$, $P\eta \in P(C^\infty(M) \otimes \mathbb{C}^n) = \Gamma(E)$, then $$(\xi,\eta)^P_x := \langle P(x)\xi(x), P(x)\eta(x)\rangle$$ for $\langle \cdot,\cdot \rangle$ the inner product on $\mathbb{C}^n$.
If $P\xi \in P(C^\infty(M) \otimes \mathbb{C}^n) = \Gamma(E)$, then $$\nabla^P P\xi := (1_{\Omega^1(M)} \otimes P) d P\xi,$$ where $d$ is the exterior derivative on $C^\infty(M)$ acting on $C^\infty(M) \otimes \mathbb{C}^n$ as $d \otimes 1_n$.

One then has that $PD_n P$ is, in fact, the twisted Dirac operator of the twisted spinor bundle $S \otimes E$, for $E$ endowed instead with the metric $(\cdot,\cdot)^P$ and connection $\nabla^P$. In particular, the fact that $\operatorname{Ind}(D_E) = \operatorname{Ind}(PD_n P)$ shows that $\operatorname{Ind}(D_E)$ is independent of the choice of metric and connection on $E$.
If you want another perspective on this issue, take a look at Chapter 11 of Roe's Elliptic operators, topology and asymptotic methods, which, in general, offers a very nice, concretely global-analytic complement to Higson--Roe.
So, one can define a continuous family of Dirac operators on a vector bundle $F \to M$ (e.g., your $F = S \otimes E$) as a one-parameter family $(g_t;c_t,(\cdot,\cdot)_t,\nabla^t)$, where for each $t \in [0,1]$,

$g_t$ is a Riemannian metric on $M$;
$c_t$ is a Clifford action, $(\cdot,\cdot)_t$ a Hermitian metric, and $\nabla^t$ a Clifford connection, making $F$ into a Dirac bundle over $(M,g_t)$;

for each $t$, then, let $D_t$ be the Dirac operator of the Dirac bundle $(F,(\cdot,\cdot)_t,c_t,\nabla^t) \to (M,g_t)$. One can then show that the $D_t$ satisfy elliptic estimates uniformly in $t$, and hence prove by functional-analytic arguments [Roe, Prop. 11.13] that $t \mapsto \operatorname{Ind}(D_t)$ must therefore be constant. In your particular context, $g$ and $c$ are constant, particularly since the spinor bundle $S$ is fixed, but given your vector bundle $E$, you'd need to construct $(\cdot,\cdot)_t$ and $\nabla^t$ to appy Roe's proposition. Then main ideas are these:

If $(\cdot,\cdot)_0$ and $(\cdot,\cdot)_1$ are two smooth metrics on $E$, then there exists a fibre-wise positive-definite (with respect to $(\cdot,\cdot)_0$) $T \in \operatorname{End}(E)$ such that $(\xi,\eta)_1 = (\xi,T\eta)_0$ for all $\xi,\eta \in \Gamma(E)$. Since $T$ is fibrewise positive-definite with respect to $(\cdot,\cdot)_0$, you can define $\log T \in \operatorname{End}(E)$ with $T_x = \exp((\log T)_x)$ for each $x$; then $(\cdot,\cdot)_t$ can be defined by $$(\xi(x),\eta(x))_{t,x} := (\xi(x),\exp(t(\log T)_x)\eta(x))_{0,x}.$$
If the metric $(\cdot,\cdot)$ is fixed, and $\nabla$ and $\nabla^\prime$ are two metric connections on $E$, then $M := \nabla^\prime - \nabla$ is a skew-adjoint $\operatorname{End}(E)$-valued $1$-form, and hence you can take $\nabla^t := \nabla + t M$.

These ingredients then allow you to define the corresponding continuous family of Dirac operators on $S \otimes E$.

Index of twisted Dirac operator


Ajax HTTP error occured. HTTP Result code: 200

Question: I get Ajax error when I click next button. You can test it here.
I have found out the problem. It is due to the custom module which I have made.
<!DOCTYPE html>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />

<?php

/**
 * Implements hook_block_info().
 *
 * This hook declares what blocks are provided by the module.
 */
function custom_module_block_info()
{
    $blocks['tag_cloud'] = array(
        // The name that will appear in the block list.
        'info' => t('Custom Moudle'),
        // Default setting.
        'cache' => DRUPAL_CACHE_PER_ROLE
    );
    return $blocks;
}

When I remove the first two line (Doctype and meta). It works fine. But If I remove first two lines. It doesn't work on IE. I had to insert these two statements to get it working on IE. Now If I keep these two lines, it causes Ajax error, and if not It doesn't work on IE.
Can anyone help?
Comment: Probably an echo in your code is creating the problem. Please check if there is any unnecessary echo
Answer: You can't just add arbitrary HTML at the top of a module file - Drupal runs through a process to theme the page, and you need hook into that.
You have a couple of options:

Override html.tpl.php in your theme, and add the tag to the  section manually. This is probably the easiest way.
Use drupal_add_html_head() in your module, e.g.
$tag = $element = array(
  '#tag' => 'meta',
  '#attributes' => array(
    'http-equiv' => 'X-UA-Compatible',
    'content' => 'IE=edge',
  ),
);
drupal_add_html_head($tag, 'mymodule:ua_compatibility');

Make sure you pick an appropriate hook to do this in (preprocess_page, etc), don't just add it to the top of the file or it won't work.


Which is a better option, OpenGL or a game engine for developing a game for the iphone or ipod touch?

Question: I am new to OpenGL ES, and I'm about to begin a 3D game for the iphone in which we are showing some car pursuit or racing. Is it possible just with the OpenGL ES or UIKit only, or do I have to use other tools for it? I am comfortable with UIKit but newer to OpenGL/OpenGL ES; which would be better to start this game?
Or should I use a game engine? If so, then which game engine would give us the 3D feeling, quality of images and motion, and rendering of the views with the sound effects?
Comment: I recommend openGL ES. Works great for me. Start from the EAGL demo code.
Answer: First of all, OpenGL, UIKit and Game Engines are very different from each other and specifically geared towards different uses.
OpenGL is a 3D graphics API. If you go with this, you'll have to write quite a bit of extra code, maybe some tools and a pipeline, to get a fully-featured game going. For example, collision systems and AI will be on you to develop.
UIKit is geared towards simple applications that don't require complex graphics. As the name suggests, it's best for applications that revolve around a UI.
Game engines usually include tools and pipelines, physics, audio and graphics engines, and possibly some other features such as simple AI/Navigation systems.
For your application, it sounds like you might be better off going with a game engine as it will get you up and running much sooner than if you try to develop those systems yourself. One popular engine is the Unity engine.
Comment: "OpenGL is a 3D graphics engine", probably "OpenGL is a 3D graphics APIs", to avoid confusion.
Comment: I used openGL for my 2D application.  It can be done.  It was quick to get off of the ground.
Answer: Actually you cannot compare OpenGL and game engines. OpenGL is just a graphics programming API, the very basic rendering stuff so to speak. If you are going for OpenGL you will have to code everything yourself, find out how to render complex effects like shadows, lights, as well as all game objects.
While a game engine is not a rendering engine either, a decent game engine already has all the rendering stuff covered and will manage your game objects (cars, houses, trees, etc.) for you. Depending on how good it is it may impose certain restrictions on what you can do with, but for a beginner using a game engine would certainly be the right start off. With a game engine you can just specify your game's behaviour on a pretty high abstraction level and won't have to bother about all the basics anymore.
Think of the difference between OpenGL and a game engine like the difference between getting a car building factory where you have to program all the machines yourself to get the desired car's part (OpenGL) and having all parts of the car ready for assembly already (game engine) and only having to put them together, maybe change the color here and add a gear there.
Answer: This really depends on how comfortable you are programming graphics code. OpenGL is easy to get used to if you have a strong C background, but if you're used to an object-oriented language like Java it can be difficult. As Dominic mentioned, you also have to write a substantial amount of code to get a good game off the ground. 3D adds a substantial amount of complexity over 2D.
I would suggest using a game engine such as Unity. I have a friend that writes iPhone games using it, and I've been very impressed with the results. It will import 3D models from Maya or 3D Studio Max directly and worry about texturing, materials, etc...
The only downside to this approach is that the game engine cannot be optimized to your specific needs. If there's a special OpenGL technique you want to use, or a very graphics-intensive scene you need to render, writing everything directly in OpenGL will give you more control and better results.
Answer:
HI
I am new to the opengles

You just answered you own question.  Game engine.
Cocos2D if you don't need 3D, there is a free 3D engine or two around but the commercial ones are really compelling.
Comment: You said Cocos2D if you don't need 2D.... don't you mean to say you 'if you don't need 3D?'


Multi-Tenant Application Owin External Logins

Question: I'm building a Multi-Tenant application and I'm having problems for specify multiple sub-domains for a Facebook and Google external login witn Owin and WIF.
The tenants are using a sub-domain for example:
<code>http://tenant-1.domain.com/
http://tenant-2.domain.com/
http://tenant-3.domain.com/
</code>
With Facebook and Google I can't specify multiple sub-domains for returns url of an application.
What are other solutions to this problem?
I thought about building a single login page, and after making the login to identify users, and perform the routing to tenant corresponding subdomain. The problem is that each tenant access his own database, and this solution involves having a common database of all users.
In short, I need to use external logins with a multi-tenant with a subdomain for each tenant. I do not think this problem is so rare, and the answers in stackoverflow are old, and no longer apply because have changed the application settings in Facebook and Google.
Comment: As far as Facebook goes, you can only specify one domain for Facebook login.
Answer: Finally, we adopt a solution-type like Single Sign On Server, which separates all user management from applications.
We recommend for such solutions, Identity Server v3 (https://github.com/IdentityServer/IdentityServer3).
Thanks!


C# WCF impersonation does not work with Directory.Exists of network direcotory

Question: I have WCF service, that checks if directory exists with Directory.Exists method (this directory is locate on network server). After that it does some random stuff. This service uses clients impersonation. I've tested it and with WindowsIdentity.GetCurrent().Name it shows the right user name. My client application is simple console application.
So my problem is, that when I call the service that runs on Computer A from computer A, using Credentials A, it works. If I call it from Computer B with credentials A or B (or any other for that matter), it doesn't work anymore. Directory.Exits returns false. But both, user A and B have all the permissions to access/modify this directory.
Please note that directory is locate on computer C. For debugging reasons I return the current user identity name and it's always the one that it should be. Obviously this credentials for Directory.Exits are not passed on as they should be if client application is located on the same computer as service is.
Any help or idea is most welcomed.
Comment: Is it windows service or IIS?
Comment: Service is runing on IIS.
Answer: Your expectation that credentials should be passed over second "hop" is wrong - server can't pass impersonation to yet another server using regular Windows authentication.
Why you see A->A->C working - your credentials are not leaving box where you originally signed in (A) and still have one "hop" to C to check file system there.
A->B->C case does not work because "hop" is used up for impersonation on B during A->B part and hence for B-> C your credentials no longer can be used.
Common fixes:

run directory access code under locally authenticated credentials on B (i.e. process credentials)
use Kerberos (How can I fix the Kerberos double-hop issue?)

Further reading - search for "NTML one-hop" or "double-hop authentication in Windows" to find articles like  http://blogs.msdn.com/b/knowledgecast/archive/2007/01/31/the-double-hop-problem.aspx
Answer: Then you can follow this (it's probably a Kerberos issue):
http://blogs.msdn.com/b/distributedworld/archive/2012/04/24/troubleshoot-kerberos-in-wcf.aspx
It's maybe a little bit old, but I remember having the same issue in the past.


Why does {$i \mid i \notin S_i$} lead to a contradiction when showing the set all subsets of a countably infinite set are uncountable?

Question: In the following explanation of why all subsets of a countably infinite set are uncountable, I am not understanding why the existence of {$i \mid i \notin S_i$} leads to a contradiction:

The set of all subsets of a countably infinite set is uncountable.
Answer: True. Assume the sets are countable and thus each set corresponds to a natural number: $S_i$. The set {$i \mid i \notin S_i$} cannot be any of the $S_i$ 's since it differs on whether $i$ is in the set of not.

I am wondering if here there is a certain way with which we associate a set with the natural number corresponding to it such that the set {$i \mid i \notin S_i$} leads to a contradiction somehow- must $S_i$ contain $i$? What would the construction of the $S_i$ formally look like? I am at a loss to understand how this leads to a contradiction, and would appreciate if someone could elucidate this.
Comment: All subsets of a countable set are obviously countable. What is not countable is _the set_ of all subsets of a countable set.
Answer: Let $S = \{x_1, x_2, \ldots\}$ be your countably infinite set. The $S_i$ aren't constructed. They are handed to you. They are, supposedly, a list of all the subsets of $S$. As in, whoever gave it to you is "hoping" that
$$
P(S)=\{S_1,S_2, S_3, \cdots\}
$$
(where $P$ stands for the power set.) Technically, the way this is set up, you are the one to put the indices on this list, and this gives you even more power. But it is not power we need, so we can leave the indexing up to whoever gave us the list.
Maybe $x_1\in S_1$, maybe not. Maybe $x_2\in S_2$, maybe not. It depends on the person who made the list, and how they made it.
But no matter who made the list, no matter how it's made, we can construct a subset of $S$ that's not in the list. That subset is $S_c=\{x_i\mid x_i\notin S_i\}$. Why is it not in the list? Well, $x_1$ is contained in either $S_1$ or $S_c$, but not in both. So those two sets are unequal. And $S_c$ can't be equal to $S_2$, because $x_2$ is contained in one of $S_2$ and $S_c$, but not in both. And so on. None of the $S_i$ can be equal to $S_c$, because no matter which $S_i$ you compare $S_c$ to, there is at least one element that's in one and not the other, namely $x_i$.
If someone then gives you a different list, in the hope that this time they have really nailed it down, then you will construct a different $S_c$, proving that this list is also deficient. No matter what list of subsets you get, you can always demonstrate that it is deficient (as long as the list is countable). You can always prove that it doesn't contain all subsets of $S$. And you do it with the same construction every time.
I don't see any contradiction here. Only a proof that any countable list is deficient. One could start by assuming that the list we have is indeed complete, and then construct the "counterwitness" $S_c$, and claim contradiction. But I personally don't like this extra layer of abstraction. This is a proof that any countable list necessarily must be incomplete. So that is how I will phrase the proof.
Comment: Who handed you the list? I like to think about a Math God, or maybe a Devil's advocate, trying as hard as they can to set you up to fail. They are giving you the most tricky list they can imagine. They will look into the future to see what proof you're going to write, and they will try their darnedest to give you a list that foils your attempt. It is your job as the proof writer to not give them any loopholes, and to demonstrate that there are no loopholes.
Comment: Is it correct to view this as diagonalization given a bijective mapping from $\mathbb{N}$ to each subset of $S$ ? for each element in this mapping, starting from the first, if the first set has the first element of $S, S_1$, we don't include it in this set we are constructing; if it doesn't have it, we include it- and going forth for all natural numbers, which  $i$ assumes? And then at the end, there is proof by contradiction because if this constructed set $S_c$ was mapped from natural number $j$, then if $S_c$ had $j$, $S_c$ doesn't have $j$, and if it didn't have $j$, then it has $j$?
Comment: Thanks; how do we know that $i$ should have been in the original set $S$? Also, do we lose generality by talking about natural numbers belonging to the $S_i$, or were you just saying that to illustrate a specific example?
Comment: @Shmuel Good question. I think I got my lines crossed for a second there. It seems like both I and your quote assume that $S = \Bbb N$. Which is the archetypal countably infinite set, but there is no reason for this assumption. I think the easiest way to fix this is to simply index all the elements of $S$. I'll get right on correcting this in my answer.
Comment: @Shmuel Yes, that's it.


Javascript Error on User sign up page

Question: I have suddenly started getting these errors on my sign up page:

Failed to load resource: the server responded with a status of 406 (Not Acceptable) .co.uk/misc/jquery.cookie.js?v=1.0
Uncaught TypeError: Object function (j,s){return new b.fn.init(j,s)} has no method 'cookie' form.js:69

Any ideas what might be causing this...
Comment: It's hard to say, without more info. What modules do you have installed? What scripts do you have running on your signup page? Where and when are you seeing these errors?
Comment: installed modules, http://wequest.co.uk/text.html, scripts: http://wequest.co.uk/scripts.png
Comment: there is only one custom module, and I disabled it, and still getting the error
Comment: read somewhere it might be a server issue with mod_security, so getting them to disable it.
Comment: Have you tried loading the page without scripts and enabling one by one to see which one it's coming from?
Comment: I think that is a good plan. Will try that.
Comment: I'm stupid. The error says it's coming from jquery.cookie.js. Do you know which module adds that file?
Comment: Did you check file permissions ?
Answer: This is due to using Autocomplete functions. Disable autocomplete module and Sure error will be gone.
Comment: Nope that wasn't the problem.
Answer: problem was rules for mod_security on the server being triggered.

Javascript Error on User sign up page


Model selection with nonlinear fitting? Statistical tests seem ambiguous

Question: I'm working on fitting an exponential model
$\mathrm{Flux} = A+Bt+F\left(\exp(t_0-t/T_r) + \exp(t-t_0/T_f)\right)^{-1}+...$
to astronomical data (a light curve).
$A$, $B$, $F$, $t_0$, $T_r$, and $T_f$ are all free parameters in the model.
I am trying to determine if a two-peak, three-peak, or four-peak model is appropriate for my dataset (with support from statistical tests). For each n-peak model (n=2,3,4) there is a corresponding exponential function in my model with it's own values of $t_0$ and F. I'm using nls in R to perform the fit.
The problem I'm having is that it is ambiguous whether a 3-peak or 4-peak model is preferential. I also looked at a 5 peak model just for curiosity's sake. So far I have looked at a likelihood ratio test, the AIC and BIC and none seem to put preference on one model versus the other.
Likelihood ratio test
Using the 2-peak model as my null hypothesis
3 peak: p=1.325564e-10
4 peak: p=2.220446e-16
5 peak: p=1.110223e-16
Here I see it as the 4-peak model being preferred over the 2-peak model, as the $H_0$ is rejected with a greater significance. But when you get p values this small, do differences this small really matter?
3-peak model as $H_0$
4 peak: 5.164630e-08
5 peak: 1.877226e-08
My interpretation: 4-peak model preferred.
4-peak model as $H_0$
5 peak: .01661512
My interpretation: 5-peak model preferred over 4-peak model.
AIC
2 peak:-58011.87
3 peak:-58053.36
4 peak:-58082.92
5 peak:-58087.11
My interpretation: 4-peak and 5-peak models equally preferred. But I would select the 4-peak model over the 5-peak model because it has fewer free parameters. But I question this because the difference between the AIC values (even between the 2-peak and 5-peak models) is so small.
BIC
2 peak: -57988.89
3 peak: -58025.27
4 peak: -58049.72
5 peak: -58048.80
My interpretation: 4-peak model and 5-peak model equally preferred. Again, I would select the 4-peak model over the 5-peak model because it has fewer free parameters (also the BIC value is slightly smaller)
I understand that when performing a LRT on nonlinear models it is preferable to use a non-parametric fit for your null hypothesis, however I have been unable to get that to work in R. I think my dataset may be too small (I have 95 data points).
So my question really boils down to: have I interpreted these statistical tests properly.
Also, are there any methods better than the ones I've already utilized to select one model over the other?
Just for some context, the reason the model selection is so vital is that the values for $T_f$ under the 3-peak versus 4-peak model are very different and point to two differing physical explanations.
Comment: A difference of 75 between the AIC values for the 2- & 5-peak models is not "small". Remember there's an arbitrary additive constant in the log-likelihood, so don't compare differences to the values for each model. @Nestor has adressed this point but I thought it worth emphasizing.
Answer: If you are trying to do model selection, I would definetly go for AIC and/or BIC.
The main reason for not looking at the likelihood-ratio tests that you gave in your example is that the p-values aren't comparable with each other (well...in general, p-values aren't comparable!): each time you calculate a p-value, you are not considering that there exist other possible models (e.g., when you perform the 2-peak model v/s the 3, 4, etc. separately) and therefore the null distribution that serves for the calculation of the p-value does not make sense for the problem at hand...the p-values are, therefore, meaningless for your problem!
Now, in general, to compare the AIC values in order to select a model, a difference of more than $2$ between the AIC values is usually denoted as "distinguishable models" by the AIC (see this wikipedia article on the AIC). Due to the low number of samples, however, I would recommend calculating the AICc instead of the "plain AIC", which is the "low-sample corrected" version of the AIC and is given by:
$$AICc=AIC+\frac{2k(k+1)}{n-k-1}$$
where $AIC$ is the AIC value that you have, $k$ is the number of parameters and $n$ is the number of datapoints. You can check out more about the AICc in the wikipedia article that I cited before. For further references, please check out the excellent textbook of Burnham & Anderson (2002).
Answer: Based on "Just for some context, the reason the model selection is so vital is that the values for Tf under the 3-peak versus 4-peak model are very different and point to two differing physical explanations."
Is there any theoretical or empirical evidence in your field that would favor one explanation (and hence, parameterization) over the other? Depending on your study, this could be an important criterion to consider, especially if you are interested in a more mechanistic interpretation of your model. This may be more favorable than leaving model selection only to goodness-of-fit measures (especially if you suspect the sample size was on the small side).


When I can and when I cannot use polar coordinates for a limit?

Question: I was doin the next exercise: ¿Is this function differential in (0,0)?
$$
\text { Let } f(x, y)= \begin{cases}\frac{x(1-\cos y) \sqrt{x^2+y^2}}{x^2+y^4}, & \text { if }(x, y) \neq(0,0) \text {; } \\ 0, & \text { if }(x, y)=(0,0) .\end{cases}
$$
So i just took the jacobian on (0,0) as a candidate for the differential:
$$
\begin{aligned}
& \frac{\partial f}{\partial x}(0,0)=\lim _{h \rightarrow 0} \frac{f(h, 0)-f(0,0)}{h}=0 \\
& \frac{\partial f}{\partial y}(0,0)=\lim _{h \rightarrow 0} \frac{f(0, h)-f(0,0)}{h}=0
\end{aligned}
$$
And the candidate jacobian is: (0,0), then I use the definition to see whether is differential or not:
$$
\begin{aligned}
\lim _{(x, y) \rightarrow(0,0)} \frac{x(1-\cos y) \sqrt{x^2+y^2}}{\sqrt{x^2+y^2}\left(x^2+y^4\right)} & =\lim _{(x, y) \rightarrow(0,0)} \frac{(1-\cos y)}{y^2} \frac{x y^2}{x^2+y^4} \\
& =\frac{1}{2} \lim _{(x, y) \rightarrow(0,0)} \frac{x y^2}{x^2+y^4}
\end{aligned}
$$
Then, we only have to check out what happens when we choose (t,0) and $(t^2,t)$ to see that we have two different limits, then is not differential in (0,0) BUT, if we use polar cordinates. we get:
$$
\frac{1}{2} \lim_{(x, y) \to (0,0)} \frac{r^3(\cos(\theta)\sin^2(\theta))}{r^2\cos^2(\theta)+r^4\sin^4(\theta)} = \frac{0}{2\cos(\theta)} = 0
$$
which tell us is actually differentiable in (0,0). Is this because it could be the case that cos(θ)=0?
thanks!
Answer: Note that by polar coordinates
$$\frac{r^3(\cos \theta \sin^2 \theta)}{r^2\cos^2 \theta+r^4\sin^4 \theta}=\frac{r(\cos \theta \sin^2 \theta )}{\cos^2 \theta+r^2\sin^4 \theta}$$
therefore we can't conclude limit is zero for the presence of the $\cos^2(\theta)$ term which goes to zero for $\theta \to \frac \pi 2$ which is consistent with the result you have found for the parametrization $(x,y)=(t^2,t)$ which correspond to a path with "vertical" tangent at $t=0$ (namely $y=\sqrt x$).

For the general question, after the standard check by direct substitution and continuity, we can always use polar coordinates for this kind of limits and it can be useful in two ways

to conclude for the existence of the limit when we obtain an expression in the form $r^af(\theta)$ with $a>0$ and $f(\theta)$ bounded;
to guess the problematic paths when we obtain an expression with $f(\theta)$ not clearly bounded, looking at the value of $\theta$ such that $f(\theta)$ diverges at infinity, as in the case in hand.
Comment: perfect, now i understand much better. Thanks


Expected value of a conditional Y given X, $E(Y|X)$ is or is not a constant?

Question: For a random variable $X$, there is an expected value $E(x)$. Since $E(X) = \mu \in \mathcal{R}$ where $\mu$ is a mean, and can be viewed as a constant. If this is true, then $E(E(X)) = E(\mu) = \mu$ by linearity and property of expectation.
However, my confusion sets in when I try to apply this logic in trying to understand the law of total expectation that is $E(Y) = E(E(Y|X))$. If I know that X is given, then it is appropriate to characterize $E(Y|X)$ as a constant, according to previous logic, such that $E(E(Y|X)) = E(Y|X)$, but $E(Y) = E(E(Y|X)) \neq E(Y|X)$
Can anybody give me a hand here? Thanks.
Comment: The outer "$E$" is taken with respect to $X$, so, although at the time of evaluating $E(Y|X)$ $X$ is a constant, at the time of evaluating the outer expectation in the expression $E[E(Y|X)]$, $X$ is not.
Comment: Another way to say this is that $\operatorname E(Y|X)$ is still a random variable and it is being averaged w.r.t. the marginal distribution of $X$
Comment: thanks a lot for the clarification
Answer: The conditional expectation $E(Y|X=x)$ is a function $g(x)$ of $x$.  For a fixed value $x$ this is not a random variable.
The notation $E(Y|X)$ (a slight abuse of notation since $X$ is not an event) is shorthand for $g(X)$.  This is a random variable and hence we can talk about $Eg(X)=E(E(Y|X))$ which according to the law of total exectation equals $EY$.


Ações Padrões do Windows Form [Minimizar - Maximizar - Fechar]

Question: Eu estou usando o visual studio - Windows Forms, e por padrão o form tem os botões de controle do form de "Minimizar" outro de "Maximizar" e outro para Fechar o form que é um "X",
Eu preciso manipular as ações dentro deles, mais especificamente quero que o programa ao minimizar de hide no form.
Algum conhece alguma forma de fazer isso ?
Answer: Você pode manipular o evento Resize:
<code>    private void Form1_Resize(object sender, EventArgs e)
    {
        if (this.WindowState == FormWindowState.Minimized)
        {
            this.Hide();
        }
        else
        {
            this.Show();
            this.BringToFront();
        }
    }
</code>
Caso você queira definir isso para todos os forms, você precisa fazer um form de base que deverá ser herdado pelos outros.
Comment: Perfeito, Muito Obrigado.


Is the limit of càdlàg functions càdlàg?

Question: Is the pointwise limit of càdlàg functions càdlàg? If not which are the weaker conditions to assure it? I cannot find a counterexample
Comment: That's haute mathématique ;)
Comment: I used to drive a Cadlag.
Comment: [Càdlàg](https://en.wikipedia.org/wiki/C%C3%A0dl%C3%A0g): "right continuous with left limits". Had not heard that one before.
Comment: glad that you got something new ;)
Answer: What about $$
f_n\colon x\in[0,2] \mapsto \begin{cases}
x^n & x \leq 1 \\
(2-x)^n & x > 1
\end{cases}$$
?
The pointwise limit is the function
$$
f\colon x\in[0,2] \mapsto \begin{cases}
1 & x = 1 \\
0 & x \neq 1
\end{cases}$$
which is not càdlàg.
Answer: A simple counter-example of a cumulative distribution function corresponding to when $\Pr(X_n =\frac1n ) = 1$:
$$F_n(x)=\begin{cases} 0   & \qquad x \lt \frac1n \\ 1 &  \qquad \frac1n \le x\end{cases}$$
so the pointwise limit is
$$F(x)=\begin{cases} 0   &  \qquad x \le 0 \\ 1 &  \qquad 0 \lt x\end{cases}$$
which is not càdlàg but càglàd (or làdcàg?) and so not the cumulative distribution function of a random variable almost surely $0$.
Answer: Take $$f_n(x)=\begin{cases} 0 & x<0\\ 1 & 0\le x<\frac{1}{n}\\ 0 & \frac{1}{n}\le x\end{cases}$$
The limit is $0$ everywhere, except $1$ at $0$.