Is the fixed point set of an involution on a topological manifold a submanifold?

Question: Let $f:X\to X$ be a homeomorphism of a topological manifold with $f^2=\mathrm{id}$.
Is each connected component of $\{x\in X \mid f(x)=x\}$ a topological submanifold?
Comment: In the case of a differentiable manifold $X$, I think you can use $T_pX\circ T_pX = T_p \text{id} = I$ and fiddle around with ranks. However, I don't immediately see an approach for topological manifolds.
Comment: Related: [Problem 44 in Eilenberg's list of open problems](http://www.jstor.org/stable/1969448?seq=14). Though the list is a bit old so I don't know if the question has been resolved.
Comment: @HSN:  One can do even better.  Equipping $X$ with a Riemannian metric, average over $f$ to obtain an $f$-invariant Riemannian metric.  It is easy to show that the fixed point set of an isometry is a totally geodesic submanifold.
Comment: related: http://math.stackexchange.com/questions/238939/is-the-fixed-set-of-a-smooth-involution-a-submanifold
Answer: No, the connected components of the fixed points of $f$ need not be a manifold. I can give an example of a homeomorphism $f\colon \mathbb{R}^4\to\mathbb{R}^4$ with $f^2=\rm id$, whose set of fixed points is connected (in fact, contractible), but is not a manifold.
Let $X=B\times\mathbb{R}$, where $B$ is Bing's dogbone space, and define $f\colon X\to X$ by $f(b,r)=(b,-r)$. This is clearly a homeomorphism with $f^2=\rm id$ and $\lbrace x\in X\colon f(x)=x\rbrace=B\times\lbrace0\rbrace\cong B$. It is known that $X$ is homeomorphic to $\mathbb{R}^4$, but the dogbone space $B$ is not a topological manifold. Also, $B$ is contractible, as its product with $\mathbb{R}$ is contractible.
Note: Bing's construction of the dogbone space was published in May 19571, and the fact that its product with $\mathbb{R}$ is $\mathbb{R}^4$ was demonstrated in 19592. Eilenberg's list of open problems linked to by Willie Wong in the comment to the question dates back to April 19493. So, it is entirely plausible that the problem was indeed open when Eilenberg published his list.

1 A Decomposition of $E^3$  into Points and Tame Arcs Such That the Decomposition Space is Topologically Different from $E^3$, R. H. Bing, Annals of Mathematics Second Series, Vol. 65, No. 3 (May, 1957), pp. 484-500. (Link)
2 The Cartesian Product of a Certain Nonmanifold and a Line is $E^4$, R. H. Bing, Annals of Mathematics Second Series, Vol. 70, No. 3 (Nov., 1959), pp. 399-412. (Link)
3 On the Problems of Topology, Samuel Eilenberg, Annals of Mathematics Second Series, Vol. 50, No. 2 (Apr., 1949), pp. 247-260. (Link)
Comment: Ah, beautiful! I've been searching for constructions like this and wasn't looking at the right place.
Comment: And lo, it was already mentioned in the [MathSciNet review](http://www.ams.org/mathscinet-getitem?mr=107228) that one of the corollaries of Bing's construction in your item 2 is precisely the answer to this question. Bravo!


Add icon to module's menu item in Administration menu

Question: I've searched for a bit and I haven't found a solution to my liking: I want to avoid adding more modules to the project.
I'm very new to Drupal, so I have minimal knowledge on that matter. I have this project which somebody else has made. They created a module which adds a menu item on the Administration menu. What this module doesn't do, is add an icon to the menu item, which makes it look bare.
I want to add a custom icon I've made next to the menu item text. The reason it needs to be a custom icon and can't be fontawesome (or anything of its liking), is because it has to be a variation of the site logo.
Is there a way to accomplish this without adding more modules to the project, or is adding more modules the only way?
It's Drupal 8 with Lightning on Debian 9 with Apache2.4 and PHP7.2.
Comment: Is it a sub menu item? Or is it a toolbar item? Where exactly is that item located?
Comment: @leymannx It's a toolbar item. Located just before help. Not a sub menu item.
Answer: I figured it out. Now, this might not be the very best way to solve it, and some things should probably be changed, but this will be fine for now. Let's assume the module name is pizza.
First, create a directory called css. Inside this folder, create a css file with the name of the module. In this case it would be pizza.css.
Since there needs to be an icon next to the module's menu item title on the administration menu, this is the CSS we'll need (or similar):
.toolbar-icon-pizza-main::before{
    background-image: url('../../../../../sites/default/files/pizza-icon.png');
}

Second, we will need a libraries file in the module's root (where pizza.info.yml is located); call it pizza.libraries.yml. Inside this file write something along the lines of this:
toolbar-icon:
  version: 1.0
  css:
    base:
      css/pizza.css: {}

Here, base probably should be changed to theme, since this is an aesthetic to the module.
Third, move into pizza.info.yml, we need to include the library we made into the module. Add this to the bottom:
libraries:
  - pizza/toolbar-icon

Fourth, move into pizza.module, where we're going to add this:
/*
 * Implements hook_toolbar_alter()
 */
function pizza_toolbar_alter(&$items) {
  $items['administration']['#attached']['library'][] = 'pizza/toolbar-icon';
}

This fixed it for me.
Source:
https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module
Comment: I'm unsure if this should be an edit to the answer or not, but the css directory should be in the module's root as well.


Can someone explain this proof that each transposition changes the parity of a permutation?

Question: Looking at: http://dogschool.tripod.com/permutation.html
It states:

Let the following represent an ordering of the n numbers 1 to n.
a1 a2 . . . x . . . y . . . an-1 a1
Each number in the string of numbers can affect the grand total in two ways. First when it is the number we're using to count how many smaller numbers are beyond it and second when it is one of the numbers "beyond" whatever number we're using to count how many smaller numbers are beyond.
Now if we exchange elements labeled x and y how will the parity of the grand total change? Let's break up the numbers into three groups.
<code>1. The numbers either before both x and y or after both x and y
2. The numbers between x and y.
3. x and y.
</code>
The same numbers will be before and after the numbers in group 1 so their contribution to the grand total will not change. The numbers in group 2 will each contribute to the grand total twice once for the change in x's position (either they were less than x or x was less than them.) and again for the change in y's position. Thus their total contribution will be to change the grand total by an even number. This will not affect the parity of the permutation. Finally, x and y switching places will add or subtract 1 from the grand total depending on whether x or y is greater. Thus the parity of the grand total (odd or even) will change.

I did not undertstand this so I tried an example:

As described in the proof the numbers before and after the two numbers that swapped have not changed. However, the proof states that the number between the swapped numbers should change by an even number, however they do not, they changed by 1. The proof also states that the numbers swapped should increase or decrease by 1, which they have not.
To be clear I am asking about this specific proof, and trying to understand this proof. I do not want some other proof proving the same thing.
Answer: Where they talk about the contribution of a number, they don't mean the contributions as you've written them down and added them up in the bottom rows. Where it says "The numbers in group $2$ will each contribute to the grand total twice", one of these "contributions" is listed, in your sum, under that number in group $2$, and the other "contribution" is listed under the first of the swapped elements, i.e. in the third column. The only contribution that they count as a countribution of $x$ and $y$ themselves is the one that you count in the third column according to whether the number in the sixth column is lower, and that "contribution" has indeed changed by $1$.


HTML5 page with Playframework2.0.2

Question: Trying to include simple HTML5 page instead of scala templates..
For this I have tried creating a simple HTML page in my views, But how can I redirect my app to this page ?
What I am trying to achieve is to use HTML pages as my UI and Play controller for POST and GET JSON data to the ui pages which will allow me to decouple UI
Answer: See the routes file, on the end there is route for assets - static files like CSS, JS and images placed in public directory.
You can create similar folder for your static HTML files and add a separate route(s) the same as for assets.
You can also add your file into the views as ie. static_html5.scala.html and just don't add any scala functions to it (just to remember leave first line of the file empty) In such case only thing you'll need to remember is to replace any @ to @@ (ie.: My email is bob@@example.com )
In such case you can render it as a common template without params:
public static Result index(){
    return ok(static_html5.render());
}

Comment: Thank you so much.. Why cant I see my html pages in controller ? I need to execute `play run` ofttn for IntelliJ to identify the pages.
Comment: Yes, Play **must** be running **all the time** to compile freshly added/changed views. Additionally you need refresh the browser. You can use also `tilde-dev` mode, in such case Play will compile it asap: `play ~run`
Comment: Thanks for the info provided it is very helpful, I have achieved the same by placing the html page in `views`.  am facing problem if I try to place the static `pages` seperately out of `views`, could you provide your sample `conf` to set the pages outside the `views` also is it must to end the pages with `.scala` ?
Comment: When placed outside the views as a static files it doesn't need to have `scala` in the name. Check docs for working with public assets: https://github.com/playframework/Play20/wiki/Assets

HTML5 page with Playframework2.0.2


Load Balancing and Securing Server for Custom TCP Protocol on EC2

Question: We've developed a custom TCP protocol to interface with iPhone clients over sockets and I am looking to layout our production server.  We'll be running our server written in erlang on a single debian EC2 instance as well as most likely running mysql on a separate instance (I'm guessing this would be recommended?).
I'm looking to secure and load balance connections to our TCP server and was looking at EC2's ELB, HAProxy, LVM and nginx.  nginx seems to be http only, and since we're using a custom protocol I was looking for some input on the design of such a system.  I am also wondering what the implications of router/firewall blocking on cellular networks ISPs will be.
My current design idea would be putting everything over port 80 to ELB and route this to the TCP server. I'm not completely sold on ELB, so I was wondering:

What other options are out there for non http reverse proxy,
Can SSL be run on the reverse proxy or does this also need to be run on the TCP server
Any recommendations for firewall/router workarounds for cellular networks other than going over port 80.
Answer: Well, neither haproxy or ELB are HTTP only; they'll both do arbitrary TCP connection proxying.  But why would you possibly want a proxy?  Just run an L3 load balancer instead; it's much cleaner.  It might not work in AWS, but I'd call that a limitation of AWS.
Comment: Sorry for the delay guys, I finally got a chance to play around with some stuff on the server. I was looking to proxy for an added level of security, but I guess there's really no point for that (I'm thinking I dont want to put apache on the net straight, but that doesnt fit in here). I looked into L3 balancer (I'm not a much of hardware esp in enterprise situations). I'm thinking this is a cisco box? It sounds much more sexy than what I've got right now, so I'll have to look into that later when funds are looking better (and hopefully off ec2). Thanks!
Comment: No, you can do L3 load-balancing using [Linux Virtual Server](http://www.linuxvirtualserver.org/), it works great and is free.
Answer:
HAProxy and ELB seem to both fit your needs well.
Adding stunnel to your HAProxy solution would accomplish this, as should ELB (though it's not completely clear if the SSL offloading works on raw TCP connections).
Depends on the cellular networks you need to work with, but I'd say avoid port 80 - some of them try to proxy those requests.  If anything, run over 443 with your SSL stream - that should function for carriers with decently limited traffic interference.
Comment: Great! I got a chance to play around with ELB, looks like that's easier to setup but it seems to be pinging/connecting to my server ever so often which is a pain (prally design issue on my side). Great call on port 443, def going to use that. HAProxy + stunnel was what i was thinking if not using ELB, so great suggestion! I guess my only follow up is the suggestion from above, as to whether I really need a proxy (for added security?) or whether load balancer is enough. I guess if I don't go with ELB, HAProxy will do both for me. I'm totally new to this level of server, thanks for you're input!


I got a multiple buttons event handler here But I need to target only one button if it was clicked how do I do that?

Question: <code>    private void btnCodeAkas_Click(object sender, EventArgs e)
    {
        tmrTimerAkas.Start();
        tmrTimerTwoAkas.Start();

    }
</code>
But I need to target only one button if it was clicked how do I do that?
Comment: Perhaps look at the `sender`?
Comment: Compare `sender` against the buttons you have with an `if()` statement?
Comment: You've got into the event trap, put your code into a method and invoke it from only buttonClick events of buttons you want.
Comment: Is there more code?  If not, then why have multiple buttons fire that event?
Comment: @Idle_Mind, Why? Because lazyness :)
Comment: Does this answer your question? [How to create an event handler for multiple buttons?](https://stackoverflow.com/questions/21570994/how-to-create-an-event-handler-for-multiple-buttons)
Answer: well you can cast your sender to Control object so you can get the name of the button then you write your conditional logic.
<code>       private void button1_Click(object sender, EventArgs e)
    {
        var control = sender as Control;

        if (control.Name == "button1")
        {
            Console.WriteLine($"Clicked {control.Name} button");
        }
        else if (((Control)sender).Name == "button2")
        {
            Console.WriteLine($"Clicked {control.Name} button");
        }
    }
</code>


Running createIPA task following Xcode 10 upgrade

Question: Following installation of latest Xcode, running gradle task createIPA to create my iOS package with robovm produces error

No SDK found matching version string 11.4
Answer: Following the Xcode upgrade I just:

Started Xcode
Updated 12.0 in robovm.xml in my ios module

Ran createIPA gradle task again. Problem solved.


Implicit intent - No suitable recipient

Question: What would happen if there are no available applications (satisfying the intent criteria) that can take up a particular implicit intent ?.
If there are multiple apps available that can take up, a choice is given to the user..I am interested in the other way around.
Can anyone provide their input ?
Answer: An ActivityNotFoundException will be thrown, that's why if you are not using a system app, you should always put your intent calls in try catchs
Answer: From memory I think an "ActivityNotFoundException" is thrown when you attempt to start the activity e.g.
<code>Uri marketUri = Uri.parse( "market://details?id=" + packageName);
Intent marketIntent = new Intent(Intent.ACTION_VIEW, marketUri);
try {
   startActivity(marketIntent);
} catch (ActivityNotFoundException ex) {
   // Google market not installed...
}
</code>

Implicit intent - No suitable recipient


Implementing my own getline function

Question: Good day,
I'm trying to write a get line function that will take user input and stored it into a character array. The code below is what I've come up with so far but unfortunately my code just sits at the command prompt. I'm not sure what's wrong, I've tried numerous approaches but I can't seem to get it to work. Any help would be appreciated, thank you in advance.
In addition; here's the code for the overloaded function +=;
void MyString::operator +=(char addend)
{
    reserve(getLength() + 2);
    char ch[1] = { addend };
    strncat(sequence, ch, 1);
};

My getline function:
istream& getline(istream& ins, MyString& target)
{

    char ch = 0;
    istream& get(char& ch);
    while (ins && ch != '\n')
    {
        istream& get(char& ch);
        target += ch;
    };
    return ins;
};

Comment: What do you think `istream& get(char& ch);` is supposed to be doing?
Comment: You call functions correctly in other parts of your code. What's so different about `get`?
Comment: I thought it polled a individual character from the istream
Comment: No, it actually declares a function. What you should be doing is **calling** the function like this: `ins.get(ch)`.
Comment: But I think the real question is *why* are you performing input like this?
Comment: I'm not sure what you mean by why?
Comment: Ideally one would create an overload of the extractor for the class. If you need to read a line of input from the stream, use `std::getline()`. You should have an `std::string` data member within the class as well to extract the line into.
Comment: I see, the code I am developing is for a project to create our own string class. My professor explicitly stated not to use the built-in string class.
Comment: @0x499602D2 The whole point of the question is that he can't / doesn't want to use `std::getline()`.
Comment: I guess I could use the get line function, but in the handout he stated:

"For the getline function, you may also want to read one character at a time. You may use the following istream member function get in your program.
istream& get ( char& c ); // Extracts a character from the
                          // stream and stores it in c."
Answer:  istream& get(char& ch);

That line will declare a function.  You need to call a function:
while (ins.get(ch) && ch != '\n')
{
    target += ch;
}

Comment: Thanks, I got confusing when I was looking up the get function.

Implementing my own getline function


what DataAnnotation to make an SQL Identity column?

Question: I have the following in my class and need to know how to modify the DataAnnotation to make it an identity column
public class Item
{
    public Int16 ItemID { get; set; }
}

The goal is to have the EF5.0 equivalant of the SQL
ItemID smallint IDENTITY(0,1) NOT NULL,

Answer: You can use DatabaseGenerated attribute with DatabaseGeneratedOption.Identity. You can find more details about configuring EF with attributes here http://msdn.microsoft.com/en-us/data/jj591583 and about DatabaseGnerationOption enum here:
http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.schema.databasegeneratedoption.aspx. You can also configure your model with Fluent API - here are some examples http://msdn.microsoft.com/en-us/data/jj591617
Comment: Thanks I had found the first two links but there was such little information on them about what the .Identity does I was not sure if it would set the seed and intervalt to 0,1 like I want.


Show that there are no functions $f: \mathbb R \to \mathbb R$ which have the intermediate value property and $f(f(x))=\cos^2(x)$

Question: Show that there are no functions $f: \mathbb R \to \mathbb R$ which have the Darboux property (the intermediate value property) and $f(f(x))=\cos^2(x) ; \  \forall \ x\in \mathbb R$.
I guess that I'd have to use the fact that $f(f(x)) \in [0,1]$, but I'm not sure how
Comment: If you google "f(f(x)) math overflow" you might get some hints.
Comment: Ok I give up >_<. Here are the few things I found in case it rings a bell: $\forall \ x\in \Bbb R,f(f(x))=\cos^2(x)\space\space\space\space\space\space\space\space\space\space$

$\forall x \in \Bbb R, f(f(x))\in [0,1]\space\space\space\space\space\space\space\space\space\space$

$\forall x \in \left[0,\cfrac{\pi}{2}\right], f(f(x))=\cos^2(x) \Leftrightarrow \cos(x)=\sqrt{f(f(x))} \Leftrightarrow x=\arccos \left(\sqrt{f(f(x))}\right)\space\space\space\space\space\space\space\space$

So $f$ is injective on $\left[0,\cfrac{\pi}{2}\right]$
Comment: $\forall x \in \Bbb R, \cos^2(f(x))=f(f(f(x)))=f(\cos^2(x))\space\space\space\space\space$

$f(1)=\cos^2(f(0))\space\space\space\space\space$

$f(0)=\cos^2\left(f\left(\cfrac{\pi}{2}\right)\right)$
Comment: did you find out how in the meantime? i completed my answer, let me know your thoughts
Answer: ok so i took this with me on easter and found a proof. i'll post more details later, first only a few hints to get you started. as you already found out, $f|_{[0,\frac{\pi}{2}]}$ is injective; actually, for each $n\in\mathbb{Z}$, $f|_{[n\frac{\pi}{2},(n+1)\frac{\pi}{2}]}$ is injective. using the IVP, show that each $f|_{[n\frac{\pi}{2},(n+1)\frac{\pi}{2}]}$ is continuous, hence $f$ must be continuous everywhere. show that without loss of generality we can assume $f\ge0$ and $f(-x)=f(x)$. show $f$ is periodic with period $\pi$ (so $f$ attains its maximum and minimum at the endpoints of each $[n\frac{\pi}{2},(n+1)\frac{\pi}{2}]$) and a few more things to derive a contradiction using $x=0$ and $x=\frac{\pi}{2}$. you may or may not need the fact that $f$ has exactly one fixed point $x^*$, and $x^*\in(0,1)$, and $x^*$ is also a fixed point of $\cos^2(x)$
EDIT
A solution is a function that satisfies andreea's problem (we want to prove that no such exists). Let $f$ denote any solution, unless stated otherwise. IVP stands for intermediate value property, and monotone refers to either monotonically increasing or monotonically decreasing.

Lemma 1 Let $J$ be any set, $I\subseteq J$ any subset, and $f:J\rightarrow J$ any function. Then
$$(f\circ f)|_I \quad \text{is injective} \quad \Longrightarrow \quad f|_I \quad \text{is injective.}$$
Proof Suppose $(f\circ f)|_I$ is injective, $x,y\in I$, and $f(x)=f(y)$. Then $f(f(x))=f(f(y))$, hence $x=y$.

Take $J=\mathbb{R}$, $n\in\mathbb{Z}$, $I=[n\frac{\pi}2,(n+1)\frac{\pi}2]$. Since $f\circ f=\cos^2$ and $\cos^2|_{[n\frac{\pi}2,(n+1)\frac{\pi}2]}$ is injective, this yields:

Proposition 1  $f|_{[n\frac{\pi}2,(n+1)\frac{\pi}2]}$ is injective.

$\quad$

Proposition 2  $f|_{[n\frac{\pi}2,(n+1)\frac{\pi}2]}$ is strictly monotone.
Proof Suppose $f(n\frac{\pi}2)<f((n+1)\frac{\pi}2)$. We'll show that $f|_{[n\frac{\pi}2,(n+1)\frac{\pi}2]}$ is strictly monotonically increasing.
Take $x,y\in(n\frac{\pi}2,(n+1)\frac{\pi}2)$ such that $x<y$. Suppose $f(x)>f(y)$. Note that
  $$ f(x)>\max\{f(n\frac{\pi}2),f(y)\}\quad\text{or}\quad f(y)<\min\{f(x),f((n+1)\frac{\pi}2)\} $$
  where the left equality holds whenever $f(n\frac{\pi}2)<f(x)$, and the right one whenever $f(y)<f((n+1)\frac{\pi}2)$ (there's some overlap, but this has no influence on the proof). In the 'left' case, by the IVP, $f$ must touch $\max\{f(n\frac{\pi}2),f(y)\}$ at least twice on $[n\frac{\pi}2,y]$, in contradiction to injectivity. In the 'right' case, the same applies to $\min\{f(x),f((n+1)\frac{\pi}2)\}$. Hence necessarily $f(x)<f(y)$.
Analogously, if $f(n\frac{\pi}2)>f((n+1)\frac{\pi}2)$ then $f|_{[n\frac{\pi}2,(n+1)\frac{\pi}2]}$ is strictly monotonically decreasing.

$\quad$

Lemma 2 Let $a,b\in\mathbb{R}$, and $f:[a,b]\rightarrow\mathbb{R}$ be a strictly monotone function with the IVP. Then $f$ is continuous.
Proof Without loss of generality, assume $f$ is increasing; otherwise take $-f$, since 'taking the negative' doesn't influence continuity. Choose $x\in[a,b]$ and $\epsilon>0$. Note that, by the IVP, there exist $x_-,x_+\in[a,b]$ such that
  $$ f(x_-)=\min\{f(x)-\epsilon, f(a)\} \quad \text{and} \quad f(x_+)=\min\{f(x)+\epsilon, f(b)\}$$
  Set $\delta=\min\{|x-x_-|,|x-x_+|\}\backslash\{0\}$ (i.e. we ignore the $x_-$ or $x_+$ term if $x_-=f(a)$ or $x_+=f(b)$, respectively). Then, for any $y\in(x-\delta,x+\delta)\cap[a,b]$, by monotonicity,
  $$ f(x_-)\le f(y)\le f(x_+) $$
  hence
  $$ f(x)-\epsilon<f(y)<f(x)+\epsilon\text. $$

Take $a=n\frac{\pi}2$, $b=(n+1)\frac{\pi}2$. Then $f|_{[n\frac{\pi}2,(n+1)\frac{\pi}2]}$ is continuous. In particular, $f(x)$ is both left continuous and right continuous at $x=n\frac{\pi}2$, for any $n\in\mathbb{Z}$, and we get:

Proposition 3 $f$ is continuous.

Note that, for any $x\in\mathbb{R}$,
$$
f(\cos^2(x)) = \cos^2(f(x)) \in [0,1]
$$
Thus we can define the (continuous) function $\tilde f:\mathbb{R}\rightarrow[0,\pi]$ by
$$
\tilde f(x)=\arccos\sqrt{f(\cos^2(x))}
$$
It is easy to see that $g$ is also a solution:
$$
\tilde f(\tilde f(x)) = \arccos\sqrt{f(\cos^2(\arccos\sqrt{f(\cos^2(x))}))}
\\ = \arccos\sqrt{f(f(\cos^2(x)))}
\\ = \arccos\sqrt{\cos^2(\cos^2(x))}
\\ = \cos^2(x)
$$
Without loss of generality, assume henceforth that $f=\tilde f$. This gives:

Proposition 4

$f$ is nonnegative
$f$ is even
$f$ is periodic with period $\pi$.

Note that $f(f(\frac{\pi}2))=0$, so $0\in\operatorname{im}f$ ; by periodicity and monotonicity, $f$ attains the value $0$ at one endpoint of each interval $[n\frac{\pi}2,(n+1)\frac{\pi}2]$. Focusing on the interval $[0,\frac{\pi}2]$, we have two cases:

$f(0)=0$, or
$f(\frac{\pi}2)=0$

If (1.), then
$$
0 = f(0) = f(f(0)) = \cos^2(0) = 1 \text;
$$
if (2.), then
$$
0 < f(0) = f(f(\frac{\pi}2)) = \cos^2(\frac{\pi}2) = 0 \text;
$$
both contradictions. We conclude that no such $f$ exists.
Comment: i completed my answer, feel free to comment on it
Comment: An injective monotone function is clearly strictly monotone. So in propositon 2 it may be simpler to prove $f$ is just monotone. Also lemma 2 can be simplifies using the fact that a monotone function has countable number of (jump) discontinuities.
Comment: in the proof of prop 2 i'm just assuming injectivity throughout (my usage of $<$ instead of $\le$ etc); i know it's worded in a convoluted way but that's because it summarizes the cases to be checked; i don't see how dropping the 'strictness' would make it simpler. as to lemma 2, i don't see why it matters how many discontinuities there are, although it's important to see that all discontinuities are jumps; in the proof i implicitly showed the existence of left and right limits.
Comment: btw i only realized the utility of $\tilde f$ later on, and maybe all the workup to show continuity of $f$ isn't necessary (just show that $\tilde f$ has the IVP, or that the IVP is conserved by composing with continuous and injective functions) although it was perversely interesting to find out all the properties $f$ (which doesn't exist anyway) has to satisfy


What to do when a Mann-Whitney U assumption is violated?

Question: I'm using a M-W U test to analyse some Likert scale results I have, as my data is ordinal.
One of the assumptions that keeps on appearing on references is the following: "both distributions must be the same shape (i.e., the distribution of scores for both categories of the independent variable must have the same shape).
If I fail this assumption, and therefore am unable to use M-W U, what can I use instead?
EDIT: I cannot add images, but will try to explain what my data looks like.
I have two groups based on my IV ("Yes" and "No"), charted on a boxplot with y-axis ranging from 1 - 5. For "Yes", I have a box extending from 4 to 5, with no variance. For "No", the box ranges from 3.5 to 4.5, with variance from 2.0 to 3.5, and 4.5 to 5.0.
I assume this means my shapes are "different". Does this mean I can't use MWU? If not, can you make suggestions as to what I can use instead (SPSS)?
EDIT2: Sample data:
"Yes": 5 5 5 5 5 5 4 4 4 4 5 5 4 4
"No":  4 5 5 5 3 2 4 3 4 4 4 4

I was using MWU to detect any significant differences (apparently, "yes") - but now am not sure if that's the right way to do it.
Comment: The Wilcoxon test does not strictly make that assumption if you are careful in computing $P$-values.  If you don't use the normal approximation but use a permutation exact test or use the full $U$-statistic method you can be OK.  For the latter you can run the following in the R `Hmisc` package: `rcorr.cens(x, Surv(y))` and test $D_{xy}=0$ by getting the estimate for $D$ and its standard error.  You can also use the generalization of the Wilcoxon test - the proportional odds ordinal logistic model.  See the `orm` function in the `rms` package.
Comment: P.S.  You can phrase the actual assumption made by the Wilcoxon test as being the proportional odds assumption, verifiable by plotting the logit transformation of the two ECDFs and checking for parallelism (linearity *not* required).
Comment: You need to show that these two curves are parallel: the logit transform of the empirical cumulative distribution functions for group 1 vs. group 2.  The curves do not need to be linear.
Comment: Figured out how to do this in SPSS, but my p < 0.05 now, which suggests that I've failed the assumption. Can I use alternative methods to statistically find differences between the two groups?
Comment: I posted similar question, it can be helpful. http://stats.stackexchange.com/questions/38881/how-to-test-group-differences-when-neither-parametric-nor-nonparametric-assumpti
Comment: Thanks - I saw it, but still don't really understand how to figure out the "shape" assumption, and what to do if it fails!
Comment: Thank you, Frank. I have to be honest - I'm not entirely sure what you mean by your answer; I use SPSS over R as I find it easier to understand. Is there any chance you could explain this a bit further so I can figure out how to replicate this in SPSS?
Comment: You wrote "I have two groups based on my IV ("Yes" and "No"), charted on a boxplot with y-axis ranging from 1 - 5. For "Yes", I have a box extending from 4 to 5, with no variance. For "No", the box ranges from 3.5 to 4.5, with variance from 2.0 to 3.5, and 4.5 to 5.0." I don't think you mean "variance". Since the data go only 1 to 5, you could post a table.
Comment: Regarding Frank's idea - I don't know SPSS, but surely it has ordinal logistic regression available. So, you can use that with the DV being the score and the IV being the group. Then you can test the proportional odds assumption.
Comment: The boxplot description makes no sense. How many scores do you have? Can you include them in a table?  That shape assumption does not mean identical and it doesn't sound like you've actually assessed it.
Comment: I doubt that SPSS can compute the exact P-value but see if it's an option.  I am fairly certain that SPSS can fit the proportional odds model, and you can use the likelihood ratio $\chi^2$ test.
Comment: I have 26 scores ranging from 1 to 5, split across "Yes" and "No" (IV). Data now added above.
Comment: @John: All the guides I've read indicate that to satisfy the shape assumption, you should create a boxplot and visually make sure that the "yes" and "no" shapes look similar. Is this wrong? If so, it would be great if you could give me pointers on how to actually assess this. I'm 99% sure MWU is the right tool, but find this assumption to be a stumbling block...
Answer: Here is an analysis using the R Hmisc and rms packages.
y1 <- c(5, 5, 5, 5, 5, 5, 4, 4, 4, 4, 5, 5, 4, 4)
y0 <- c(4, 5, 5, 5, 3, 2, 4, 3, 4, 4, 4, 4)

y <- c(y0, y1)
x <- c(rep(0, length(y0)), rep(1, length(y1)))

require(rms)
r <- rcorr.cens(x, Surv(y))
r

   C Index            Dxy           S.D.              n        missing
 0.6773399      0.3546798      0.1378018     26.0000000      0.0000000
uncensored Relevant Pairs     Concordant      Uncertain
26.0000000    406.0000000    275.0000000      0.0000000

z <- r['Dxy']/r['S.D.']
z   # 2.57

orm(y ~ x)

Logistic (Proportional Odds) Ordinal Regression Model

orm(formula = y ~ x)

Frequencies of Responses

 2  3  4  5
 1  2 12 11

                     Model Likelihood          Discrimination          Rank Discrim.
                        Ratio Test                 Indexes                Indexes
Obs            26    LR chi2      4.58    R2                  0.184    rho     0.407
Unique Y        4    d.f.            1    g                   0.885
Median Y        4    Pr(> chi2) 0.0323    gr                  2.424
max |deriv| 2e-04    Score chi2   4.43    |Pr(Y>=median)-0.5| 0.381
                     Pr(> chi2) 0.0354

     Coef    S.E.   Wald Z Pr(>|Z|)
y>=3  2.6045 1.0536  2.47  0.0134
y>=4  1.3459 0.6854  1.96  0.0496
y>=5 -1.3459 0.6854 -1.96  0.0496
x     1.7126 0.8426  2.03  0.0421

The likelihood ratio $\chi^{2}_{1}$ test for comparing the two groups yields $P=0.0323$
I obtained an exact $P$-value from the exactRanktests package wilcox.exact function of 0.04904.
Comment: Yes, or say it more positively: The Wilcoxon-Mann-Whitney 2-sample test is among the most robust of tests.  Having fewer assumptions than parametric tests, the Wilcoxon test is less likely than the $t$-test to be affected by assumptions not holding.  The Wilcoxon test doesn't assume that the two distributions have the same shape; it assumes that the two distributions, whatever they are, are connected by the proportional odds assumption.
Comment: No I wouldn't say that.  First of all, get away from the magic 0.05 cutoff.  Second, you haven't shown anything indicating that assumptions (proportional odds) don't hold.  The proportional odds model is an excellent way to handle heavy ties in the data, and it allows adjustment for other variables.  The proportional odds model and the Wilcoxon test have the same assumptions if  you compute $P$-values optimally.  BTW your sample size is too small to really examine the assumptions.
Comment: @FrankHarrell It depends on which assumptions we're considering. To my recollection, it seems to be slightly more affected that the t-test by serial correlation, for example. However, overall it's both quite robust overall and against the assumptions people tend to worry about, generally more robust than the t-test.
Comment: Aha! I've figured out how to do this using SPSS (Analyse -> Regression -> Ordinal). I assume p < 0.05 implies that there's a significant difference between my two groups and that I can NOT use M-W U for analysis as I've failed the assumption. Is this right? Can you help me identify alternative methods I can use?
Comment: So can I say something along the lines of, "The sample size is too small to determine whether the assumption holds" and run the M-W U anyway? I'm happy with the stats I have; just not sure how to answer a possible question about the assumption that "both distributions must be the same shape"...
Comment: Wonderful. *Thank you* so much for your help. Can you suggest a reference, in particular to the "less likely than the t-test to be affected by assumptions not holding"?
Comment: Virtually any textbook on nonparametric statistics.
Answer: The rank sum test does not strictly speaking have a shape assumption. At the most general, the rank sum test is a test of stochastic dominance with a null hypothesis H$_{0} \text{: P}(X_{A} > X_{B}) = \frac{1}{2}$; i.e. the probability of observing a randomly selected value from group A that is larger than a randomly selected value from group B is one half). With two additional assumptions, the rank sum test can be interpreted as a test for median difference with a null hypothesis H$_{0} \text{: } \tilde{x}_{a} = \tilde{x}_{b}$. These two additional assumptions are:

That the distributions have the same shape, and
That any differences in these distributions are differences in central location.

Therefore distributional differences between groups do not invalidate the use of the rank sum test, but rather alter the interpretation of its results.
See also my response here: ANOVA / Kruskal-Wallis: one of four groups has different distribution.


Criando archive.php no wordpress usando campo personalizado

Question: Estou tentando criar uma página de agenda no WordPress onde o usuário seleciona o mês por um select:
<select>
     <option>Janeiro 2015</option>
     <option>Dezembro 2014</option>
     <option>Novembro 2014</option>
     <option>Outubro 2014</option>
     <option>Setembro 2014</option>
</select>

Em seguida os posts são carregados via Ajax. Eu criei um formulário do tipo POST chamado agenda e um campo personalizado chamado agenda_data.
Eu preciso de ajuda em dois itens, o restante acho que consigo desenrolar sozinho.

No select aparecem os últimos 12 meses, a função do WordPress wp_get_archives faz isso. Porém ela retorna baseado nas datas de publicação e eu gostaria que fosse baseado na data do campo personalizado.
Um archive.php que exiba os posts também baseado na data do campo personalizado e não pela data de publicação do post.

Não achei nada ainda na internet que pudesse me ajudar.
Comment: não entendi a parte `baseado na data do campo personalizado.` Que campo é este? Como você o personaliza?
Comment: Mostra o form completo.
Comment: Um campo personalizado, onde você informa a data do evento, entendeu ?
Comment: Sergio, poderia colocar o código que você está usando? O valor do campo personalizado está sendo gravado como data ou com outro formato? Poderia colocar o código do que cria o campo personalizado tb?
Comment: Opa Ricardo, tudo bem ? agora estou usando a data mesmo nativa do Wordpress. Eu não sabia mas é possível exibir uma postagem mesmo ela estando agendada para uma data futura, usando 'post_status' => 'future'. Agora só estou com problemas no carregamento por ajax mesmo.
Comment: @SérgioMachado, você conseguiu resolver o problema, usando o `wp_get_archives()`? E como você está fazendo o carregamento AJAX?
Answer: Parece que não tem muito jeito, os filtros disponíveis na função wp_get_archives não são suficientes para fazer essa filtragem. A solução é copiar a função para uma meu_get_archives($args) e adaptar às suas necessidades: https://core.trac.wordpress.org/browser/tags/4.3.1/src/wp-includes/general-template.php#L1354
Quanto à página archive.php, em vez do tradicional <?php if( have_posts() ) : ?>, tem que fazer um WP_Query personalizado, usando o parâmetros Order & Orderby:
'order' => 'ASC',
'orderby' => 'meta_val_num'

Ou então poderia usar o filtro pre_get_posts, que é o recomendado para filtrar a query principal e deixar a o template archive.php do jeito que é.
Referências:
- Order Custom Post Type Archive by multiple values in functions.php
- Archive Listings Filtered by Date Values in a Custom Field/Post Meta? (aqui, a resposta do Mike Schinkel é uma master class)


How to properly replace view controllers

Question: I just can't understand what am i doing wrong with this. I have 2 unrelated view controllers, which i created in storyboard by dragging a view controller to screen. each has its name identifier in storyboard and i replace between them by their names.
Problem is ,that after the first replacement i get tens of memory warnings that are unrelated to reality because my memory consumption is about 59M and stay like that . When i switch from A to B and than back to A, sometimes its crash due to "lake of memory" (59M!! ) .
What am i doing wrong when replacing view controllers ???
- (IBAction)goMatrix:(id)sender
{
    UIViewController *mainV=[self.storyboard instantiateViewControllerWithIdentifier:@"MatrixView"];
    mainV.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:mainV animated:YES completion:^(void)
     {
         scroller.delegate=nil;
         scroller=nil;
         [imagesBuffer removeAllObjects];
         [scroller removeFromSuperview];
         [stripView removeFromSuperview];

     }];

}

I have a scrollview in both of them with images, that i just remove from the superview, i just can't understand what else can i do to REALLY clean things up (although memory is just 59M )

the only moment i have high memory is when i replace them, and its 134M for only 1 second(!)
Answer: If your App is a single view structure (without embedded in UINavigationController or UITabBarController), you can use:
// App Delegate
UIViewController *mainV=[self.storyboard instantiateViewControllerWithIdentifier:@"MatrixView"];
self.window.rootViewController = mainV;
[self.window makeKeyAndVisible];
stripView = nil;

Old view controller will be automatically be removed from memory if you use ARC.
If you are writing in View Controller, you can use:
UIViewController *mainV=[self.storyboard instantiateViewControllerWithIdentifier:@"MatrixView"];
AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
delegate.window.rootViewController = mainV;
[delegate.window makeKeyAndVisible];
stripView = nil;

Comment: @Raptor your answer is great , thanks a lot! what is strange to me is, why Apple has this kind of transition if you say it has a moment of high memory.
Comment: I am not sure i understand what do you mean by "can use" , what do i do with his code? i have to be able to replace from B to A, than from A to B, how would i do that , and what is wrong with my current code ?
Comment: i dont think with storyboard , you need to use setRootViewController or makrKeyAndVisible , bacause storyboard do this for you . just a defined window in appdelegate & return YES in applicationdidfinishlaunching.
Comment: that's incorrect. You can still use these with storyboard.
Comment: and why one get memory warnings for 59M ?
Comment: It really depends on what did you write in your view controller class. Too few information to diagnose.
Comment: And again, what is wrong with my code to replace views?
Comment: What if you write a lot of I/O work in `viewDidUnload`? Think about it. It will cause memory spike. `presentViewController` will cause 2 view controllers appear on screen at the same time, which results in high memory usage. Anything unclear?
Comment: To clarify further, before completion of `presentViewController`, the old view controller still occupies memory, while new view controller is occupying memory too. Also, with `animated:YES`, some memory is spent in `UIAnimation`. To be fast & clean, use my suggested method. *Again, what's wrong about my answer* ?


Is $C$ projective as $C[x]$ module?

Question: I'm asking myself if $C = C[X]/(x)$ is a projective/flat $C[X]$ module. I found on the internet that this isn't the case, but on the other hand we have $ C[X] = C \oplus xC[X]$, so $C$ is a direct summon of a free $C[X]$ module. Did I make a mistake?
Comment: That's a direct sum of $\mathbb C$-vector spaces, but not  of $\mathbb C[X]$-modules.
Comment: Why? Both are $C[x]$ modules right? So I can take the direct sum, and this does not depend on the mother ring?
Comment: A projective module is a sub-module of a free module, hence has no torsion. But your module is annihilated by $x$.
Answer: The claim that $C[X]\cong C[x]/(x)\oplus xC[x]$ as $C[x]$-modules is false. I imagine you're thinking the isomorphism would look like
\begin{align*}
\phi:\,&C[x]/(x)\oplus xC[x]\to C[x] \\
&(c,xd)\mapsto c+xd.
\end{align*}
But the issue is that this isn't an isomorphism of $C[x]$-modules. In particular, consider multiplication by $x$: we get $\phi(x(1,0))=x\phi(1,0) = x(1) = x$, if this is to be a $C[x]$-module homomorphism. But in the direct sum, $x(1,0) = (x,0) = (0,0)$ since $x=0$ in $C[x]/(x)$, and $\phi(0,0) = 0$. So this map doesn't give an isomorphism of $C[x]$-modules.
Writing $C=C[x]/(x)$ obscures the fact that as a $C[x]$-module, multiplication by $x$ takes everything to $0$.
Comment: ahh I understand, thank you. But How could I proof now in general, that this isn't a projective Moudle (i.e there is no other decomposition of a free $C[x]$ module?
Comment: By $C$, do you mean the complex numbers? If so, then a rather convoluted argument is that $C[x]$ is a PID, and $C[x]/(x)$ is not torsion-free as a $C[x]$-module (as we saw, multiplication by $x$ acts as multiplication by $0$). Thus $C[x]/(x)$ is not flat (over a PID, flat is equivalent to torsion-free), and since projective modules are flat, this means it isn't projective. But I am absolutely sure there is a better argument than this, perhaps using classification of f.g. modules over a PID or using the fact that submodules of $C[x]$ are precisely the ideals of $C[x]$ as a ring…
Comment: Oh, here is the argument: we need to find two submodules/ideals of $C[x]$ that intersect trivially (and add to give all of $C[x]$). But no two nonzero ideals of $C[x]$ can possibly intersect trivially, since we can always just multiply a nonzero element in one by a nonzero element in the other to get a nonzero element in their intersection.
Answer: $\mathbb C[x]$ does not have direct summands as a $\mathbb C[x]$ module. There are simply no nonzero submodules intersecting to $\{0\}$.
The illusion I think you are under is that that the constant term $\lambda$ in the polynomials can be exchanged for the coset $\lambda +(x)$, which of course it cannot. In $\mathbb C[x]$, $1\cdot x$ is nonzero, whereas considered as the module $\mathbb C[x]/(x)$ multiplying anything nonzero by $x$ results in the zero coset.  They just aren't isomorphic.

But How could I proof now in general, that this isn't a projective Moudle

I think you mean $\mathbb C[x]/(x)$(?)  If it were projective the exact sequence $0\to (x)\to \mathbb C[x]\to \mathbb C[x]/(x)\to 0$ would split, so that $(x)$ is a summand of $\mathbb C[x]$. It isn't, for the reason mentioned above.
Comment: Is it analogly true than that for a non trivial Ideal $I$ the $R$-Module $R/I$ is not projective? (if $R$ is a domain)
Comment: I mean the following, if it would be projective than $ 0\to I \to R \to R/I \to 0$ would split i.e $R/I$ would be a direct summand of $R$, but as $R$ is a domain it is torsion free (as $R$-Module) and $R/I$ isn't, so it cant be a direct summand.
Comment: You can say that for $I$ a nontrivial ideal of $R$, the module $R/I$ is projective iff $I$ is a summand of $R$. In particular, if $R$ has only trivial idempotents (as is the case for a domain), no such $I$ can be a summand.
Comment: why exactly is the idempotent condition enough for $I$ not beeing a direct summand of $R$ ?
Comment: @user1072285 In a ring with identity, a right submodule (resp. left submodule) is a summand iff it is $eR$ (resp $Re$) for some idempotent element $e$.  In general a submodule $N$ of $M$ is a summand of $M$ iff there is an idempotent $e$ of $End(M_R)$ such that $e(M)=N$.

Is $C$ projective as $C[x]$ module?


Não consigo aceder à minha base de dados

Question: Estou com o seguinte problema, estou a tentar alterar o ano das datas que tenho na minha base de dados, e para isso estou a usar:
mysqli_fetch_row

Mas não estou a conseguir, retorna sempre falha. Também fiz uma conexão à base de dados e aparentemente está a funcionar porque não retorna com erro. agradecia imenso qualquer tipo de ajuda prestada. Se a pergunta não estiver devidamente clara, solicitem, que farei as devidas alterações. Obrigado
Código:
 <?php
 //Create a database connection
     $dbhost = "localhost";
     $dbuser = "root";
     $dbpass = "";
     $dbname = "bd-aircaw-1";
     $connection =mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
 // Check connection
 if (mysqli_connect_errno())
   {
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
   }

    $query = "SELECT * ";
    $query .= "FROM voo ";
    $query .= "WHERE DataPartida = 2014-11-01 18:00:00";

    $result = mysqli_query($connection, $query);
    if(!$result) {
        die ("Database query failed.");
    }

    while($row = mysqli_fetch_row($result)){
        var_dump($row);
        echo "
";
    }

Comment: Valores de data devem estar entre aspas simples.
Comment: Já modifiquei as aspas para simples mas não surtiu efeito continua a dar o erro "Database query failed."
Answer: Seu código com problema:
$query .= "WHERE DataPartida = 2014-11-01 18:00:00";

Acrescente aspas simples ou aspas dupla com escape:
$query .= "WHERE DataPartida = '2014-11-01 18:00:00'";
ou
$query .= "WHERE DataPartida = \"2014-11-01 18:00:00\"";

Answer: Sua conexão esta incompleta, veja o exemplo do W3Schools: $con=mysqli_connect("localhost","my_user","my_password","my_db");
Você deve usar aspas para buscar por datas e strings no BD:
`$query .= "WHERE DataPartida = \"2014-11-01 18:00:00\"";`

Comment: Já alterei o código, obrigado pela sugestão, realmente não reparei nos parâmetros em falta, mas apesar de ter retificado, alterei e continua sem correr; o programa.
Comment: Qual o erro que dá agora?
Comment: Acho que tem outro problema em sua SQL, editarei minha resposta.
Comment: Dá o mesmo erro: "Database query failed." Penso que seja alguma coisa relacionada com os querys, não devem estar a encontram valores nenhuns, mas já verifiquei os valores e parece-me não haver erros.
Comment: Obrigado era mesmo esse o problema :) Muito obrigado pela resposta.


Number of words which are equivalent to BACHELOR

Question: Consider all the $8$-letter  words that can be formed by arranging the letters in $BACHELOR$ in all possible ways. Any two such words are equivalent if those two words maintain the same relative order of the letters $A$, $E$ and $O$. For example, $BACOHELR$ and $CABLROEH$ are equivalent. How many words are there which are equivalent to $BACHELOR\;?$
I just try to find all possible cases with maintaining the order of $A$, $E$ and $O$, but their are lots of cases and I can't find the pattern. That's why I can't calculate all possible cases.
If the title of the problem or tags should be change then please feel free to do it.
Comment: Hint:  all possible orders for $A,C,E$ come up the same number of times.
Answer: There are $8!$ possible permutations if we ignore the restriction on the order.  There are $6$ equivalence classes (as there are $6$ ways to order three letter) and each equivalence class contains the same number of permutations (there is an obvious bijection between any two equivalence classes).  Thus the answer is $$\frac {8!}6=6720$$
Answer: Method 1: There are $8$ ways to place the B, $7$ ways to place the C, $6$ ways to place the H, $5$ ways to place the L, and $4$ ways to place the R.  The letters A, E, O must be placed in the open positions in that order.  Hence, there are
$$8 \cdot 7 \cdot 6 \cdot 5 \cdot 4$$
such arrangements.
Method 2: Choose three of the eight positions for the vowels A, E, O.  They can be placed in the chosen positions in one way.  The remaining positions can be filled with the five consonants in $5!$ ways.  Hence, the number of possible arrangements is
$$\binom{8}{3}5!$$
Method 3:  There are $3!$ ways to arrange the vowels A, E, O within a given arrangement of the letters of the word BACHELOR.  Only one of these is permissible. There are $8!$ arrangements of the eight distinct letters of the word BACHELOR.  Therefore, by symmetry, the number of permissible arrangements is
$$\frac{1}{3!} \cdot 8!$$
Answer: Let $a_1$ denote the number of letters on left side of $A$.
Let $a_2$ denote the number of letters between $A$ and $E$.
Let $a_3$ denote the number of letters between $E$ and $O$.
Let $a_4$ denote the number of letters on right side of $O$.
Then the $a_i$ are nonnegative integers that satisfy $a_1+a_2+a_3+a_4=5$ and with inclusion/exclusion we find that there are $\binom{5+3}3$ of such sums.
There are $5!$ ways to arrange the letters $BCHLR$ so there are $$\binom835!$$ possibilities.
Answer: In general for an anagram with repeated letters, you can use a multinomial coefficient . So this would be suitable for example for anagrams of "CARAVANS", where we have $8$ letters with one of them repeated $3$ times, so the multinomial coefficient is
$\dbinom{8}{3,1,1,1,1,1} = \dfrac{8!}{3!\cdot 1!\cdot 1!\cdot 1!\cdot 1!\cdot 1!} = \dfrac{8!}{3!} = \dfrac{40320}{6} = 6720$
This is exactly relevant to this case as you can ignore the difference between the vowels for the purpose of finding arrangements. Once an arrangement is found - say CvBLRvvH, with v being an anonymous vowel - there is only one way to make that equivalent to BACHELOR, allocating the vowels into the v spots in the order AEO to give CABLREOH.


Can someone explain hex offsets to me?

Question: I downloaded Hex Workshop, and I was told to read a .dbc file.

It should contain 28,315 if you read
  offset 0x04 and 0x05

I am unsure how to do this? What does 0x04 mean?
Comment: Why is this question marked down? It is a perfectly valid question.
Comment: See how much better quality answers you get with a proper question?
Answer: 0x04 is hex for 4 (the 0x is just a common prefix convention for base 16 representation of numbers - since many people think in decimal), and that would be the fourth byte (since they are saying offset, they probably count the first byte as byte 0, so offset 0x04 would be the 5th byte).
I guess they are saying that the 4th and 5th byte together would be 28315, but did they say if this is little-endian or big-endian?
28315 (decimal) is 0x6E9B in hexadecimal notation, probably in the file in order 0x9B 0x6E if it's little-endian.
Note: Little-endian and big-endian refer to the order bytes are written.  Humans typical write decimal notation and hexadecimal in a big-endian way, so:
256 would be written as 0x0100 (digits on the left are the biggest scale)
But that takes two bytes and little-endian systems will write the low byte first: 0x00 0x01.  Big-endian systems will write the high-byte first: 0x01 0x00.
Typically Intel systems are little-endian and other systems vary.
Comment: @OregonGhost: Hope you don't mind, I felt your addition deserved to be part of that answer.
Answer: Think of a binary file as a linear array of bytes.
0x04 would be the 5th (in a 0 based array) element in the array, and 0x05 would be the 6th.
The two values in 0x04 and 0x05 can be OR'ed together to create the number 28,315.
Since the value you are reading is 16 bit, you need to bitshift one value over and then OR them together, ie if you were manipulating the file in c#, you would use something like this:
int value = (ByteArray[4] >> 8) | ByteArray[5]);

Hopefully this helps explain how hex addresses work.
Answer: It's the 4th and the 5th XX code your viewing...

1   2  3  4  5  6
01  AB 11 7B FF 5A

So, the 0x04 and 0x05 is "7B" and "FF".
Assuming what you're saying, in your case 7BFF should be equal to your desired value.
HTH
Answer: Start here. Once you learn how to read hexadecimal values, you'll be in much better shape to actually solve your problem.
Answer: 0x04 in hex is 4 in decimal. 0x10 in hex is 16 in decimal. calc.exe can convert between hex and decimal for you.
Offset 4 means 4 bytes from the start of the file. Offset 0 is the first byte in the file.
Answer: Look at bytes 4 and five they should have the values 0x6E 0x9B (or 0x9B 0x6E) depending on your endianess.

Can someone explain hex offsets to me?


Python IndentationError: Sublime Text 2 using SublimeREPL

Question: I am trying to evaluate some Python commands in SublimeREPL but every new command causes an IndentationError. The code works if I send it one line at a time.
Here is an attempt at an example...
class Array(object):
    def __init__(self, length = 0, baseIndex = 0):
        assert(length >= 0)
        self._data = [0 for i in range(length)]
        self._baseIndex = baseIndex
    def __copy__(self):
        result = Array(len(self._data))
        for i, datum in enumerate(self._data):
            result._data[i] = datum
        result._baseIndex = self._baseIndex
        return result
    def __len__(self):
        return len(self._data)

which evaluates to...
IndentationError: unexpected indent
>>> class Array(object):
...     def __init__(self, length = 0, baseIndex = 0):
...         assert(length >= 0)
...         self._data = [0 for i in range(length)]
...         self._baseIndex = baseIndex
...
>>>     def __copy__(self):
  File "<stdin>", line 1
    def __copy__(self):
    ^
IndentationError: unexpected indent
>>>         result = Array(len(self._data))
  File "<stdin>", line 1
    result = Array(len(self._data))
    ^
IndentationError: unexpected indent
>>>         for i, datum in enumerate(self._data):
  File "<stdin>", line 1
    for i, datum in enumerate(self._data):
    ^
IndentationError: unexpected indent
>>>             result._data[i] = datum
  File "<stdin>", line 1
    result._data[i] = datum
    ^
IndentationError: unexpected indent
>>>         result._baseIndex = self._baseIndex
  File "<stdin>", line 1
    result._baseIndex = self._baseIndex
    ^
IndentationError: unexpected indent
>>>         return result
  File "<stdin>", line 1
    return result
    ^
IndentationError: unexpected indent
>>>
>>>     def __len__(self):
  File "<stdin>", line 1
    def __len__(self):
    ^
IndentationError: unexpected indent
>>>         return len(self._data)
  File "<stdin>", line 1
    return len(self._data)
    ^
IndentationError: unexpected indent

However if I put some line comment characters in before each line it works fine except for the trailing "... ... ... ..."
class Array(object):
    def __init__(self, length = 0, baseIndex = 0):
        assert(length >= 0)
        self._data = [0 for i in range(length)]
        self._baseIndex = baseIndex
#
    def __copy__(self):
        result = Array(len(self._data))
        for i, datum in enumerate(self._data):
            result._data[i] = datum
        result._baseIndex = self._baseIndex
        return result
#
    def __len__(self):
        return len(self._data)
#

After it has been sent I have to switch over to the REPL window and hit enter on the line with the "... ... ... ..." for it to be evaluated.
>>> class Array(object):
    def __init__(self, length = 0, baseIndex = 0):
        assert(length >= 0)
        self._data = [0 for i in range(length)]
        self._baseIndex = baseIndex
#
    def __copy__(self):
        result = Array(len(self._data))
        for i, datum in enumerate(self._data):
            result._data[i] = datum
        result._baseIndex = self._baseIndex
        return result
#
    def __len__(self):
        return len(self._data)
#
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...

I am new to Python so I apologize if I am missing something very simple. I tried looking everywhere for this answer.
Answer: I suspect you've shown us code that's not exactly like what you're really running. In your actual python script, you've probably got a few newlines separating your def's from each other (which is fine), but they aren't in the pasted section of code here. Maybe because of the formatting issues here or something.
However, in Python, an empty line indicates that you're done with the previous section. This only matters when using the interactive interpreter (like in SublimeREPL). Spaces and Indentation matter. In this case, it's just transferring your text to the interpreter, which is the same thing that happens if you just cut and paste it yourself. It's seeing the newline before def __copy__(self), and assuming it should evaluate that class definition. Then, it's seeing the def __copy__(self), and noticing that it has some space indenting. This is causing the IndentationError you're receiving.
Either comment on the already existing bug about this in SublimeREPL's github account, or don't use empty lines in your code.


Como fazer um checkbox no canto de uma imagem?

Question: Eu estou a realizar um trabalho para a escola em php, css... E gostaria de saber se é possível colocar checkboxes em imagens que vem da base de dados.
Eu gostaria de colocar as checkboxes (em vermelho) como se encontram na imagem anexada. Isto é para facilitar apagar mais que um "evento" ao mesmo tempo
]1
Comment: Por favor, marque minha resposta como aceita, se o código funcionou :)
Answer: Antes de responder ao que foi perguntado, uma observação: não é possível estilizar um input do tipo checkbox apenas definindo a propriedade background (ou background-color).
Porém existem algumas formas de contornar isso e tratar a questão da cor de fundo:

Inserir o checkbox em um elemento que possui cor de fundo.
Criar um pseudo-elemento com a aparência que está buscando.
Esconder o elemento de entrada e usar um  atrelado ao elemento alvo, por meio do atributo for. Assim, ao invés de estilizar o input, você define as regras de estilo do , da mesma forma que é possível estilizar um input do tipo file.

Eu costumo utilizar a terceira opção quando preciso estilizar um elemento desse tipo. Você precisaria alterar um pouco a marcação que está fazendo, para isto:

  <input type='checkbox' id='foo'>
  ✅

No id do input, você pode ir gerando valores em sequência, por exemplo: imagem1, imagem2, imagem3... Estes valores devem ser únicos.
No for do label, você apontará para o id respectivo de cada input.
E no src da imagem você deixará como já está fazendo, inserindo a URL da imagem.

O resultado será esse:

.image-wrapper {
  position: relative;
  height: 300px;
  width: 500px
}

.image-wrapper img {
  width: 100%
}

.image-wrapper input {
  display: none
}

.image-wrapper label {
  background: #fff;
  color: #fff;
  padding: 2px 6px;
  position: absolute;
  right: 4%;
  top: 4%
}

.image-wrapper input:checked + label {
  background: red
}

  <input type='checkbox' id='dog-img'>
  ✅

Answer: Antes da linha que retorna a imagem do banco de dados adicione o seguinte código html:

<input type="checkbox" name="imgDb" value="imgDb" />

ficando assim:
echo '

                <input type="checkbox" name="imgDb" value="imgDb" />

<td style="float:left,"	';

Adicione também este css:
td{position: absolute}
.check input[type="checkbox"]{
  position: relative;
  top: 20px;
  background: red;
}

Comment: Isto: `background: red;` não funciona para *checkbox*.


How would you get a list of all the applications at your company?

Question: (Updated: I've moved this over to ServerFault)
I'm responsible for maintaining a list of all the applications in my company (about 250). The range is from HR systems that track 80k employees, to manufacturing-type systems responsible for hundreds of millions of dollars of revenue, to web applications with a small user base and not a lot of risk associated to them going down.
The technologies are mostly split between SAP, .Net, and Java, but we have legacy examples of just about everything else you can imagine.
The point of the list is to be able to manage risk and identify opportunities for improvement. For instance, when we find systems that are responsible for core business functionality that are written in clipper, we try to find some money to re-write them. We call the picture of the high-risk apps in the landscape the "heat map".
The list is pretty simple - It really just needs the name, description, ID, DB platform, App platform (ex, SAP, .Net, Java on Weblogic, Mainframe, etc), key interfaces, and key services.
Anyone have any experience building / maintaining a list like this? What should I keep in mind?
Cheers
KA
Comment: This is an excellent question for the new IT StackOverflow sister site. It'll be out in 6-8 weeks.
Comment: In theory I guess I'd start with some kind of report against my source control API...
Comment: I would vote to reopen if I had the rep
Comment: There are applications available for that. Google for Software Inventory.
Comment: @kaiser-advisor I think this is an IT Stack Overflow question, but I've sent my (somewhat spammy) answer out-of-band.
Comment: Well, for the more code oriented, you could hack up a windows forms app with a DB behind it.
Comment: @out_into_space this is not an IT question. He's talking about information management, and how to keep track of information about projects.
This is a critical part of project handoff (when the devs move to other things) that there has to be a way to store information about it.
Comment: try a google for "application portfolio management software"?
Answer: When in doubt use excel. At least to start out.
As you start to organize them, you will then see what types of organizational tools to use to improve your management.  But it could very well end up being all you need.
Ideally you would want something automated so that your "master list" knows when a certain app is down. This may not be feasible with a lot of apps spread across different languages and platforms.


Método estático chamando um objeto

Question: Porque o PHP permite eu usar assim, conforme abaixo, o script roda normalmente. Não estaria incorreto?Ou não? O aperador :: não é apenas para métodos estáticos? Estava tentando acessar um objeto por um método estático. Mas acredito eu estar incorreto dessa forma mesmo funcionando.
Class Helper extends Crud
{

   public function lista($tabela)
   {
       return $this->select($tabela);
   }

}

//Uso
<?php foreach (Helper::lista('usuario') as $value):?>

 <?php echo $value['usu_nome'];?>

<?php endforeach;?>

Comment: O que tem nessa classe `Crud`? Tem o código dela?
Comment: Métodos protecteds apenas
Answer: A partir da versão 5.4, é emitido erro do tipo STRICT para o caso apresentado.
Se não está vendo mensagens de erro na tela pode ser devido as configurações do reportador de erros.
Caso esteja usando PHP versão 5.4 ou superior, defina o reportador de erros para permitir reportar erros do tipo STRICT
Uma sugestão, num ambiente de desenvolvimento, é recomendável exibir todo tipo de erro e então corrigir todo tipo de problema que aparecer, mesmo os do tipo STRICT e DEPRECATED.
ini_set('error_reporting', E_ALL);
ini_set('display_errors', true);

A decisão sobre como configurar o reportador de erros depende de cada caso. Há casos onde é necessário ocultar erros do tipo STRICT e DEPRECATED. Um exemplo, é sistemas legados onde tornar-se inviável corrigir e converter muitos códigos. (falta de tempo, falta de investimentos, falta de permissão de um superior, etc).
Voltando ao assunto, é recomendável que corrija dentro do padrão, declarando explicitamente a visibilidade e o tipo dos métodos, tal como das propriedades de uma classe.
Exemplo
Como NÃO fazer:
class Foo {
    function Bar() {

    }
}

Corrija definindo a visibilidade. Nesse exemplo vamos usar public.
class Foo {
    public function Bar() {

    }
}

O método não é estático, portanto deve ser invocado por uma instância
$c = new Foo;
$c->Bar();

Se tentar Foo::Bar(); apresentará erros STRICT e outros erros subsequentes como o acesso ao $this fora de contexto, por exemplo. E isso vai causando uma bola de neve de erros.
Driblando o reportador de erros
Conforme mencionado acima, pode haver situações onde é inviável corrigir todos os erros. Para esses casos, pode fazer a seguinte configuração
/*
Aqui diz que deve reportar todos os erros exceto os do tipo STRICT e DEPRECATED.
*/
ini_set('error_reporting', E_ALL & ~E_STRICT & ~E_DEPRECATED);

/*
true: para ambiente de testes (o seu localhost)
false: para ambiente de produção (o site online, no servidor)
*/
ini_set('display_errors', false);

/*
Opcionalmente pode ligar o log de erros e então definir uma local onde deseja salvar esses avisos.
*/
ini_set('log_errors', true);
/*
Local onde serão gerados os arquivos de logs de erro.
Apenas cuidado pois dependendo da quantidade de acessos e de erros, esses arquivos podem ficar enormes. O ideal é estarem sempre vazios. Portanto, qualquer erro pequeno, sempre corrija o mais rápido possível
*/
ini_set('error_log', BASE_DIR.'..'.DS.'logs'.DS.'php'.DS.'PHP_errors-'.date('Ym').'.log');

Gambiarra, invocando método não estático num método estático
class Foo {
    public function Bar() {

    }
    public static function Bar2() {
        $c = new Bar;
        return $c->Bar();
    }
}

Foo::Bar2();

O problema aqui é que não faz sentido. Está criando apenas uma faxada para tornar o código mais "elegante" e apenas consumindo memória e processamento desnecessário.
Uma solução é criar as definições de forma consistente com o objetivo final do que precisa ser usado dessa classe.
Evite gambiarras e ocultar erros do tipo STRICT e DEPRECATED. Normalmente, erros nesse nível, em curto ou médio prazo tornam-se de nível FATAL.
Comment: relamente o debug tava desligado. Deprecated: Non-static method Helper::lista() should not be called statically, assuming $this from incompatible context in C:\wamp64\www\SISGES2\system\includes\pagehome.php on line 103
Comment: aproveitando como uso um objeto dentro do estático
Comment: Editei. Leia "Driblando o reportador de erros"
Comment: Obrigado pela atenção já uso o error_log e no error_reporting uso E_ALL mas vou alterar para essa indicada obrigado.
Comment: Amigo  a intenção é que possuo um classe crud com os métodos protected  e preciso de um método externo(estático) para listar categorias do banco em varias telas do sistema e essas categorias são dinâmicas sempre sofre alterações. Então bastaria um método para listar sem precisar instanciar.
Comment: Entendo a intenção mas não faz sentido algum do ponto de vista OOP. Além do mais , classe e CRUD nada tem ver um com o outro. Mas na verdade, no final das contas estaria instanciando de qualquer forma, só que de um jeito "mascarado".  Usei o termo "fachada"  e comentei sobre  redundância e custo. Há conceitos errados e sem sentido no que vc comentou agora. Enfim, não é uma pergunta sobre design pattern, OOP ou conceitos básicos de modelagem. Mas como tocou no assunto, tive que comentar brevemente. Se quer aprender, fique a vontade para perguntar. Há vários bons profissionais que podem ensinar.
Comment: Explica o conceito errado para meu aprendizado.A classe crud contem insert, select etc abstratos.
Comment: Pesquise no site sobre esses termos ou faça novas perguntas específicas.
Answer: Veja, como foi dito na resposta do DanielOmine, dependendo da versão do PHP, uma mensagem de erro é disparada (E_STRICT).
Isso porque, apesar de ser permitido, isso pode gerar um grave erro. É quando você tem a variável especial $this.
Veja:
    class Test{

    public function z()
    {
        return 'zzz';
    }

    public function y()
    {
        $this->y = 'yyy';

        return $this->y;
    }
}

Test::z(); // Mensagem E_STRICT

Test::y(); // Aqui vai ter um problema com `$this`

Using $this when not in object context

O Operador de resolução de escopo (::), portanto, deve ser usado quando você for chamar métodos ou propriedades estáticas e constantes.
O PHP 5.4 oferece uma facilidade para você utilizar métodos de uma classe que seja dinâmicos com maior facilidade:
Poderia ser feito assim:
 foreach ((new Helper())->lista('usuario') as $value)

Comment: e caso precisasse usar om objeto de uma classe extendida para um método estático como usaria?
Comment: Você teria que ter a instância da classe (caso o método que deseja usar não seja estático, e sim dinâmico)

Método estático chamando um objeto


Implement IDisposable on partial LINQ to SQL entity classes

Question: I am extending LINQ to SQL entity classes using partial classes, and I'm wondering how to best reset some properties on the entity objects to their default state.
My partial classes uses no unmanaged recourses. And as far as I can tell; neither does the LINQ to SQL entity classes. So I'm thinking that I'll implement IDisposable and handle the resetting of properties inside of Dispose().

What are your thoughts on this approach?
And would you set before mentioned properties to null or something else?
Answer: For better or worse, IDisposable is almost universally associated with finishing with a resource rather than reseting it. This sounds like an odd use to me. I would just create a Reset() method - or just create a new instance when you need to. What's the purpose of this? What are you trying to achieve?
As for "suppress[ing] the instance on the GC" - what exactly do you mean? If you're talking about a finalizer, I'd think very carefully before adding a finalizer - it's very rarely the right way to go.
Comment: Well, I am trying to "finish" my objects. I'm just not sure how, though. The only thing I can come up with is resetting the object.
Comment: Why are you trying to do this though? What's wrong with just letting them become eligible for garbage collection and let things take their course? What benefit do you expect to see?
Comment: Lets say I call Remove() on an object. The method deletes the objects associated database-entry. Now the object represents something that no longer exists (the entry in the database). I'd like the object to reflect the database entry at all times--ideally I want the object to be null after a call to Remove()
Comment: An object itself can't be null. Can't you just trust your callers to not reference the object after removing it? Is this *actually* a problem for you, or are you just trying to anticipate problems?


during the initial page load need to change the add/edit color

Question:
I am learning angular2.
during the initial page loads, I need to change the add/edit preference colour.
can you tell me how to fix it?
I googled for the load event.
but I am not able to find out anything.
providing my code below.

https://stackblitz.com/edit/angular-zddcxy?file=app/app.component.html

 public loadColor() {
      console.log('this.changeColor--->');
  }
    add/edit prefrence

Answer: For catch initial page loads event, you need to use Angular component lifecycle hook. So you need it add ngOnInit is called by Angular completed creating the component.
For add ngOnInit you need import OnInit
import {Component, OnInit} from '@angular/core';

You need to add ngOnInit hook method
 //implement OnInit's `ngOnInit` method
ngOnInit(){
   console.log('this.changeColor--->');
}

For more information https://angular.io/guide/lifecycle-hooks
I have updated your code https://stackblitz.com/edit/angular-gzqebz?file=app/app.component.ts
Answer: Use ngOnInit and ViewChild decorator
@ViewChild('open1') el:ElementRef;
  ngOnInit(): void {
  const span = this.el.nativeElement;
  span.style.color = 'red';
}

And in HTML add #open1 as ref
add/edit prefrence

see https://stackblitz.com/edit/angular-uvmusm?file=app/app.component.html
Comment: hey thanks for reply....can you explain so that in future I will do it myself....not sure why we are using viewchild and native element
Comment: It's just a way to direct access to the DOM. ViewChild it's a decorator that will allow you to manipulate the reference element in a class. You point to an element of the dom with `#toto` identifier. And you get it with `@ViewChild('toto') el:ElementRef`, then on `ngOnInit` or `ngAfterViewInit` you can manipulate this DOM element when  component loads


How to digitally sign PDF files with XFA forms using iText

Question: iText release notes mention that signing of PDFs with XFA forms is supported from iText versions 5.4.2 and 5.4.3:
http://itextpdf.com/history/?branch=54&node=542
http://itextpdf.com/history/?branch=54&node=543
Is there a documentation somewhere how to do the signing in Java?
I am specifically interested in signing PDFs with XFA where there is a prepared field for signature.
Answer: This is a small example showing how to sign using XmlDSig:
<code>PdfReader reader =new  PdfReader(src);
FileOutputStream os =new  FileOutputStream(dest);
PdfStamper stamper = PdfStamper.createXmlSignature(reader, os);
XmlSignatureAppearance appearance = stamper.getXmlSignatureAppearance();
appearance.setXmlLocator(new  XfaXmlLocator(stamper));
appearance.setXpathConstructor(new XfaXpathConstructor(XfaXpathConstructor.XdpPackage.Datasets));
ExternalSignature signature =new  PrivateKeySignature(pk, digestAlgorithm,"BC");
//use signXmlDSig or signXades
MakeXmlSignature.signXmlDSig(appearance, signature, chain);
</code>
You can also sign using XAdES, but then you won't be able to validate the signature in Adobe software because I don't think Adobe already supports XAdES (please correct me if I'm wrong).


Git on Window prevent multiple branch with different case

Question: A few time I have had an issue when pushing branches to VSTS I will end up with multiple versions of the same branch but different case.
Just wondering if there are a way to config my git locally to prevent this from happening?
Comment: Is your local OS Windows? If yes are you sure you can create both branches locally?
Answer: The setting you want is actually on the server instead of locally. There is an option in Azure DevOps that will prevent anyone from pushing branch names that differ from existing branch names by case only. (If you're still using VSTS I assume the setting exists there too.)

If you test locally on a Windows OS you should find that you already cannot create two branches that differ by case only. But you can create a branch called testing, push it out, delete the local branch and create a new branch called Testing, and push it out. To prevent that you should enable the option on the server.


Visualizar resultado de forEach fora dele

Question: Há alguma forma dos dados do forEach ser visualizado fora do forEach?
Preciso visualizar os dados do forEach fora dele, mas sempre que faço isso ele só devolve o último dado, e não todos os dados. Já tentei utilizar o localStorage e da o mesmo resultado.
Se caso não dê, tem alguma forma de fazer um forEach com dois arrays? Poderiam dar exemplos?
Meu código:
this.MetaService.CheckOrderGet().subscribe(
              data => {
                const pesquisa = (data as any)
                this.check = JSON.parse(pesquisa._body)

                this.check.forEach(apielement => {

                  this.fil.forEach(dados=> {

                    if (apielement.FI == dados.FI) {
                      console.log(`Dados iguais ${apielement.FI}`);
                    }else{
                      console.log(`Diferentes ${apielement.FI}`);

                    }

                  })
              }
            )

Comment: não pode por um exemplo prático para ajuda a entender? o `forEach` nada mais faz que verificar os elementos de um array, você pode inspecionar esse array a qualquer momento, em outras partes do código. *"le só devolve o ultimo dado, e não todos os dados"*, sim, a cada interação um elemento é acessado, quando acaba só tem referência ao último, a não ser que você guarde vários elementos... *"tem alguma forma de fazer um forEach com dois arrays?"* não, o forEach é para um objeto (array, collection) por vez, mas pode fazer um dentro do outro se quiser
Comment: Eu fiz um dentro do outro, mas aí eu precisava fazer a comparação do resultado de um com o outro, e nisso os resultados acabavam sendo repetidos, aí a comparação nao tinha o resultador correto. Vou colocar o meu código pra ajudar
Comment: @Maria aqui nao rola usar um for e navegar no outro array pelo indice nao? tem alguma chance dos array A ser diferente do B?
Comment: outra coisa se vc for array[indice][subindice].obj vc navega por ele fora do for each
Comment: é que eu preciso de um dado especifico que ta dentro deles, pra poder comparar um com o outro. Preciso percorrer o array pra acessar só um dado dele @Willian
Comment: Praticamente quase sempre os arrays vao ser diferentes e também vai ter igual sempre
Answer: Não entendi muito bem sua dúvida, mas essa função aqui faz a comparação entre os dois arrays, linha a linha, verificando os dados em cada posição se são iguais ou diferentes. Começa varrendo o primeiro array e percorre o segundo array comparando os indices.
const a = [1, 2, 3, 4, 5, 6, 7];
const b = [5, 4, 3, 1, 2, 5, 6];

a.forEach(function(valor){
    b.forEach(function(v) {
        if(v === valor)
            console.log('iguais');
        else
            console.log('diferentes');
    });
});

Comment: Não tem como ele mostrar uma unica vez os diferentes e iguais? Pq ele mostra os diferentes nos iguais, e só no final ele mostra quais sao realmente iguais e diferentes
Answer: this.MetaService.CheckOrderGet().subscribe(
data => {
const pesquisa = (data as any)
this.check = JSON.parse(pesquisa._body)

this.new = [];
for (var key in this.check) {
  if (this.check[key].FI == this.fil[key].FI){
   this.new[] = `Dados iguais ${this.check[key].FI}`;
  }else{
  this.new[] = `Diferentes ${this.check[key].FI}`;
  }
}

);

o new vai estar fora do forech
Comment: axo que tem em ema6 ou 7 o foreach de key value, transcreve ae se precisar
Comment: ta dando erro no  `this.new[] =` que fica dentro do if
Comment: `Dados iguais ${this.check[key].FI}`;
Comment: Com this.check dá erro, eu tive que colocar `Dados iguais ${apielement.FI}`;
Comment: o código ficou assim `this.check.forEach(apielement => {

                  this.fil.forEach(dados => {

                    for (var key in apielement) {

                      console.log(this.new);

                      if (apielement[key].FI == dados[key].FI) {
                        this.new = `Dados iguais ${apielement.FI}`;
                      } else {
                        this.new = `Diferentes ${apielement.FI}`;
                      }

                    }`
Comment: editei a resposta ae seria assim pelo que descreveu
Comment: isso dentro do forech? ele ta mostrando apenas os iguais, tem como ele mostrar os diferentes?
Comment: entao mais como que esta a estrutura vindo do backend? pq olhando daki parece que o codigo esta separando, me passa os dados do backend ou da uma analisada com um console.log(this.check[key].FI, this.fil[key].FI); abaixo do for e antes do if
Comment: me passa o array que tem do back end dos 2 array que teste aqui
Comment: os dados do this.fil vem de uma api, e os dados do this.check vem de outra api. pq quando os dados do this.check nao tiver no this.fil, ele deve ser inserido lá, e caso ja esteja, ele faz nada
Comment: array do this.check =`[
    {
      "FI": "24",
      "porc": "92,509%"
    },
    {
      "FI": "36",
      "porc": "51,445%"
    }
  ]`
array do this.fil = `(8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {FI: "15", porc: "167,701%"}
1: {FI: "02", porc: "138,763%"}
2: {FI: "33", porc: "110,720%"}
3: {FI: "30", porc: "103,536%"}
4: {FI: "24", porc: "100,733%"}
5: {FI: "04", porc: "96,082%"}
6: {FI: "03", porc: "84,180%"}
7: {FI: "20", porc: "75,897%"}`
Comment: da uma olhada ae rodou de boa https://ideone.com/L1dnQN
Comment: como n? igual: 24,diferente: 39,igual: 36, ae ve se e isso igual: 24 , 24,diferente: 39 , 37,igual: 36 , 36... olha la dinovo o ideone
Comment: no código aqui ficou assim: `    var neww = [];
                for (var key in this.check) {
                  if (this.check[key].FI == this.fil[key].FI) {
                    neww.push('igual: ' + this.check[key].FI);
                  } else {
                    neww.push('diferente: ' + this.check[key].FI);
                  }
                }

                console.log(neww);` certo? mas aí ele mostra no console só os diferentes, que na vdd os dados q ta mostrando nao ta correto, sao os dados iguais
Comment: ah vei;;; vc joga wow de troll ne... claro o console.log so ta no diferente... ponhe um no igual pra ver
Comment: acabei mostrando o código com um teste q eu tava fazendo, o correto é `       var neww = [];
                for (var key in this.check) {
                  if (this.check[key].FI == this.fil[key].FI) {
                    neww.push('igual: ' + this.check[key].FI);
                  } else {
                    neww.push('diferente: ' + this.check[key].FI);

                  }
                }
                console.log(neww);`
Comment: conseguiu @Maria? seguinte essa função que fiz ela verifica o array por posição caso os array não estiver igual, e melhor usar a do @JrD, pois ele vai fazer um loop em cada posição do array 2


How Can I use Stoke's Theorem to solve this Line Integral.

Question: Evaluate $\displaystyle \int_{C} y^2dx + z^2dy + x^2dz$ where $C$ is the curve of intersection of the sphere $x^2 + y^2 + z^2 = a^{2}$ and the cylinder $x^2 + y^2 = az$ $(a \gt 0, z \ge 0)$ integrated anticlockwise when viewed from origin.
For this line integral I feel that using Stoke's Theorem will be  more helpful,but I am not sure how to solve  for the normal vector $\hat{n}$.  and how to setup the integral
Can anyone tell me how can i setup the integral for Stoke's theorem ?
Thank you.
Comment: $x^2+y^2=az$ is not cylinder.
Answer: Your second surface is a paraboloid, not a cylinder. Regardless, the trick to Stokes' theorem is that you have the freedom to choose any surface with that curve as a boundary (since there are infinitely many) and you are guaranteed that the integral over all of them will be equal to each other.
In this case, notice that your curve of intersection is contained entirely within the plane $z=\frac{\sqrt{5}-1}{2}a$. So choose to parametrize that plane:
$$\mathbf{r}(x,y) = \left(x,y,\frac{\sqrt{5}-1}{2}a\right), \hspace{20 pt} x^2+y^2\leq \left(\frac{\sqrt{5}-1}{2}\right)^2a^2$$
The normal vector for a plane is easy, it's just $(0,0,1)$ in this case. Which is a bonus because if we're smart about this, we don't have to compute the whole curl, only the $z$ component which is
$$\frac{\partial Q}{\partial x} - \frac{\partial P}{\partial y} = -2y$$
And if we're even smarter, we'll recognize that the $z$ component of the curl is an odd function of $y$, and we are integrating over a surface (a disk) with $y$ symmetry, so we can conclude the integral is simply $0$ without parametrizing further.
Comment: How do u determine which curve to find line integral ? In my book it says it should be boundry and smooth and Piecewise but What if you have multiple boundaries


http 405 error in microsoft totorial - asp.net mvc

Question: the "create" part is giving me a headache
StudentsController.cs
using ContosoUniversity.Data;
using ContosoUniversity.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ContosoUniversity.Controllers
{
    public class StudentsController : Controller
    {
        private readonly SchoolContext _context;

        public StudentsController(SchoolContext context)
        {
            _context = context;
        }
        public async Task<IActionResult> Index()
        {
            return View(await _context.Students.ToListAsync());
        }

        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var student = await _context.Students
                .Include(s => s.Enrollments)
                    .ThenInclude(e => e.Course)
                .AsNoTracking()
                .FirstOrDefaultAsync(m => m.ID == id);

            if (student == null)
            {
                return NotFound();
            }

            return View(student);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("EnrollmentDate,FirstMidName,LastName")] Student student)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    _context.Add(student);
                    await _context.SaveChangesAsync();
                    return RedirectToAction(nameof(Index));
                }
            }
            catch (DbUpdateException /* ex */)
            {
                //Log the error (uncomment ex variable name and write a log.
                ModelState.AddModelError("", "Unable to save changes. " +
                    "Try again, and if the problem persists " +
                    "see your system administrator.");
            }
            return View(student);
        }

    }
}

Create.cshtml
@model ContosoUniversity.Models.Student

@{
    ViewData["Title"] = "Create";
}

CreateView

Student

        <form asp-action="Create">

                <input asp-for="LastName" class="form-control" />

                <input asp-for="FirstMidName" class="form-control" />

                <input asp-for="EnrollmentDate" class="form-control" />

                <input type="submit" value="Create" class="btn btn-primary" />

        </form>

    Back to List

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

if i remove "[HttpPost]" my model get's instantly updated and submitted with empty data and returns to index page
the link to actual tutorial:
https://learn.microsoft.com/en-us/aspnet/core/data/ef-mvc/crud?view=aspnetcore-5.0#update-the-create-page
thanks
Answer: found a solution ... i need another method for HttpGet, with same name (create) ... still unsure why, and it works now, no 405 error
if someone has a good explanation, please
this is what i added in controller:
public IActionResult Create()
        {
            return View();
        }

Comment: You create an `HttpGet` action in order to display the form to the user, then the user posts the form data to the controller `HttpPost` action. This is typical for an MVC application.  To update or create a record `HttpGet` is used to display the form, then `HttpPost` to receive the submitted data. The Post action is only used when the form is submitted
Answer: You only need to add method="post" to <form></form>.
<form asp-action="Create" method="post">

                <input asp-for="LastName" class="form-control" />

                <input asp-for="FirstMidName" class="form-control" />

                <input asp-for="EnrollmentDate" class="form-control" />

                <input type="submit" value="Create" class="btn btn-primary" />

        </form>

So that the form will include a hidden input which name is __RequestVerificationToken,which contains the value of AntiForgeryToken.When form submit,the token will be passed to Create action.
Comment: this didn't work, problem is probably somewhere else
Answer: since the action has an [ValidateAntiForgeryToken] attribute you should add the same to the view, and replace form tag with an html helper
@using (Html.BeginForm("Create", "Students", FormMethod.Post))
{
    @Html.AntiForgeryToken()

 .... and so on

}

and IMHO don' t use any bind at your post action, it is never a good idea
[HttpPost("~/students/create")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(Student student)

Comment: tried this too, same problem, 405 again ...
Comment: @turpija can you post the controlle too pls?
Comment: i added whole StudentsController.cs in original post
Comment: @turpija Thanks, I updated my answer too, should be using (Html.BeginForm("Create", "Students", FormMethod.Post))


Django 1.9 "Common Password Validator" - Strange Behaviour

Question: I'm attempting to replace the built in common-passwords.txt.gz file, which supposedly contains the top 1,000 common passwords, with my own identical version which contains the top 10,000 common passwords for my country, but I've encountered some rather strange behaviour.

Firstly I directly substituted Django's common-passwords.txt.gz file (4KB) with my own containing my .txt file with the same utf-8 encoding as Django (which comes in at 34KB), then restarted the test server. When changing a users password to "password" it does not raise the expected error as it does with Django's common password file.
The first line of both the built in password list and my new one begins 123456password12345678qwerty123456789... so it clearly should do.
When I append a few extra passwords to their common-passwords file it appears to work as it should and raise an error if I try to use them as passwords, so I don't think that it's cached somewhere or anything like that.
Is there some kind of built in file size limit for the common password list or for the gzip.open(password_list_path).read().decode('utf-8').splitlines() function?
Secondly, trying to figure out the above led me to a strange bug. Using Django's built in common-passwords.txt.gz (of which the first line starts 123456password12345678qwerty123456789...) successfully raises a validation error for "password" and "password1", but not for "password12" or "password123"!
As I read it, the Django validation code basically checks if the submitted password is in each line from the common passwords file, and I cannot find any code that exempts passwords above a certain length from the validation. Am I missing something or is this a bug?

The "common password validation" function in Django 1.9 is found in \venv\Lib\site-packages\django\contrib\auth\password_validation.py, the relevant class is below:
class CommonPasswordValidator(object):
"""
Validate whether the password is a common password.

The password is rejected if it occurs in a provided list, which may be gzipped.
The list Django ships with contains 1000 common passwords, created by Mark Burnett:
https://xato.net/passwords/more-top-worst-passwords/
"""
    DEFAULT_PASSWORD_LIST_PATH = os.path.join(
        os.path.dirname(os.path.realpath(upath(__file__))), 'common-passwords.txt.gz'
    )

    def __init__(self, password_list_path=DEFAULT_PASSWORD_LIST_PATH):
        try:
            common_passwords_lines = gzip.open(password_list_path).read().decode('utf-8').splitlines()
        except IOError:
            with open(password_list_path) as f:
                common_passwords_lines = f.readlines()

        self.passwords = {p.strip() for p in common_passwords_lines}

    def validate(self, password, user=None):
        if password.lower().strip() in self.passwords:
            raise ValidationError(
                _("This password is too common (it would be trivial to crack!)"),
                code='password_too_common',
            )

    def get_help_text(self):
        return _("Your password can't be a commonly used password.")

Comment: I don't think it's a good idea to substitute the file by overwriting it. Here is an example of how to use the validator with your custom path https://github.com/orcasgit/django-password-validation/blob/master/password_validation/test/test_validators.py#L151. Could you provide more context of where you are going to use the validator?
Comment: I'm attempting to use the validator everywhere that a person can create a password in my app (currently only the admin interface, but eventually on custom forms too!), thats why I'm trying to directly replace the built in list with my own.

Can you test with your version of Django if it raises an error for Password12 or Password123?
Answer: Finally got to the bottom of this!
There is some kind of invisible unrendered character in-between the passwords contained in Django's built in common passwords validation file, this explains both issues I encountered.
I changed my top 10k common passwords file to have the usual newline characters between them instead and now it all works great! Even though there are now 10 times as many passwords for it to compare against it still runs pretty much instantaneously!
I've uploaded my 10,000 most common passwords file to github for any future people who encounter this issue or who just want to improve Django's built-in common password validation: https://github.com/timboss/Django-Common-Password-Validation/


Postfix Relay Networks Relay

Question: Can i use Domain Name instead of IP Public Address in Postfix Relay?
I tried the pattern like this but it doesn't work
#Not Work
mynetworks = 192.168.1.0/24, 127.0.0.1/24, 192.168.2.0/24, mail.fendyfy.com
#Work Finely
mynetworks = 0.0.0.0/0
#Work(But idk why my email landed in SPAM)
mynetworks = 192.168.1.0/24, 127.0.0.1/24, 192.168.2.0/24, 18.104.22.168
#Error Code
Relay access denied; email@example.com email@example.com proto=ESMTP helo=<WINSVR.fendyfy.local>
Answer: I think you may be confused about what mynetworks is doing in the Postfix configuration: it is the list of network IP ranges from which Postfix will accept email for delivery, without additional authentication.
This is a limitation on the connecting client, and not on the messages - so if a message is accepted for delivery, it will be delivered. Postfix doesn't do SPAM detection by itself, and depending on what you use for SPAM detection, that might take I think you may be confused about what mynetworks is doing in the Postfix configuration: it is the list of network IP ranges from which Postfix will accept email for delivery, without additional authentication.
This is a limitation on the connecting client, and not on the messages - so if a message is he originating IP address under consideration (ormore likely, now)accepted for delivery, it will be delivered. Postfix doesn't do SPAM detection by itself, and depending on what you use for SPAM detection, that might take the source IP address under consideration (or, more likely, not) but Postfix mynetworks setting does not factory into it.
Now as to whether mynetworks setting accepts host names: the answer to that is no. The documentation says:

Specify a list of network addresses or network/netmask patterns

"network addresses" here means IP addresses and not names.
Comment: i see, if i change mynetworks to 0.0.0.0/0,
but the client must auth first using username&password before using my SMTP,
is that a best practice?, btw i tried using postfix SASL but it doesnt working...
i still can send email through my smtp anywhere like smtper.net etc...
Comment: `mynetworks` is specifically all the networks where the client *isn't required* to auth - never set it to `0.0.0.0/0`: that is an "open relay" and way to spam the world. I'm a little hazy on what you are trying to achieve - are you looking to limit messages coming into your relay, or messages going out from your relay?
Comment: i use 0.0.0.0/0 because my Exchange server IP is dynamic, so what should i do for that...
Comment: If your Exchange server is on the LAN, and the Postfix relay is on a DMZ or something (so it can see the LAN address), just set the LAN address range in `mynetworks`. If your Exchange is on the internet and you really don't know anything about the possible addresses - set your Exchange server to deliver mail using SASL authorization. There are tutorials on the web.

Postfix Relay Networks Relay


Why is this algebraic curve irreducible?

Question: I have found this in a book:

but I don't know why the curve $x^m-y^n=0$ is irreducible when n, m are coprimes.
Can someone help me?
Answer: Here's one way to see it.  There may be cleaner ones, but this has the advantage of being a brute-force approach that doesn't require any cleverness or special machinery.
Consider the ring $R := k[x, y] / (x^m - y^n) = k[x, \sqrt[n]{x^m}]$.  We want to show that $R$ is an integral domain, because this is equivalent to $(x^m - y^n)$ being prime, which is equivalent to the curve $x^m - y^n = 0$ being irreducible.
A general element of $R$ looks like
$$p_0(x) + p_1(x) \sqrt[n]{x^m} + p_2(x) \left(\sqrt[n]{x^m}\right)^2 + \cdots + p_{n-1}(x) \left(\sqrt[n]{x^m}\right)^{n-1}$$
where the $p_i$ are polynomials, and moreover this representation is unique.  (For uniqueness, we're using that $m, n$ are relatively prime).
So, take another element, say
$$q_0(x) + q_1(x) \sqrt[n]{x^m} + q_2(x) \left(\sqrt[n]{x^m}\right)^2 + \cdots + q_{n-1}(x) \left(\sqrt[n]{x^m}\right)^{n-1},$$
multiply them together, and show that if you get zero from this then either all the $p_i$ were zero or all the $q_i$ were zero.