prove the homeomorphism about torus

Question: Let $\Phi :[0,2\pi] \times [0,2\pi] \rightarrow R^{3}$ be given by  $$\Phi(\theta,\phi)=((A+\cos\phi)\cos\theta,(A+\cos\phi)\sin\theta,\sin\phi), \quad A>1
$$
Explicitly prove that image of $\Phi$ is homeomorphic to $S^{1}\times S^{1}$.
First of all,$[0,2\pi]$ is homeomorphic to $S^{1}$ by gluing 0 and $2\pi$ together via exponential function. Then by introducing an equivalent relationship on $[0,2\pi] \times [0,2\pi]$,we have a quotient map.from university property of quotient map,we know that map induced from $\Phi$ which is from $S^{1}\times S^{1}$ to image of $\Phi$ is continuous .Surjective is obvious.I don't know how to prove injective and continuity of the inverse. Could anyone give some help?
Answer: This is an application of a standard theorem of topology which you can find, for example, in Munkres "Topology", which goes like this.
If $f : X \to Y$ is a continuous, surjective function from a compact space $X$ to a Hausdorff space $Y$, then $f$ is a quotient map (the proof is elementary, and uses the fact that a compact subset of a Hausdorff space is closed, and a closed subset of a compact Hausdorff space is compact).
Furthermore, let $Q$ be the quotient space of $X$ obtained by decomposing $X$ into the point pre-images $f^{-1}(y)$, $y \in Y$. Also let $F : Q \to Y$ be the induced function $F(f^{-1}(y))=y$. Then $F$ is a homeomorphism (again the proof is elementary, being just an application of the definition of a quotient map and the quotient topology).
In your example, $X = [0,1] \times [0,1]$ which is clearly compact, $Y$ is a subspace of $\mathbb{R}^3$ which is clearly Hausdorff, and $f$ is clearly continuous and surjective.

prove the homeomorphism about torus


Firebase show data in select form - angular

Question: I'm trying to show data in select form, from table heroes and "nombre"
this is a name of client.

In my second table I want to show them while adding products to
attribute clients to them.

Can any one help me to this? I'm new to angular :)
heroes.component.ts
import { Component, OnInit } from '@angular/core';
import { HeroesService } from '../../services/heroes.service';
import { HeroeModel } from '../../models/heroe.model';
import {AngularFireDatabase } from 'angularfire2/database';

import Swal from 'sweetalert2';

@Component({
  selector: 'app-heroes',
  templateUrl: './heroes.component.html',
  styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {
  heroes: HeroeModel[] = [];
  cargando = false;

  constructor(private heroesService: HeroesService) {}

  ngOnInit() {
    this.cargando = true;
    this.heroesService.getHeroes().subscribe(resp => {
      this.heroes = resp;
      this.cargando = false;
    });
  }

  borrarHeroe(heroe: HeroeModel, index: number) {
    Swal.fire({
      title: 'Uwaga!',
      text: `Czy chcesz trwale usunąć kontrahenta ${heroe.nombre}?`,
      type: 'warning',
      showConfirmButton: true,
      showCancelButton: true
    }).then(resp => {
      if (resp.value) {
        this.heroesService.deleteHeroe(heroe.id).subscribe(resp => {
          this.heroes.splice(index, 1);
        });
      }
    });
  }
}

add-products.component.ts
import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import Swal from 'sweetalert2';
import { Observable } from 'rxjs';
import { ActivatedRoute } from '@angular/router';
import { ADDProductsModel } from 'src/app/models/add-products.model';
import { ProductsService } from 'src/app/services/products.service';
import { HeroesComponent } from 'src/app/pages/heroes/heroes.component';
import { HeroeComponent } from 'src/app/pages/heroe/heroe.component';

@Component({
  selector: 'app-add-products',
  templateUrl: './add-products.component.html',
  styleUrls: ['./add-products.component.css']
})
export class ADDProductsComponent implements OnInit {

  ADDProducts: ADDProductsModel = new ADDProductsModel();

  constructor(
    private ProductsService: ProductsService,
    private route: ActivatedRoute
  ) {}

  ngOnInit() {
    const id = this.route.snapshot.paramMap.get('id');

    if (id !== 'new') {
      this.ProductsService.getADDProducts(id).subscribe((resp: ADDProductsModel) => {
        this.ADDProducts = resp;
        this.ADDProducts.id = id;
      });
    }
  }

  guardar(form: NgForm) {
    if (form.invalid) {
      console.log('Nieprawidłowy format');
      return;
    }

    Swal.fire({
      title: 'Ładowanie',
      text: 'Trwa zapis...',
      type: 'info',
      allowOutsideClick: false
    });

    Swal.showLoading();

    let peticion: Observable<any>;

    if (this.ADDProducts.id) {
      peticion = this.ProductsService.actualizarADDProducts(this.ADDProducts);
    } else {
      peticion = this.ProductsService.crearADDProducts(this.ADDProducts);
    }

    peticion.subscribe(resp => {
      Swal.fire({
        title: this.ADDProducts.number,
        text: 'Dodano pomyślnie',
        type: 'success'
      });
    });
    console.log(form);
    console.log(this.ADDProducts);
  }
}

Comment: You can use `@input` and `@output ` directive, for component interaction. You can send data to child component using `@input `and from child to parent you can send event emmiter using `@output`. Alternatively, you can use rxJS Subject too.. in your case you can consider your two components heros and add-item interaction with this approach.
Comment: What is the problem?
Comment: That I don't know how to download data to fill form to another component :( I have been trying to deal with this for hours.
Comment: @GaurangDhorda will it work with Firebase?
Comment: Yes, first you need to get all data from firebase and then pass data to component property, and that data again used as input data for child component, `` this is your child component. And in child component get data like this.. `@input('childData') childPropData;` and then you can use data in html like `{{ childPropData.fieldName}}`
Comment: @GaurangDhorda when i'm using
in child component I can see parent component https://i.imgur.com/tGYltk6.jpg not data from {{heroe.nombre}}
Comment: better screen https://imgur.com/kmjONzA
Answer:
First, Consider Parent-Child model of communication in component interaction. For ease I am not going to include any firebase part here. I assume you are working with firebase Data very fine.

Now Your problem is how to send data back from child to parent so here is your solution.
Complete solution is found here in StackBlitz Link

app.component.html

       Name comes form child in Parent Component
      <select>
          <option> Select Name </option>
          <option *ngFor="let item of nameFromChild"> {{item}} </option>
      </select>

app.component.ts
 export class AppComponent  {
        nameFromChild: string[] = []; // your property.
        /*
            nameFromChildFun() is called when there is data emitted from child-component.
            @parms ='nameFromChild' : gets parameter from child using $event from app.component.html.
        */
        nameFromChildFun(nameFromChild){
               this.nameFromChild.push(nameFromChild); //name pushes to property. and displaying in select tag using *ngFor.
        }
 }

child.component.html
 <input type ="text" [(ngModel)]="name">

 <button (click)="sendNameToParent(name)"> Add Name to Parent </button>

child.component.ts
 import { Component, EventEmitter, Output } from '@angular/core';

 export class ChildComponent implements OnInit {
        @Output() nameFromChild = new EventEmitter();
        // nameFromChild is passed in app.component.html in <app-child (nameFromChild)="nameFromChildFun($event)

        sendNameToParent(name){
             this.nameFromChild.emit(name); // emitting value to parent.
        }
 }

Now when user clicks in childComponent`s addNameToParent button then, call your firebase service here to Save ot Update data first and then load those data in parent app.component.
Comment: The problem is that after doing your code nothing shows up in dropdown form :(
Comment: I don't have any idea at this moment what I'm doing wrong ....
Comment: What have you been tried? And have you checked stackblitz?
Comment: Yes, and after implementing your code nothing shows up in a component that data should be shown up.


Recommendations - or best practices - for analyzing non-independent data. Specific example relating to pain perception data provided

Question: I am seeking recommendations and/or best practices for analyzing non-independent data. In particular, I am curious about non-independent data that does not reflect typical repeated-measures time-based data in which data for the same question(s) or stimuli are collected at different time points. Rather the data collected is elicited from similar (but not identical) questions or stimuli that are known to be related. A specific example follows.
I have pain perception data for two groups (group A, group B) that can be further divided by gender (i.e., A-women; A-men; B-women; B-men). The pain perception dependent variables include 3 thermal threshold tests (i.e., detection, pain, tolerance) and pain magnitude estimates for a range of specific temperatures (temp X1, X2, X3, X4, X5). These pain perception variables are collected for both heat and cold stimuli (e.g., heat pain tolerance; cold pain tolerance; heat temp X1; cold temp X1). It should be expected (and indeed it is observed) that the various pain perception variables for a given individual are not independent.
The purpose of the analysis is to look for between group differences based on group membership (group A vs. group B) and sex (women vs men). It is desirable to find interactions between group membership and sex. It is also desirable to find interactions between specific pain perception variables (or types of variables; i.e., "cold stimuli") and group membership and/or sex. I have tried running a series of repeated-measures ANOVAs separately for each of the different groupings of pain perception variables (i.e., heat stimuli threshold tests; cold stimuli threshold tests; heat pain magnitude estimates; cold pain magnitude estimates); however this solution does not feel optimal or adequate. My specific questions are:
1) is it appropriate to analyze data elicited from related (but not identical) questions/stimuli using repeated measures?
2) Is it appropriate to analyze chunks of the data (e.g., cold pain magnitude estimates; cold stimuli threshold tests) separately?
2) Would a different strategy (such as multilevel analysis / profile analysis / or some type of multivariate repeated measures ANOVA) be more appropriate?
3) General recommendations and/or best practices for analyzing data such as this.
Thank you for your feedback and input
Patrick Welch
note: I already searched the site for related questions (i.e., ANOVA with non-independent observations ; Parametric techniques for n-related samples) but believe the current question to be different enough to warrant unique consideration.
Answer: As to your suggestion of using Multi-level models in this and the other thread, I see no benefit of approaching your analysis in this manner over repeated measures ANOVA. MLM are simply an extension of OLS regression, and offer an explicit framework to model group level (often referred to as "contextual") effects on lower level estimates. I would guess from your example you have no specific "contexts" besides that measures are repeated within individuals, and this is accounted for within the repeated ANOVA design (and your not interested in measuring effects of specific individuals anyway, only to control for this non-independence). Neither groups nor gender with what your description says are "contexts" in this sense, they can only be direct effects (or at least you can only observe if they have direct effects).
MLM just complicates things in this example IMO. It doesn't directly solve your problem that several dependent measures are non-independent, you can't measure any group level characteristic on your outcome because you only have two groups, and your hierarchy is cross classified and has three levels, (an observation is nested within only 1 individual, but the gender and group nestings are not mutually exclusive). All of the things you listed as purposes of the project can be accomplished using repeated ANOVA simply including group, gender, and group*gender interaction effects into the models.
It is beyond the scope of your question, but I would never agree that gender is a group observations are nested within.
Answer: If temperature levels X1...X5 are specific degree values, I'm not sure how temperature and stimulus (hot/cold) can be completely crossed. I presume then that "temperature" consists of 5 ordinal categories, ranging from "likely to cause minimal discomfort" to "likely to cause maximum discomfort permissible by my research ethics board", which then permits crossing with hot/cold direction.
If this is the case, you are correct that the 3 response variables might not be expected to be independent, so you might increase your power (relative to 3 seperate analyses) if you do a multivariate test. Frankly, I must admit that my first inclination would be to simply do three separate analyses, one for each response variable, but that's because I'm not very knowledgeable with regards to the mechanics of multivariate tests. That said, given the likely dependence between the 3 response variables, significant results across 3 separate anovas might be most reasonably considered as manifestations of this dependence rather than 3 truly independent sets of phenomena.
I am pretty sure that you shouldn't lump all 3 response variables into a single univariate analysis by adding "response variable type" as a predictor variable; this approach could run into trouble if the scales and variances of your response variables are very different. Presumably, a multivariate analysis has features that take such differences into account. (However, I wonder if a mixed effects analysis might also be able to handle such differences? I'm new to mixed effects, but suspect I it might...)
Comment: Hi Mike, thank you for your feedback. Temperature levels X1....X5 are specific degree values (i.e., heat stimuli = 42C, 44C, 46C, 48C, 50C; cold stimuli = 8C, 6C, 4C, 2C, 0C); however, they can also be conceptualized as stimuli ranging from "likely to cause minimal discomfort (i.e., 42C or 8C)" to "likely to cause maximum discomfort permissible by my research ethics board (i.e., 50C, 0C)". With this being the case do you think that a series of univariate repeated measures or a multivariate analysis is ok?
I too am am interested to hear suggestions from any mixed effects/multivariate gurus
Answer: I don't think that repeated measures is appropriate here - as I understand your protocol, the five temperatures (either hot or cold) are not repeated measures as they occur at different temperatures.
However, it does feel like you need some data reduction across the five levels in each temperature group.  You might be well-served to consider some exploratory analysis to decide what the general shape of the relationship of pain perception to ordinal temperature input is across the hot and cold groups; then reduce that to a linear slope or exponential function; then model that single variable as your dependent variable with gender and A/B as factors.
Latent growth curve modeling might also be appropriate, but that is beyond me.


Nested Nginx location (prefix blocks in regex blocks) not working

Question: I'm having trouble understanding nested locations in nginx.  I have two locations with some configuration directives in common, so rather than repeat the directives, I'd prefer to repeat the URI using a regular-expression:
location ~ /a|/b {
        location /a {
        }
        location /b {
        }
}

However, this gives the error
nginx: [emerg] location "/a" is outside location "/a|/b" in /etc/nginx/nginx.conf:36

Without the or | it seems okay, though.
location ~ /a {
        location /a {
        }
}

What am I doing wrong?  Is there a better way to do this without repeating anything?  Can I group locations in another way?
Comment: because logically they are grouped
Comment: This took me a long time to understand but in the end I was able to create a simple(ish) [priority list of how locations are chosen](https://artfulrobot.uk/blog/untangling-nginx-location-block-matching-algorithm).
Comment: http://forum.nginx.org/read.php?2,174517,174534#msg-174534
Comment: There is a ticket for improving location docs: https://trac.nginx.org/nginx/ticket/1467
Answer: Old question, but the issue is because the parent location is a regex location while the nested locations are prefix locations.
When a parent location is defined by a regex, any nested locations must also be defined by regexes:
location ~ ^/(a|b) {
        location ~ ^/a {
        ...
        }
        location ~ ^/b {
        ...
        }
}

You may only define nested prefix locations when the parent location is also a prefix location:
location /a {
        location /a {
               # You can also skip this location and just write
               # your code directly under the parent location
        }
        location /a/b {
        ...
        }
}

However, you may define nested regex locations when the parent location is a prefix location:
location /a/b {
        location ~ /a {
        ...
        }
        location ~ /b {
        ...
        }
}

Comment: That first sentence should be in the [documentation](http://nginx.org/en/docs/http/ngx_http_core_module.html#location).
Comment: Ah nevermind I misunderstood. The nested locations don't inherit anything from their parent locations.
Comment: In the first example, if you leave out the `location /a { }` boilerplate -- does the order matter?
Comment: I got confused by your first sentence, but your examples make sense.  I assume in the last example, the prefix location `/b` will throw an error?
Comment: the comment in the 1st example almost answers my question. If I put directives in the top location block are they inherited by all nested location blocks, or do the nested blocks need to repeat or override those directives?
Comment: The parent location can be a non regex location but any multiple nested locations within the parent have to all be either regex / non regex.
Comment: This does not explain why the asker's second example would work.
Comment: @purefanatic. It doesn't explain this because the second example will not work. A Prefix Location Block will fail when nested in a Regex Location Block as shown.
Comment: @Dayo But you are wrong: The asker's second example works just fine while you claim it shouldn't. It's exactly that: a prefix location block nested in a regex location block, yet it still works. And I don't know why it works, neither does the asker and your answer does not explain it.
Comment: And even if the second example of the asker *didn't* work I feel like an answer should point that out because the whole question presupposes that it *does* work.
Comment: @purefanatic. It could be that it does work now but pretty certain that would not have worked when the answer was written. As for your feeling about what should have been pointed out, feel free to add an answer of your own on this.
Comment: @purefanatic, @Dayo: The second example is regex location nested in regex location. `location ~ ^/a` defines regex, `location /a` is prefix, although both match same urls.


Finding the eigenvalue and eigenspace for a function defined as the intersection of element of A and B

Question: Let $S$ be a non empty set and let $V_S$ be the set of all the subsets of $S$.
$V_S=\{A:A⊂S\}$
Now fix an element $B$ of $V_S$ and define a function $f:V_S \rightarrow V_S$ by $f(A)=A∩B$. Find the eigenvalues and eigenspaces of $f$.
Comment: Typically "eigen-values" and "eigen-vectors" are associated to linear transformations on a vector space. Your question does not seem to deal with that, so perhaps you can also define these terms in your setting.
Comment: Perhaps it would help to clarify this question.  For instance, what is $S$?  Do you want all subsets or subspaces?  If $Vs$ is a set of subsets, it's not necessarily a linear space.  Do you want $f:Vs\rightarrow Vs$?
Comment: Your question doesn't make sense.
Answer: the power set may be regarded as a vector space over the field $F_2$, by identifying each subset with its indicator function. addition is the exclusive or operation (symmetric difference), for which the identity is the empty set, and with each set  being its own additive inverse (characteristic 2).
in this setup subset means subspace. the intersection with a fixed set is thus a projection operator which can take only the eigenvalues 0 or 1. perhaps you can identify the corresponding eigenspaces?
Comment: Thank you so much David !! Can I know how you know that addition is the exclusive or operation (symmetric difference) in this question ?
Comment: if you think of the components of a vector as elements of $F_2$ (so each is 0 or 1) the addition table is $0+0=0; 0+1=1+0=1;1+1=0$
Comment: @DavidHolden Can the power set still be a vector space over some other field that have more than 2 elements?


Cardinality of different properties of binary relations

Question: English isn't my first language, so I tried to translate it as best as I could.
$A$ and $B$ are finite sets. In dependence of $|A|$ and $|B|$ give the number of  relations of $R \subset A \times B$  with the following properties:
a) R is right-unique
b)R is right-unique but not left-total
c)R is left-total or not right-unique.
Hint: The number of functions from $A$ to $B$ is $|B^A| = |B|^{|A|}$

My Answer:
a)Right-unique: $\forall a\in A$ $\forall b\in B$ $\forall c\in B$: $(a,b)\in R \land (a,c)\in R \Rightarrow b=c$
That means every $a\in A$ can have at most one partner in $B$ ("One or less").
So the number of relations should be $|B^A| \leq |A|$
b)Right-unique: $\forall a\in A$ $\forall b\in B$ $\forall c\in B$: $(a,b)\in R \land (a,c)\in R \Rightarrow b=c$
And not left-total:$\lnot(\forall a\in A$ $\exists b\in B: (a,b) \in R) \Leftrightarrow \exists a\in A$ $\forall b\in B: (a,b) \notin R$
Right-unique: every $a\in A$ can have at most one partner in $B$.
not left-total: There exists at least one $a\in A$ for all $b \in B$ so that $(a,b)\notin R$ (so that there is no relation).
$|B^A| \lt |A|$, it can't be $|A|$ since there exists at least one $a \in A$ so that the relation doesn't work
c)left-total: $\forall a\in A$ $\exists b\in B: (a,b) \in R$
not right-unique:  $\lnot[\forall a\in A$ $\forall b,c\in B$ : $(a,b)\in R \land (a,c)\in R \Rightarrow b=c]$
$\Longleftrightarrow $$\exists a\in A$$\exists b\in B$ $\exists c\in B$: $\lnot((a,b)\in R \land (a,c)\in R \Rightarrow b=c)$
$\Longleftrightarrow $$\exists a\in A$$\exists b\in B$ $\exists c\in B$: $(a,b)\in R \land (a,c)\in R \Rightarrow b \neq c)$
left-total: every $a\in A$ has at least one partner in B
not right-unique: There exists at least one $a\in A$, at least one $b \in B$ and at least one $c \in B$ so that $(a,b)\in R \land (a,c)\in R$ so that $b \neq c$.
That means there is at least one $a \in A$ that has at least two partners in $B$.
There have to be more relations then there are elements in $A$.
If it was only left-total then $|B^A| \geq |A|$
But since it's left-total or not right-unique:
$|B^A| \gt |A|$
Is my answer correct? Because I didn't use the cardinality of B at all.
Answer: In the case of (a), right-uniqueness does not guarantee the domain of $R$ is $A$. In fact, the domain could be empty. However, if the domain of $R$ is known, say it $X$, then $R$ must be a function between $X$ and $B$. Furthermore, any function from $X\subseteq A$ to $B$ is right-unique. Therefore the number of right-unique relations is
$$\sum_{X\subseteq A}|B|^{|X|} = \sum_{k=0}^{|A|} \binom{|A|}{k} |B|^k.$$
For (b), observe that right-unique, left-total relations are exactly functions from $A$ to $B$. Therefore we can count relations satisfying (b) by subtracting $|B|^{|A|}$ from the result in (a).
(c) is the mere negation of (b), and the total number of relations is $2^{|A||B|}$. Could you see how to get an answer?
Comment: Thanks for your clarification. I got the first part with $X \subseteq A$ but I don't understand how you got the sum with the binomial coefficient.
Comment: @franz3 It relates to counting the number of subsets of $|A|$ whose cardinality is $k$.
Comment: @HanulJeonWhy did you multiply it with $|B|^k$ at the end
Comment: @franz3 This term came from $|B|^{|X|}$; just replacing $|X|$ to $k$ then we have it.
Comment: @HanulJeonyou assumed that the relation from X to be is a function, that means you say that the relation R is left-total and right-unique. But shouldn't I only assume that the relation R is only right-unique. That means it wouldn't be a function
Comment: @franz3 You are right, and this is what I have pointed out. However, I restricted $R$ to a relation between $X=\operatorname{dom} R$ and $B$. Then $X$ is a function between $X$ and $B$, since $R$ is now left-total by definition of $X$.


set type of any of javascript object property

Question: I have the following javascript object
 venue = {
    id: 0,
    name: '',
    venueimage_set: [
      {
        imageurl: '',
      },

    ]...

then later in my code I change the object:
 this.venue.venueimage_set[+image] = this.venue.venueimage_set[+image].imageurl;

for a image viewer to work I need the url of the image only not the key that the image url is part of. So I take whats in the key and set the array position to the keys value, the image url.
then I get this noise.
ERROR in mainroot/venuepage/venuepage.component.ts(171,25): error TS2322: Type 'string' is not assignable to type '{ imageurl: string; }'.
mainroot/venuepage/venuepage.component.ts(175,127): error TS2339: Property 'imageurl' does not exist on type 'string'.
I would like typescript to ignore typing and just let me do this. How would I?
Comment: Why are you using typescript at all if you are doing some very weird type mixing? `for a image viewer to work` there will be probably a far more elegant way that also ensures typesafety.
Comment: @JonasW. because I want  my slideshow plug in to work, and I am using typescript because angular uses typescript, and I hate javascript. Even in Java I can manipulate and cast types as I see fit if I have to in werid uses cases like these
Comment: Just add `as any` following the expression.
Comment: @JonasW. there most likely are but I am not going to let my bussiness hold off while I make a more elegant solution to something so trival. Just want it to work and move on.
Comment: Writing unsafe code might work "now" but it might somehow stop working somewhen and then you are in troubles.
Comment: @JonasW. this is interesting I literrally add the words `as any` to the end of the expression? I tired it out and it seems to work.
Comment: @JonasW. and I won't be doing what you are suggesting in your answer only because this is a placeholder object. The object gets replaced with an object  from the database. its just to make my code not break while it is waiting for the http reponse on the inital of the component
Comment: Then just turn that response into a Venue when it arrives and assign that.
Answer: Here is a typesafe version of what you're trying to do:
function toVenue<T>({id, name, venueimage_set}: T) {
  return {
    id,
    name,
    venueImageSet: venueimage_set.map(el => el.imageurl)
  };
}

Which can be used when setting venue:
const venue = toVenue({
    id: 0,
    name: '',
    venueimage_set: [{
       imageurl: '',
    }]
});

And here the unsafe version (please don't do this):
this.venue.venueimage_set[+image] = this.venue.venueimage_set[+image].imageurl as any;

Comment: the as any was not accepted  in my code. this is werid


Proof verification for proving the inequality $\limsup(a_n+b_n)\ge \liminf a_n+\limsup b_n$

Question: I want to prove that for any sequences $(a_n)$ and $(b_n)$, the following holds $$\limsup(a_n+b_n)\ge \liminf a_n+\limsup b_n \tag 1$$
I want to prove the above inequality only for the case when quantities on RHS are finite.
I'm using the following definition.
Definition: $\liminf_{n\to \infty} x_n= \lim_{n\to \infty} (\inf_{m\ge n}x_m)$, where quantity in parentheses on RHS is $\inf\{x_m: m\ge n\}$.
Now, RHS can be simplified using the definition as follows:
$\liminf a_n+\limsup b_n=\lim (\inf_{m\ge n} a_m+\sup_{m\ge n} b_m)$. Let $u_n:=\sup_{m\ge n} b_m $
For any $n$, there exists some $m'\ge n$ such that $$\inf_{m\ge n} a_m+(u_n-\frac 1n)\le a_{m'}+b_{m'}\le\sup_{m\ge n}(a_m+b_m)\tag 2$$
It follows by $(2)$ that $\inf_{m\ge n} a_m+u_n-\frac 1n\le \sup_{m\ge n}(a_m+b_m)$, which gives  $$\lim_{n\to \infty}(\inf_{m\ge n} a_m+u_n-\frac 1n)\le\lim_{n\to \infty}\sup_{m\ge n}(a_m+b_m)\tag 3$$ and LHS of $(3)$ (by limit rules and noting that $\frac 1n\to 0$) simplifies to $\liminf a_n+\lim u_n\le\limsup (a_n+b_n)$. This proves $(1)$.
Is my proof correct? Thanks.
Answer: You are making it too complicated.
$(a_n+b_n) \ge \inf_{m \ge n}a_m+b_n$ for all $n$.
Hence $\sup_{k \ge n} (a_k+b_k) \ge \sup_{k \ge n} (\inf_{m \ge k}a_m+b_k)$.
Note that $\inf_{m \ge n}a_m \to \liminf_n a_n = \sup_n \inf_{m \ge n}a_m$, hence taking limits we get the desired result.
(Note that if $c_n \to c$, then $\limsup_n (c_n+b_n) = c + \limsup_n b_n$.)
Comment: Take $a_n=(-1)^n$ and $b_n=(-1)^{n+1}$. For $n$ even your first display does not hold.
Comment: @VáclavMordvinov I need more alcohol. Thanks for catching that.
Answer: Here is a possible answer based on the properties
$$\limsup_{n \to \infty}(a_n + b_n) \leq \limsup_{n \to \infty}(a_n) + \limsup_{n \to \infty}(b_n) $$
and
$$ - \limsup_{n \to \infty} (-a_n) = \liminf_{n \to \infty} (a_n). $$
Both of these follow from the definitions. Well,
$$b_n = (b_n + a_n) - a_n $$
so that the first property implies
$$ \limsup_{n \to \infty}(b_n) \leq \limsup_{n \to \infty}(b_n + a_n)  + \limsup_{n \to \infty}(-a_n)  $$.
Now move $\limsup_{n \to \infty}(-a_n)$ to the LHS and use the second property.
Comment: Is the step just before $(3)$ in my post correct or is my overall proof correct? Thanks.


angular js upload file function does't work as expected

Question: using angular to make upload file function and flask as the backend server.
However when I try to upload the file , always get error message.
Here are the codes.
HTML Elements:
        <input class="paper-trade__upload-button_hidden" type="file" id="csv-upload" name="file" accept=".csv" ngf-max-size="2MB" (change)="csvToArray($event)">

Angular:
    csvToArray(fileInput: any) {
    const hotInstance = this.hotRegisterer.getInstance(this.instance);
    let fileReaded = fileInput.target.files[0];
    this.tradeCaptureService.uploadPaperTradeCSV('KGI',
    fileReaded).subscribe();
    }

the request body:
uploadPaperTradeCSV(brokerName: string, file): Observable<Trade> {
const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'multipart/form-data',
  }),
};
let formData: FormData = new FormData();
formData.append('file', file);

return this.http.post<Trade>(`${this.baseUrl}/trade/upload?broker_name=${brokerName}`, formData, httpOptions)
  .pipe(
    tap(data => console.log(data)),
);

}
Backend codes(python): as the request.files the requirments, send the file data as form-data
    @hello.route('/upload', methods=['POST'])
@jwt_required
def import_trades():
    if request.method == 'POST':
        broker_name = request.args.get('broker_name', '')
        data = request.form.get('file')

        if 'file' not in request.files:
            return jsonify({'fail': 'no file found'})
        file = request.files['file']
        if not file.filename:
            return jsonify({'fail': 'no file selected'})
        file_format = file.filename.split('.', 1)[1].lower()
        allowed_extension = set(['csv'])
        if file and file_format in allowed_extension:
            filename = secure_filename(file.filename)
            file_path = os.path.join(UPLOAD_FOLDER, filename)
            file.save(file_path)
            response = trade_orm.convert_file_data(broker_name, file_path)
            if os.path.exists(file_path):
                os.remove(file_path)
            return response
        else:
            return jsonify({'fail': 'please input valid info'})

However I try to upload the file , it always return 'no file found' message.Buy when using Postman to send request, it works fine.I stuck here for quite long time .....
Any help would be great appreciated, thanks for the help
Comment: And what is the error message
Comment: 'no file found',  somehow it just can't find the key word 'file' in the reqeust.files.
Answer: I finally find the solution for this issue, remove the 'const httpOptions = {}' staff in uploadPaperTradeCSV() method, then the would work well.so the new code would be like this
uploadPaperTradeCSV(brokerName: string, file): Observable<Trade> {

let formData: FormData = new FormData();
formData.append('file', file);

return this.http.post<Trade>(`${this.baseUrl}/trade/upload?broker_name=${brokerName}`, formData, httpOptions)
  .pipe(
    tap(data => console.log(data)),
);

but still I cant figure out why...


MultiThreading with instance variable java

Question: I have a class like,
Class A extends B {

   String test = "";
   String first = "";

   public void testMethod() {
      new Thread() {
         public void run() {
           testThreadMethod();
         }
      }.start();

   }

   public void testThreadMethod() {
     System.out.println(first + " " + test);
   }
}

The above class compiles fine. But in run time, the error is thrown in system.out.println() saying "invalid thread access".
Is there any wrong in the code. Accessing instance variables in multithread not allowed? Is there any way to access the instance variable inside the thread?
Thanks in advance.
EDITED NEW: To Reproduce the problem
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.part.ViewPart;

public class SWTView extends ViewPart{
    public static Display display;
    public static Shell shell;
    static Text sampleText;
    static String testField1 = "";
    static String firstField2 = "";
    public static void main(String[] args) {
        display = new Display();
        shell = new Shell(display);
        // Create a new Gridlayout with 2 columns
        // where the 2 column do not have the
        // same size
        GridLayout layout = new GridLayout(2, false);
        // set the layout of the shell
        shell.setLayout(layout);
        // Create a label and a button

        sampleText = new Text(shell, SWT.NONE);
        Label label = new Label(shell, SWT.NONE);
        label.setText("A label");
        Button button = new Button(shell, SWT.PUSH);
        button.setText("Press Me");

        // Create a new label that will spam two columns
        label = new Label(shell, SWT.BORDER);
        label.setText("This is a label");
        // Create new layout data
        GridData data = new GridData(GridData.FILL,
                GridData.BEGINNING, true, false, 2, 1);
        label.setLayoutData(data);

        // Create a new label which is used as a separator
        label = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL);
        // Create new layout data
        data = new GridData(GridData.FILL, GridData.BEGINNING, true,
                false, 2, 1);
        data.horizontalSpan=2;
        label.setLayoutData(data);

        // Create a right aligned button
        Button b = new Button(shell, SWT.PUSH);
        b.setText("New Button");
        b.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent e) {
                new Thread() {
                    public void run() {
                        printInstanceVariables();
                    }
                }.start();
                //showProgressBar() ---> // This is been implemented in another file which will shoe progress bar
            }
        });

        data = new GridData(GridData.END, GridData.BEGINNING, false,
                false, 2, 1);
        b.setLayoutData(data);

        shell.pack();
        shell.open();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch())
                display.sleep();
        }
        display.dispose();
    }

    public static void printInstanceVariables() {
        System.out.println("Text entered is :: " +sampleText.getText());
        System.out.println("test Field 1 is :: " + testField1);
        System.out.println("first Field 2 is :: " + firstField2);
    }

    @Override
    public void createPartControl(Composite arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void setFocus() {
      shell.setFocus();
    }

}

The above code will throw invalid thread acesses ecpection @ printInstanceVariables() first system.out.println()
Answer: Got it.. It is because of accessing the component Text inside the thread in printInstanceVariables(). When i pass this component as paramter, everything works fine. Thanks for all you answers.
Comment: @cmbaxter Why? There is no need. The program looks fine so the problem is in the code that has not been shown yet...
Comment: Is there a stack trace with the error? Please post the entire error message. There isn't anything special that you must do to access instance fields from a thread.
Comment: Try declaring `test` and `first` as `final`
Comment: I tried it as well. Worked for me.
Comment: sorry.. mistakenly typed at end of testmethod.
Comment: @cmbaxter Marking them as `final` will help to make them thread-safe but should not address this issue. There is no reason a thread may not access non-final fields.
Comment: My thought was that you had an anonymous class accessing non final fields.
Comment: @cmbaxter that would only be a problem if the variables were local. With instance variables it is not an issue.
Comment: There is nothing wrong with it. It works. I tried it!
Comment: I am executing this class with SWT view part. the class B in question is the ViewPart class and class A is my view. The class A will be executed when the view is loaded and the new thread inside the class will be executed on click of a button in the view. Since class A is not executed by new Thread, the instance variables are not accessible in new thread??? please let me know on this.
Comment: What methods are declared in B? By the way, use `class` instead of `Class` to compile (typo I suspect).
Comment: You should check this previous post: http://stackoverflow.com/questions/5980316/invalid-thread-access-error-with-java-swt
Comment: @Rock123 To get better, faster help: build a [SSCCE](http://sscce.org): a simple example that reproduces your problem and that we can test.
Answer: This program compiles and executes as expected (it prints a space and a new line). Your problem is somewhere else:
public class Test {

    public static void main(String[] args) throws Exception {
        A a = new A();
        a.testMethod();
    }

    static class A {

        String test = "";
        String first = "";

        public void testMethod() {
            new Thread() {
                public void run() {
                    testThreadMethod();
                }
            }.start();
        }

        public void testThreadMethod() {
            System.out.println(first + " " + test);
        }
    }
}

Comment: Correct. I got the same result.
Answer: I tried your code without extending class B and its working fine. What does your class B contain? Is there really any need to extend class B?
Comment: Good question. @Rock123 - what does B look like?
Comment: I am executing this class with SWT view part. the class B in question is the ViewPart class and class A is my view. The class A will be executed when the view is loaded and the new thread inside the class will be executed on click of a button in the view. Since class A is not executed by new Thread, the instance variables are not accessible in new thread??? please let me know on this.
Comment: @Rock123 The `new Thread` instance is an anonymous instance of `A` and therefore DOES have access to the fields of `A`. We have said this MULTIPLE times. Something ELSE is the issue.
Answer: anonymous inner class is only allowed access FINAL member variable.
this is JVM specification.
i doubt why there is no warning when your code be compiled.

in fact i could get nothing out put when run these code. is there something wrong?

i rewrite the codes, test it and find
it can't access a member variable when the thread in anonymous inner class.
please see the output from eclipse.
Comment: I believe you are thinking of `final` parameters. This is not true of fields.


Fitting child molecule concentration in parent molecule exponential decay

Question: I am new to CrossValidated so hope this question is appropriate... apologies if not.
I am studying the stability of a molecule 'B' and have data on the recorded level at different time points. Molecule B actually increases over time due to the fact that its parent molecule, AB, is decaying releasing it (and A): AB -> A + B
If I were measuring AB I believe it would decay along the following model:
$$
N(t) = N_0 e^{-\lambda t}
$$
Where $N_0$ is the start concentration of AB, $\lambda=\ln(2)/t_{1/2}$ and $t$ is time. For example when $N_0=1000$ and $t_{1/2}=2$ we get as below, which when log transformed these form a nice straight line on which real data can easily be fit, see left hand images in this Google spreadsheet
However, because I am measuring B, and the parent start concentration is unknown (probably much bigger than B), I am getting a graph like (top-right graph in link), which is a mirror of the decay curve of AB, starting at the start concentration of B (known, and in this example 100) and increasing by the decay of AB: ($N_0 - N(t)$) at each $t$.
However, log transforming this does not produce a straight line, because the concentration is not halving or doubling, but increasing by an amount to do with the unknown start concentration of AB, producing the not very useful graph (bottom-right graph in link).
Therefore, I am finding it hard to fit a line to my data. I have tried converting concentration of B into something that looks like concentration of AB which can then be converted easily into a straight line by log transforming, but had no luck as I don't know $N_0$ for AB.
I am hoping I've missed something and there is a nice way transform my data to a straight line, or model it some other way. Any help and ideas would be very much appreciated!
Thanks
Nick
Answer: The problem is that $[B]$ behaves like $N_\infty-N_\infty e^{-\lambda t}$, and the log of this is nothing really interesting. You should subtract this from the asymptotic value to get exponential function again and restore linear look on the log-y plot.
Easy to say, but how to get this $N_\infty$? One way is to wait some time (rule of thumb say $>3/\lambda$, but obviously the more the better) and collect some points then and average them (they will be very close to $N_\infty$).
The better idea is not to plot any lines at all and just use non-linear fitting procedure (such as nls in R) to fit $N_\infty\left(1-e^{-\lambda (t-t_0)}\right)$ to the data and just get all those parameters nicely approximated with CIs.
Comment: With this data I am not able to estimate [B] at t=infinity, as (1) data already collected and (2) the halflives are too long even if redid experiment. I will give nls() in R a go, I was just hoping there was a way to get data as a straight line as it is *just* the mirror of a curve that does transform. Thanks a lot.


Transform pandas dataframe with binary columns to a more compact representation

Question: I have the following pandas dataframe:
import pandas as pd
import numpy as np

np.random.seed(0)
daytime = pd.date_range('2015-02-24', periods=6, freq='d')
df = pd.DataFrame({'DATE': ['2015-02-24', '2015-02-24', '2015-02-25', '2015-02-25', '2015-02-26', '2015-02-26'],
                   'HappyCustomer': ['True', 'False','True', 'False','True', 'False'],
                   'HappyCustomerCount': [2, 4,1, 6, 2, 3] })

df.set_index('DATE', inplace=True)

df.head(6)

    HappyCustomer   HappyCustomerCount
DATE
2015-02-24  True    2
2015-02-24  False   4
2015-02-25  True    1
2015-02-25  False   6
2015-02-26  True    2
2015-02-26  False   3

I think the column HappyCustomer is redundant, since it is always 'True' and 'False'. I would like to transform the column to sth. like this:
Solution:
        HappyCustomerCount_True  HappyCustomerCount_False
DATE
2015-02-24      2                 4
2015-02-25      1                 6
2015-02-26      2                 3

Optional:
In best case scenario I can do this transformation with (SQL related) functions like groupby since I have to do the same job later in SQL database.
How can I do this?
Answer: Use, DataFrame.set_index along with DataFrame.unstack to reshape the dataframe finally use map with join to flatten the MultiIndex columns:
df1 = df.set_index('HappyCustomer', append=True).unstack()
df1.columns = df1.columns.map('_'.join)

Result:
# print(df1)

            HappyCustomerCount_False  HappyCustomerCount_True
DATE
2015-02-24                         4                        2
2015-02-25                         6                        1
2015-02-26                         3                        2


Trocando de mysql para mysqli

Question: Fala pessoa beleza?
Então eu estou a mais ou menos 3 dias fuçando e mexendo neste código.
Todos os erros de obsolencia do mysql somem, e eu consigo navegar normalmente pela área de administrador.
Porém, ao sair da área e tentar entra novamente, ele me alerta com 'Acesso Negado'
Ou seja, nessa brincadeira de alterar bugou alguma coisa que fez com que o sistema não aceitasse meu login...
Estou a horas tentando arrumar e nada, alguém pode dar uma lida nos arquivos e ver se acha algo?
Abraços.
Principal.php:

$usuario_id   = $_SESSION['usuario_id'];
$usuario_nome = $_SESSION['usuario_nome'];
}
?>
<?php
// PEGA OS DADOS DO USUÁRIO

$query = "SELECT * FROM tbl_usuarios where id = '$usuario_id'";
    $resultado = mysqli_query ($conexao, $query);
$campo = mysqli_fetch_array ($resultado);
$usuario_nome = $campo ['nome'];

$sign = "ike3da";
?>

<META http-equiv=Content-Type content="text/html; charset=iso-8859-1">
<title>Área Administrativa</title>

Seja bem-vindo, <?php echo "$usuario_nome"; ?>.

Cadastrar Notícia

Listar Notícias

Sair

<?php include "pages.php"; ?>

conexao.php:
    <?php
$conexao = mysqli_connect('localhost', 'root', 'wamp', 'noticias');
if($conexao){
      if (mysqli_select_db($conexao, 'noticias')){ print "";
      }else{ print "Não foi possível selecionar o Banco de Dados"; }
}else{ print "Erro ao conectar o MySQL"; }
?>

autenticacao.rotinas.php:
<?php
session_start();
include ("../config/conexao.php");

$cliente_username = $_POST["usuario"];
$cliente_password = $_POST["senha"];
$enviado          = $_POST["enviado"];

if ($enviado == "posted"){

if (!isset($cliente_username) or !isset($cliente_password)) { echo "Erro!"; exit; }
if (empty($cliente_username) or empty($cliente_password)) { echo "Dados inválidos!"; exit; }

$query = "select * from tbl_usuarios where login = '$cliente_username' and senha = '$cliente_password'";
$result = mysqli_query($conexao, $query);
$number = mysqli_num_rows($result);

if ($number==0) { ?>
<?php
exit;
} else {
$_SESSION['usuario_id'] = mysql_result($result,0,'id');
$_SESSION['usuario_nome'] = mysql_result($result,0,'nome');
?><?php
}
mysqli_close($conexao);

}
?>

Answer: O problema deve estar na criação das sessions, que ainda está usando mysql_result:
$_SESSION['usuario_id'] = mysql_result($result,0,'id');
$_SESSION['usuario_nome'] = mysql_result($result,0,'nome');

Mas não existe uma função mysql_result equivalente em mysqli, tem que usar as funções mysqli_fetch_* da classe mysqli_result.
A função mysqli_fetch_assoc retorna uma linha como um array associativo. Portanto, podes fazer assim:
$row = mysqli_fetch_assoc($result);
$_SESSION['usuario_id'] = $row['id'];
$_SESSION['usuario_nome'] = $row['nome'];

Comment: Simplesmente perfeito! Quebrou um galho irmão! Você é demais!!
Comment: Você pode aceitar esta resposta. [Como e por que aceitar uma resposta?](http://meta.pt.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta)

Trocando de mysql para mysqli


Random Bug in Unity2D

Question: I've been working on a project for the GMTK 2022 Game Jam recently, and I ran into a very strange problem. I have a dash that starts when you are moving and press space. It moves you in the direction of your velocity, then for a short time lets you move very quickly. It works perfectly fine in all cases, unless the direction you are moving is up and to the left, in which case, the if statement strangely won't trigger. I'm sure this is something idiotic, but I've been troubleshooting it for the last hour and it's been driving me insane.
<code>// Update is called once per frame
void Update()
{
    playerInputh = 0;
    playerInputv = 0;
    if (Input.GetKey("right"))
    {
        playerInputh = 1;
    }
    if (Input.GetKey("left"))
    {
        playerInputh = -1;
    }
    if (Input.GetKey("right") && Input.GetKey("left"))
    {
        playerInputh = 0;
    }
    if (Input.GetKey("up"))
    {
        playerInputv = 1;
    }
    if (Input.GetKey("down"))
    {
        playerInputv = -1;
    }
    if (Input.GetKey("up") && Input.GetKey("down"))
    {
        playerInputv = 0;
    }

    Vector2 screenPosition = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
    Vector2 mouseWorldPosition = Camera.main.ScreenToWorldPoint(screenPosition);

    //This is the dash that isn't working:
    if ((Input.GetKeyDown(/*"right shift"*/"space")) && (playerInputh != 0 || playerInputv != 0))
    {
        Debug.Log("Dash");
        //Vector2 transform2dposition = new Vector2(transform.position.x, transform.position.y);
        m_Rigidbody.AddForce((m_Rigidbody.velocity) * 500f);
        wJumpTimer = airControlAfterJump;
        speed = maxSpeed*3.5f;
        StartCoroutine(Roll());
    }

}

void FixedUpdate()
{
    //no moving while jumping!!!
    if (wJumpTimer > 0)
    {
        wJumpTimer -= 1;
    }
    else
    {
        wJumpTimer = 0;
    }

    //move
    if (playerInputh != 0 && playerInputv != 0) //make diagonals no super sayan
    {
        playerInputh *= moveLimiter;
        playerInputv *= moveLimiter;

        one_h = playerInputh;//futureproof
        one_v = playerInputv;
    }
    if ((playerInputh != 0 || playerInputv != 0) && speed < maxSpeed) //are we hitting the move buttons??
    {
        speed += acceleration;//accelerate
        one_h = playerInputh;//futureproof
        one_v = playerInputv;

    }
    else
    {
        if (speed > 0f) //are we getting off the ride
        {
            speed -= deceleration; //decelerate
        }
        else
        {
            speed = 0f; //no funny buisness
        }
    }

    m_Rigidbody.velocity = new Vector2(one_h * speed, one_v * speed); //actually move

}

void SetFace(int diceNumb)
{
    rndr.sprite = sprites[diceNumb];
}
IEnumerator Roll()
{
    Random diceNumb = new Random();
    rndr.sprite = sprites[diceNumb.Next(0,5)];
    yield return new WaitForSeconds(0.125f);
    rndr.sprite = sprites[diceNumb.Next(0, 5)];
    yield return new WaitForSeconds(0.125f);
    rndr.sprite = sprites[diceNumb.Next(0, 5)];
    yield return new WaitForSeconds(0.125f);
    rndr.sprite = sprites[diceNumb.Next(0, 5)];
    yield return new WaitForSeconds(0.125f);
    var newValue = diceNumb.Next(0, 5);
    FaceValue = newValue + 1;
    rndr.sprite = sprites[newValue];

}
</code>
Answer: How are your inputs setup? I am suspecting you have one key bound to multiple actions, like one key is set up as primary for an action and alternate for another action.
Personally I'd also stop using the assignment operators and increment instead. Instead of
<code>    playerInputh = 0;
    if (Input.GetKey("right"))
    {
        playerInputh = 1;
    }
    if (Input.GetKey("left"))
    {
        playerInputh = -1;
    }
    if (Input.GetKey("right") && Input.GetKey("left"))
    {
        playerInputh = 0;
    }
</code>
you can do
<code>    playerInputv = 0;
    if (Input.GetKey("right"))
    {
        playerInputh += 1;
    }
    if (Input.GetKey("left"))
    {
        playerInputh += -1;
    }
</code>
Net result is the same here - if you push both keys the result sums to zero, but the code is easier to read (IMO).
When you check things for key bindings also check alternates for space, because that's another one of the triggers you need to dash.
Comment: Thanks for the suggestions! If you want it, here's the code for the movement, I will warn you it's a bit scuffed.
Comment: Unfortunately, the code still isn't working, and for whatever reason whilst moving up and right you can't dash

Random Bug in Unity2D


DNS not resolving on Virtualmin

Question: I am having problems reaching my site hosted on a virtualmin virtual server. It is the only site I have hosted on the server right now (I am just learning my way around virtualmin and VPSs in general) and I can access it via IP address but not via the domain name.
Running whois returned the correct nameservers so I then ran:
host mysite.com ns1.mynameserver.com

and received "connection timed out; no servers could be reached."
I then added my ip address manually to named.conf and ran:
host mysite.com ns1.mynameserver.com

again, which now yields the correct IP.
The only problem is my site is still unreachable via the domain name (I get "server not found"). I setup all the DNS stuff more than 24hrs ago with the exception of adding my IP to the named.conf file.
My question is, shouldn't my domain name resolve to the site now that host mysite.com ns1.mynameserver.com returns the correct IP?
Any idea as to what I should do next?
Also, why did I have to add my IP manually to named.conf? Did I miss something in the virtualmin setup or (more likely) screw up some setting that I am not aware of?
I did set virtualmin to listen locally only so as to access it via an ssh tunnel, could this have lead to an alteration of the named.conf file?
I appreciate any assistance and beg your indulgence of a rank amateur. I am sure this is just the first of many stupid questions.
Comment: Thanks for the edit Mathias, you made the question much more readable. I should have formatted the question a bit differently when I wrote it, suppose I was just in a hurry due to being frustrated and over-caffeinated.
Answer: So after taking a break and coming back to the problem and a little help from the virtualmin forums this is why the nameservers were not responding:
The name.conf file was completely set up for local use only. I was under the impression that virtualmin was supposed to take care of this but as I said before I am very new at this. When I added the IP manually to named.conf I should have also changed:
allow-query { localhost; };

to
allow-query { any; };

Hopefully this will be of some use to those who encounter a similar situation.

DNS not resolving on Virtualmin


Problem in understanding the proof of boundedness of a convergent sequence.

Question: I was seeing Prove: Convergent sequences are bounded. The proof is as follows:

Let $s_n$ be a convergent sequence, and let $\lim s_n = s$. Then taking $\epsilon = 1$ we have:
$n > N \implies |s_n - s| < 1$
From the triangle inequality we see that: $ n > N \implies|s_n| - |s| < 1 \iff |s_n| < |s| + 1$.
Define $M= \max\{|s|+1, |s_1|, |s_2|, ..., |s_N|\}$. Then we have $|s_n| \leq M$ for all $n \in N$.

I've some problem in understanding the approach of this deduction.
We need to show that the sequence is bounded which means $|s_n| \le M$ . Now, this must be for every $n$. What I am not understanding is whether the first step to show that for $n \gt N$, $|s_n| \lt |s| +1$ was necessary. After all, a number $M$ greater than all the sequence-elements were taken next; so why not, take this step firstly?
I only want to know how the first step for showing that for $n \gt N$, $|s_n| \lt |s| +1$ is essential for the proof. Also, it deduced that $|s_n| \color{red}{\lt} |s| +1$; so how did, finally, at the last step of proof $\color{\red}\le$ come in place of $\color{red}{\lt}$? Thanks in advance.
Answer: $M$ was not chosen to be greater than all terms of the sequence: it was chosen to be at least as large as $|s|+1$ and the first $N$ terms of the sequence.
The first step takes care of all but the first $N$ terms: there is some integer $N$ such that $|s_n|<|s|+1$ whenever $n>N$. Thus, $|s|+1$ is almost an upper bound for the sequence: it's bigger than the absolute value of every term except possibly one or more of the terms $s_1,s_2,\ldots,s_N$, However, there are only finitely many of those terms, so we can pick the one with largest absolute value; say that it's $s_m$. Now we know that $|s_k|\le |s_m|$ if $1\le k\le N$, and $|s_k|<|s|+1$ if $k>N$. If we now let $M=\max\{|s|+1,|s_m|\}$, we know that
$$|s_k|\le|s_M|\le M$$
if $1\le k\le N$, and
$$|s_k|<|s|+1\le M$$
if $k>N$, so $|s_k|\le M$ for all $k$. Thus, the sequence lies entirely in the interval $[-M,M]$ and is therefore bounded.
As for your last question, if $a<b$, then it's certainly also true that $a\le b$: if you know the former inequality, you can certainly claim the latter.
The basic idea of the proof is that since the sequence is convergent, it must eventually get and stay close to its limit $s$. In this specific argument we choose $N$ so that $|s_n-s|<1$ whenever $n>N$, so that the sequence stays within one unit of $s$. The first $N$ terms could be anywhere, but there are only finitely many of them, so there is a largest (in absolute value). Thus, we have the bound $|s|+1$ that is known to work for all but the first $N$ terms, and we can get a bound on that finite set of terms. We then take the larger of these bounds and can be confident that it bounds every term.
Comment: Sir, thanks for the answer. Shouldn't in $s_k\le|s_M|\le M$ & $s_k<|s|+1\le M$, there would be $|\;\;|$ in $s_k$; in the above lines you've written them correctly including $|\;\;|$ sign: "Now we know that $|s_k|≤|s_m|$ if $1≤k≤N$, and $|s_k|<|s|+1$ if $k \gt N$"; but later, you didn't mention them. So, I think this is a typo:|
Comment: Also, I want to know how you inferred $|s_k|\le M$ from $|s_k|<|s|+1\le M$;  Yes it is accurate to write that $|s_k| \lt M$ but why the equality? $|s|+1$ can be equal to $M$ but not $|s_k|$ since it is less than $|s|+1$. So, can you help me shun this confusion?
Comment: @user36790: Yes, I inadvertently omitted the absolute value signs around $s_k$ in the displayed formulas; they're fixed now. Thanks for noticing. \\ From $|s_k|<|s|+1\le M$ we can, as you say, actually infer that $|s_k|<M$, but of course if this is true, then it's certainly also true that $|s_k|\le M$. For $1\le k\le N$, however, we can infer only that $|s_k|\le M$. Thus, the best that we can claim for *all* $k\in\Bbb Z^+$ is that $|s_k|\le M$. If we defined $$M=\max\{|s|+1,|s_1|+1,\ldots,|s_N|+1\}\;,$$ then we could infer that $|s_k|<M$ for all $k$, since for $1\le k\le N$ we would have ...
Comment: ... $|s_k|<|s_k|+1\le M$. But we don't need this: in order to show that that sequence is bounded, we need only show that there is an $M$ such that $|s_k|\le M$ for all $k$, and we've done that. (It may help to point out that it's perfectly correct to write, for instance, $2\le 3$, even though we know that in fact the stronger statement $2<3$ is true.)
Answer: The point is that the definition of convergence only says that given any positive error margin eventually the elements in the sequence will be within that error margin around the limit. We do not know when that eventual situation would be, so we have no choice but to separately bound the initial part of the sequence before that point. Thankfully that initial part has finitely many numbers and hence is bounded, so since the latter part is also bounded, the whole thing is bounded.
Also, if $a < b$ then $a \le b$ so there is nothing wrong with doing that last step.
Answer: According to definition of convergent sequence after certain stage all terms of sequence lies in a band. I.e $L-\epsilon<a_n<L +\epsilon$ after n greater than equal to m say. This means after m, the sequence is bounded above by $L+\epsilon$. So we need to worry about terms from $n=1$ to $n=m-1$. Let we have P be the maximum value of these terms and let us take $M=\max\{P,L+\epsilon\}$. So sequence is bounded above by $M$.
Comment: This is a very common proof technique.


Connecting to SQL Server 2005 database in SQL Server Management Studio Express

Question: I have installed Microsoft SQL Server 2005.
When I go to: Start --> All Programs --> SQL Server Management Studio Express
I don't get the Connect button highlighted and the Server name text box is empty.
How do I connect to the database with SQL Server Management Studio Express?
Answer: Assuming you are using Sql server express:
First make sure that sql server service is actually running.
Try the following names for servername:
.
.\sqlexpress

localhost
localhost\sqlexpress

or: try to open the dropdownlist in servername and use '<browse>'
ps: the . is really a dot only
Comment: @Pleun. Thanks for your reply. Maybe the issue is in making sure that the sql server service is running. How can I make sure of that?
Comment: Start the sql server configuration manager (available from the start menu) and click on the services node
Comment: @Pleun. I just have `SQL Server Management Studio Express`. And, the folder that comes under `Microsoft SQL Server 2005` is `Configuration Tools` which contains `SQL Server Error and Usage Reporting`. I couldn't find what you mentioned, and don't know why I'm not getting what you told me to do. Thanks
Comment: You can also see the services in the general windows services configuration. (%SystemRoot%\system32\services.msc)
Comment: @Pleun. I saw the services, but `Microsoft SQL Server 2005` is not there!
Comment: Are you sure you installed the complete sql server and not only the management studio... There's no MSSQLSERVER service? What OS are you running?


How do I find the "max" string in Javascript?

Question: Similar to How to sort strings in JavaScript but I want to avoid sorting first, I just want the "largest" value of a string.  For example
f(['Aa', 'B', 'C', 'Acd', 'Ace']) == 'C'

I am thinking it's something with .reduce like
const f = (a) => a.reduce(someFunctionGoesHere)

Where some function has an undefined check
UPDATE: Got it working but looks fugly.  I wonder if I can reduce that function
const someFunctionGoesHere = (prev, current) => {
  if (!prev) {
    return current;
  }
  else if (prev.localeCompare(current) < 0) {
    return current;
  } else {
    return prev;
  }
};
const f = (a) => a.reduce(someFunctionGoesHere)

console.log(f(['Aa', 'B', 'C', 'Acd', 'Ace','CC']));

UPDATE: this works, one line, but looks quite ugly.  I guess this is the best that can be done with Javascript itself.
const maxString = (a) => a.reduce((prev, current) => (!prev || prev.localeCompare(current) < 0) ? current : prev)

console.log(maxString(['Aa', 'B', 'C', 'Acd', 'Ace','CC']));

Comment: You can give a default value in `array#reduce`.
Comment: You already have reduce function. What do you want to achieve?
Answer: Indeed, reduce() will get you there:

const f = (array) => array.reduce((a, v) => v.localeCompare(a) > 0 ? v : a, '');

console.log(f(['Aa', 'B', 'C', 'Acd', 'Ace','CC']));
Comment: @RickyMo Thanks, updated. Looks like I need more coffee :)
Comment: `localeCompare` returns a number. Your condition only false when `v` and `a` are equal.
Comment: @RobbyCornelissen same here.  I thought and proven again that sometimes articulating what you want makes the answer come out more naturally.


print description and field value directly in taxonomy-term--drzava.html.twig

Question: First I disable view for taxonomy-term, so I can use taxonomy-term--drzava.html.twig, where drzava is name of vocabulary.
How to print description and filed value for taxonomy-term directly, without using
field--taxonomy-term--description--drzava.html.twig

{{ content.description }} or {{ content.field_flag_code}}
I have problem to analyze devel output. I try {{ content.description.value }} but its do not work.
and for field, I try something like this but its do not work. {{ content.field_flag_code.0.value }}
In Devel there is Definition, Render and Load, what from this tri tabs I need to look for twig?
Thanks for the help in advance.
Answer: I remembered. I hadn't used drupal for a while, so I forgot.
I use Devel:
{{ kint(content.description['#items'].getValue()|first.value) }}

and in taxonomy-term--drzava.html.twig, I Use
{{ content.description['#items'].value }}

This is my output. But I don't understand why its display

Comment: `` tags are probably being added because the description is passed through an input filter, which adds the tags automatically.  If you want to get rid of them, use `striptags`: https://twig.symfony.com/doc/2.x/filters/striptags.html
Comment: Yes, this is clear in the debug output because the field has a property `format`. The correct way is then to output it as processed_text to apply the output filters of the text format, too. See https://drupal.stackexchange.com/questions/238762/how-to-safely-render-node-body-on-a-custom-variable. This link is for a node, in a taxonomy term template use `term`.
Comment: You don't need a preprocess hook because the variable `term` is already available, see the documentation at the top of template. I post a code example as answer.
Comment: @4k4 This is very nice solution. Where to put '#test' => $term in some preprocess functions or..? I always afraid to write preprocess functions.
Answer: The description field is a formatted text field which should be printed as processed text render element:
taxonomy-term.html.twig:
{{ {
  '#type': 'processed_text',
  '#text': term.description.value,
  '#format': term.description.format,
} }}

If you want to get rid of the
 tag you have to configure the field with a a different text format or use |render|striptags on a variable stored like in the linked topic.
The other field value:
{{ term.field_flag_code.0.value }}

Comment: Thank you a lot. I learn one very nice staf. https://prnt.sc/26ja49b I edit a litle your answer
Comment: About your edit, the other field doesn't seem to be a formatted text field.
Comment: I was plane to use field_flag_code field as css marker.  like flag-icon-{{ term.field_flag_code.0.value }} . I was use the some method and its work. :)


Which pieces did Mozart write originally for SATB choir a cappella?

Question: Specifically:

it has to be written for a cappella performance by a mixed soprano-alto-tenor-bass choir. It can't have a mandatory instrumental part (e.g. piano, organ, string quarter, etc.), but may have an optional instrumental part, e.g. it could be a Choir + Organ piece where the composer has explicitly stated (e.g. in the sheet) that the instrumental may be dropped for some reason (e.g. if the choir is large enough) - these are acceptable.
it has to be an original Mozart work - KV catalogue index and all. Arrangements of Mozart works by other composers (e.g. a cappella arrangements of Requiem) don't count.
it may require a solo performer.

Basically, imagine Mozart hearing Viadana's Exultate Justi, saying to himself: "I can do better than that!" and getting straight to work. I'm searching for the result of that!
Comment: Yes, I have googled and googled. As @RolandBouman guessed correctly, I found mostly arrangements or non a cappella works. I asked on this site _specifically_ because I though that the question fits snugly with the Q&A format. Guys, Stack Exchange is a Micro FAQ suite of sites, where no well-asked question is undeserving. If your idea of an answer in a FAQ site is "Here's the complete repertoire of Mozart's work, do your research! Alone!", then the music stack exchange might well not make it out of Beta.
Comment: In my experience, the topic of finding a Mozart piece suitable for choir performance crops up surprisingly often. I asked the question here _specifically_ because I think that the question will indeed prove useful to future readers (was it bad judgment?). I did my best to word my question in a search-friendly way. Finally, I got both an excellent answer and an excellent answer-finding technique.
Comment: Have you googled "mozart choral satb a capella" yet?  If you haven't, perhaps it would be best to start there.  I did so and find several arrangements available that appear to meet your needs.
Comment: I will take consolation in knowing that novice choir geeks like me will stumble upon imslp's `List_of_works_by_xxx` tables thanks to this question's answer, making this whole diatribe worth enduring. @RolandBouman +1
Comment: Yeah I agree with Stefan. It's not the first time either I've seen good, sensible questions being held off as off-topic here, see for example http://music.stackexchange.com/questions/15586/retrograde-and-inverted-songs/15600. Personally I think the policy applied in both cases is overly broad. This is not about identifying "a particular song", it is about a well-defined class of compositions. Questions like "how do I learn to play using X technique on instrument Y" invariably have the same, predictable useless answers ("practice, a lot") and are never held off.
Comment: @BobRodes the requirement was: written by Mozart / not an arrangement by another composer. Your google suggestion leads to pages and pages of cold leads. Many results come without provenance so you'd have to still track down to see if it is an original composition or an arrangement by another composer. It might've worked if Mozart had in fact, written tons and tons of a cappella works, and no other composers decided to make a-capella arrangements of his accompanied works. In which case I don't think Stefan would've asked in the first place.
Comment: You can find an extremely comprehensive list of Mozart choral pieces in sheet music at http://www1.cpdl.org/wiki/index.php/Wolfgang_Amadeus_Mozart. Whether he wrote some with instrumental accompaniment or not, you will have to research.
Comment: @Roland: you're right, I missed that in your requirements. (Sorry if my post sounded like you hadn't spent enogh time looking for an answer; looking at it again I can see that it might look that way and it wasn't intentional.) I wasn't able to find anything either. Interesting.
Comment: @BobRodes it's ok - no offence taken :) In retrospect, I thought that maybe it is possible to find exactly the desired result with just Google, and my google-foo might just not be good enough. Regardless I still think this "put on hold" policy is way too stringent, or maybe it is used too lightly.
Comment: I added this to the meta: http://meta.music.stackexchange.com/questions/731/please-relax-the-policy-on-questions-that-ask-for-examples-of-a-particular-class
Comment: @StefanDragnev, I think it would be helpful if you could go to http://meta.music.stackexchange.com/questions/731/please-relax-the-policy-on-questions-that-ask-for-examples-of-a-particular-class and explain how you thought of your question, and what your expectations were w/re to the answers. Would be great if you could give your feedback. Thanks in advance!
Answer: Using this list:
http://imslp.org/wiki/List_of_works_by_Wolfgang_Amadeus_Mozart
I found 2 for mixed chorus. Click the links to download the score.

God is Our Refuge, K.20 (Youtube video, with score)
Quaerite primum regnum Dei, K.86/73v (Youtube video)

Both pieces are quite short, just over a minute.
I added a musescore transcription for God is our Refuge. You can download this score as musescore file, pdf file, musicXML file, midi, or mp3. I also made a matching videoscore.
Update
Here's another list of Mozart pieces scored for choir (with sheet music provided for each one) at the Choral Public Domain Library. However these might not be originally written for only choir.
http://www1.cpdl.org/wiki/index.php/Wolfgang_Amadeus_Mozart


Dúvida sobre como chamar a função com cada botão de mouse

Question: Pessoal tenho esse código mas não consigo fazer com que cada botão do mouse chame uma função diferente:
var tela = document.getElementById("tela");
var c = tela.getContext("2d");

c.strokeStyle = "black";
c.strokeRect(0, 0, 600, 400);

var atira = function(evento) {
    var x = evento.pageX - tela.offsetLeft;
    var y = evento.pageY - tela.offsetTop;

    c.fillStyle = "blue";
    c.beginPath();
    c.arc(x, y, 10, 0, 2 * Math.PI);
    c.fill();
};

var atira2 = function(evento) {
    var x = evento.pageX - tela.offsetLeft;
    var y = evento.pageY - tela.offsetTop;

    c.fillStyle = "red";
    c.beginPath();
    c.arc(x, y, 10, 0, 2 * Math.PI);
    c.fill();
};

tela.onclick = function(evento) {
    switch(evento.which) {
        case 1 :
            console.log("botao esquerdo");
            tela.onclick = atira;
            break;
        case 2 :
            console.log("botao do meio");
            tela.onclick = atira2;
            break;
        case 3 :
            console.log("botao direito");
        default:
            console.log("mouse estranho");
    }
};

Comment: Pode por também seu html? pode ser só a parte relevante.
Answer: Para ouvir os seus botões, utilize mousedown.
Veja:
document.getElementById('workspace').addEventListener('mousedown', function (event) {
  event.preventDefault();

  if(3 === event.which) alert('right click!');
  else alert('left click!');
}, false);

Para ressaltar, workspace é o id do elemento onde o usuário vai clicar e que você deseja ouvir o pressionamento do botão.
Um exemplo completo, veja aqui, no jsFiddle.

No seu caso em específico, você não precisa do tela.onclick para engatilhar as suas funções. Veja um exemplo que criei (você precisa remover os comentários em questão para funcionar) baseado no seu cenário:
var tela = document.getElementById("tela");

/*
 * var c = tela.getContext("2d");
 * c.strokeStyle = "black";
 * c.strokeRect(0, 0, 600, 400);
 */

var atira = function(evento) {
  var x = evento.pageX - tela.offsetLeft;
  var y = evento.pageY - tela.offsetTop;

  c.fillStyle = "blue";
  c.beginPath();
  c.arc(x, y, 10, 0, 2 * Math.PI);
  c.fill();
};

var atira2 = function(evento) {
  var x = evento.pageX - tela.offsetLeft;
  var y = evento.pageY - tela.offsetTop;

  c.fillStyle = "red";
  c.beginPath();
  c.arc(x, y, 10, 0, 2 * Math.PI);
  c.fill();
};

tela.addEventListener('mousedown', function(evento) {
  if(1 === evento.which) {
      console.log('botão esquerdo');
      atira();
  } else if(3 === evento.which) {
      console.log('botão direito');
      atira2();
  }
}, false);

tela.addEventListener('contextmenu', function(event) {
  event.preventDefault();
}, false);

O exemplo completo está aqui, no jsFiddle.

Se nenhum dos exemplos funcionar para você, o problema pode estar no seu DOM. Por favor, poste o seu HTML.
Se você não entendeu o porquê d'eu estar utilizando .addEventListener, veja a documentação aqui.
Comment: *Yoda conditions*!
Comment: Oi @bfavaretto. Então, ele deu CTRL+C / CTRL+V no meu código e essa reação é mais do que normal – é esperada. Como pode ver no código e inclusive na advertência da minha postagem, existem três linhas que eu comentei no código dele para que eu pudesse exemplificar melhor – linhas essas que caso ausentes resultam no tal erro pelo usuário apresentado. Portanto, cabe a ele descomentar as linhas e fazer as alterações que propus no(s) meu(s) exemplo(s).
Comment: Não consigo não usar, @Beterraba. UAhuahua
Comment: O autor da pergunta relatou ter tentado isso e obtido o seguinte erro: *Uncaught TypeError: Cannot read property 'pageX' of undefined*. (Excluí a postagem dele pois foi postada como resposta).
Answer: O seu tela.onclick está simplesmente redefinido a si mesmo durante o primeiro clique, de modo que todo clique subsequente executará a mesma função toda vez. Exemplo:
// O mouse foi clicado com o botão esquerdo
tela.onclick = function(evento) {
    switch(evento.which) {
        case 1 :                           // Entrou aqui...
            console.log("botao esquerdo");
            tela.onclick = atira;          // Aqui você redefiniu tela.onclick...
            break;                         // Saiu..
    }
    // ...e não fez mais nada! o primeiro clique não disparou nenhuma função (pun intended).
};
// O mouse foi clicado de novo com o botão esquerdo
tela.onclick = atira; // Ele vai executar o código de atira. Parece que funcionou, não? Só que...
// O mouse foi clicado de novo, agora com o botão direito
tela.onclick = atira; // Ele vai executar o código de atira, não de atira3...

Em vez de redefinir o tela.onclick, simplesmente chame a função relevante:
tela.onclick = function(evento) {
    switch(evento.which) {
        case 1 :
            console.log("botao esquerdo");
            atira();
            break;
        case 2 :
            console.log("botao do meio");
            atira2();
            break;
        case 3 :
            console.log("botao direito");
            ...
        default:
            console.log("mouse estranho");
    }
};

Isso deve resolver seu problema imediato (de todos os cliques estarem indo pra mesma função). Para uma solução mais completa, ver a resposta do Guilherme Oderdenge.
Answer: Também estava tentando resolver este mesmo exercício, e consegui da seguinte forma:
tela.addEventListener('mousedown', function(evento){

switch(evento.which){

    case 1:
        console.log("botão esquerdo");
        tela.onclick = atira;
        break;

    case 3:
        console.log("botão direito");
        tela.oncontextmenu = atira2;
        break;

    default:
        console.log("mouse estranho");

  }
}, false);

as respostas postadas aqui me ajudaram em alguns pontos, mas o que me permitiu "matar a charada" foi o entendimento de que o evento CLICK está vinculado ao botão esquerdo do mouse e o evento CONTEXTMENU é que está vinculado ao botão direito do mouse.
Segue material que me ajudou: eventos em Javascript
Answer: Olha, uma maneira simples de executar funções para cada click do mouse, esquerdo e direito, é desabilitar a função responsável pelo menu do click direito e substituir por outra, veja se entende:
<canvas id = "tela" width = "800" height = "800"> </canvas>

Answer: Os navegadores entendem que o onclick é apenas para cliques do botão esquerdo! Note que, quando você clica com o botão direito, uma janelinha com o menu de ações é aberto. A função que cuida disso é a do oncontextmenu e, para impedir o navegador de abrir a janelinha de menu, você ainda pode adicionar a chamada a evento.preventDefault():

<canvas id="tela" width="600" height="400"></canvas>


Como criar um Cascading DropDown?

Question: Gostaria de criar um DropDown dependente de outro DropDown em C#, ASP.net - MVC 5, no caso seria um dropDown com os nomes de todos os cliente e em seguida outro DropDown com os telefones do Cliente selecionado no primeiro DropDown. Como fazer?
Classe : Pedido
 public class Pedido
{
    public Pedido()
    {
        this.Produtos = new List<Produto>();
    }

    [Key]
    public int PedidoID { get; set; }

    public Cliente Cliente { get; set; }

    [Display(Name = "Nome do Cliente")]
    public int ClienteID { get; set; }

    [Display(Name = "Telefone")]
    public string ClienteFone { get; set; }

    [Display(Name = "Cidade")]
    public string   ClienteCidade { get; set; }

    [Display(Name = "Estado")]
    public string ClienteEstado { get; set; }

    [Display(Name = "Endereço")]
    public string ClienteEndereço { get; set; }

    public ICollection<Produto> Produtos { get; set; }

    [Display(Name = "Status to pedido")]
    public Estatus Estatus { get; set; }

    public int EstatusID { get; set; }

    [Display (Name="Data do pedido")]
    public DateTime DataPedido { get; set; }

}

Create.cshtml
 @Html.ValidationSummary(true)

        @Html.LabelFor(model => model.ClienteID, "ClienteID", htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.DropDownList("ClienteID", String.Empty)
            @Html.ValidationMessageFor(model => model.ClienteID)

        @Html.LabelFor(model => model.ClienteFone, "ClienteFone", htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.DropDownList("ClienteFone", String.Empty)
           @* @Html.EditorFor(model => model.ClienteFone)*@
            @Html.ValidationMessageFor(model => model.ClienteFone)

Answer: Faça da seguinte forma, abaixo é um exemplo com uma tabela com a seguinte estrutura
clientes(ClienteID, Nome, Telefone)

Controller
var clientes = (select u in model.clientes ......).ToList();

ViewBag.Clientes = new SelectList(clientes, "ClienteID", "Nome");
ViewBag.Telefones = new SelectList(clientes, "telefone", "telefone");

View
@Html.DropDownListFor(model => model.ClienteID, (SelectList)ViewBag.Clientes) /* Gera um select com nomes e value o ClienteID */

@Html.DropDownListFor(model => model.ClienteFone, (SelectList)ViewBag.Telefones) /* Gera um select com telefones e value o telefone */

Espero que tenha entendido o uso, a validação continua a mesma coisa, os campos e a lista no controller você altera para a lista de clientes do seu sistema.
Agora para popular o segundo DropDownList selecionando com base no primeiro, será necessário o uso de javascript
View
@Html.DropDownListFor(model => model.ClienteID, (SelectList)ViewBag.Clientes, new {id="clienteID"}) /* Gera um select com nomes e value o ClienteID */

@Html.DropDownListFor(model => model.ClienteFone, String.Empty, new {id="clienteFone"})

Controller
public JsonResult ListaTelefones(int clienteID) {
   var telefones = (from u in model.telefones where u.ClienteID select u.telefone).toList(); //Nesse caso estou usando uma tabela ficticia com os telefones do cliente cadastrado

   return Json(telefones, JsonRequestBehavior.AllowGet);
}

Jquery
$('#clienteID').change(function() {
   var clienteID = $(this).val();

   $.get('/MeuController/ListaTelefones', {clienteID : clienteID}).done(function(data){
      var drop = $('#clienteFones');
      drop.html("");
      $.each(data, function(i, item) {
         drop.append('<option val="'+item+'">'+item+'</option>');
      });
   });
});

Comment: estou tendo problemas ao colocar os id's nos dropDowns, é dessa forma mesmo?
Comment: Que tipo de problema?
Comment: não estou recebendo o valor da segunda dropdown para cadastrar no banco, quando seleciono o cliente visualizo os telefones mas não esta sendo executado pelo metodo Create na minha controller
Comment: Isso ocorre por causa do "bind" que o MVC faz com os dados, esqueça a criação com razor e faça `` Provavelmente agora deve passar.

Como criar um Cascading DropDown?


Who should nominate him self as a candidate in elections?

Question: I just saw that there is an election on our community & as we can see that many peoples are nominating their self as an aspirants in the election for the post of moderator.
I also filled the nomination but then withdrew my name from the nominators list just because I felt that I still need to know much more about magento before standing as an aspirant in the election for the magento community.
My question is that who should stand as an aspirant for the post of moderator & On what basis we should judge them that whether he is really a good candidate or not for the post of magento moderator?
Comment: This is a really good question. I hope all the candidates see it.
Comment: I'm thinking, I'm thinking. But I guess there is no perfect answer on this. All I can do is give you my opinion. I will try to write something today.
Comment: Thank you @Marius ! I would be great full to have your answer on this
Answer: Since (almost) everyone can sign up for the election and my vote counts just as much as the next person's, what follows is just my opinion and should not be taken as fact in any way. It does not mean I'm right, it does not mean I'm wrong either.
You should nominate yourself if:

you have proven yourself as an active member in the past. A good indicator of this may be the number of "Moderation Badges" you have (https://magento.meta.stackexchange.com/help/badges). Another indicator may be the number of days you visited the website that you can find in your profile page. Or the number of posts you had on meta.
You think something is wrong with the website and you have a plan to fix it. (you should do this anyway even if you don't want to be a moderator).
You value education instead of destruction for new comers.

You should not nominate yourself if:

You just want to brag to your friends that you have a diamond next to your name in a stackexchange website.
You did not really participate in this website much, but being a moderator will motivate you to do so. The motivation to participate should not be influenced by being a moderator or not.
you have close to none reviews in the review queue in all the categories.
You have no idea what the meta website is.
A significant part of your posts (questions and answers, but mostly questions) have low score and a lot of comments that require improvement.
You ask questions like this: Regrading 2018 Community Moderator Election for which you could have found the answer easily.

When should you withdraw from the election:

When you see that your candidate score in the election has 1 digit followed by /40.
Comment: I totally agree with your opinions & the last-one is really **mark-able** I hope those who are standing as an aspirants with 1/40 or below 10/40 should have a look into this.
Answer: This question is interesting, but difficult to give a full qualifying answer. Any way I will put my two cents here.
You can be a candidate if:

You are around here at least for one year and during that period you were constantly put effort to improve this community. Why one year? Each community works different. It will take some time to understand the community, how the community works here, what are the things we can do/no-do etc. So a buffer time of one year would take to understand the community in my opinion.
You are constantly moderating in community. There are lot of things come here. You are constantly monitoring the community activities and report any issues to moderators for immediate actions, taking actions against on false contents which you have privilege to do. Upvote questions and answers which are really relevant.
You are taking a humble approach to newbies. We are stable now. So we don't need to do a strict scrutiny to the new questions which are coming to our site now. We can take a humble approach now and teach a newbie how to ask a question and how to answer a question. This will enrich and inspire them and that will eventually leads to more frequent participation from their side. This is a must requirement in my opinion.
You have a quiet good knowledge about the moderation and your additional responsibilities if you become a moderator. For this, you should engage with the moderators and take feedback from them. Meta is a wonderful place to ask such questions if you are not clear with the approach you should take in a given situation or you need assistance from the moderators.
Last but not least, you are a person who are using all your moderation privileges in its fullest. This is a MUST.

You should not nominate if:

You just answered 5 questions and now you feel you know everything about moderation. We appreciate your effort, but which is not enough for moderation.
You don't have patience and you are responding to any no-do action with    your first instinct or rage. Remember patience is the quality a moderator need. A best moderator will engage the community to take a decision if it is possible even if he can do that action with a simple click.
You don't know what are the rules in this community
You are not using your moderator privileges in it's fullest. Oh boy!! this is critical one.

Why I am not applying this time
If you look my profile, I am eligible to apply for election. But I am not considering me as an eligible candidate, since:

My moderation in this community for the past 5 month is very less. At least, it is not satisfying myself. I am not getting 2 hours to spend here due to my busy office work.
I know people who are constantly engaging with the community do exists and I would love to vote for them. Within two days, the people in my mind are not applying, then I will shoot a notification to them. This is something that I do always whenever an election happens.
Most importantly, I fear I could not find much time to do my moderation duties in the coming future. I think this is the reason why one of our existing moderator back out from his position. I really do appreciate that.

Now please keep this in mind and think. If you still feel you are good, then nominate yourself. :)
Comment: I already mentioned here that I withdrew my name from the nomination as because I am not considering myself as a good candidate for the post of **Moderator**. I just asked this here to be clear that who should apply & to whom should we vote for this post, Thank you for your response!
Comment: @ABHISHEKTRIPATHI My answer is not intended to you. This answer is my opinion to your question. Since this question is in general in the context, the answer also treat like that. :)
Answer: You can see in nomination page there are block showing of candidate score. You can judge by that which candidate is suitable for job. That is the way i choose whom to vote.
candidate score 37/40
reputation >= 20k
moderation badges: 5/8
editing badges: 6/6
participation badges: 6/6

Note: It is my opinion to choose candidate
Answer: I agree what Qaisar said ,
Apart from this you can click on review  and meta post link to see their meta participation, how they have answered some question and take part in discussions.
By clicking on reviews you can see their participation in close vote/Low Quality post review/ suggested Edits etc..
from review link you can easily identify how frequent they participate in moderator activity to make site more clean
candidate score 23/40
reputation 9k
moderation badges: 5/8
editing badges: 4/6
participation badges: 5/6


Url.Action fora da Area

Question: Separei o cadastro de usuário do asp.net mvc em uma área
Area Controle
Em uma action, de cadastro, ele envia o link de confirmação, o mesmo é gerado da seguinte forma
var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);

Ao receber o email, ele fica a Url assim:
http://localhost:50855/Controle/Account/ConfirmEmail?userId..

Ele acaba pegando o nome da área, sendo que a Account está fora da área
Como posso resolver isso?
Answer: Só explicitar que a Action não usa Area:
var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code, area = "" }, protocol: Request.Url.Scheme);

Comment: te devo mais uma kkkk te mandar uma caixa de bera HUASHDU
Comment: Daqui a pouco vira um caminhão, hein?
Comment: [Ou então usa esse link aqui](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=58B8G88A995VJ).

Url.Action fora da Area


How to specify a custom method in a LINQ query (C# Entity Framework)

Question: I have defined a super class "Validity" which defines a time span (ValidFrom / ValidTo) in which an object is "valid". It also defines a function that returns true for a given timestamp, iff (=if and only if) a (derived) object is valid at this time.
public class Validity
{
    public int ValidityID { get; set; }

    public DateTime? ValidFrom { get; set; }
    public DateTime? ValidTo { get; set; }

    bool isValidAt(DateTime time)
    {
        return (ValidFrom == null || ValidFrom >= time)
            && (ValidTo == null || ValidTo < time);
    }
}

Now I would like to write some function that checks isValidAt within a LINQ query. I guess this is possible via IQueriable, but I didn't find out how...
The following code snipped is what I want to have "working" in some way (especially the where n.isValidAt(t)). So, how can this be achieved?
public class Node : Validity {
    public int NodeID { get; set; }

    public static getFirstNode(DateTime t)
    {
        MyContext db = new MyContext();
        var items = from n in db.Nodes
                     where n.isValidAt(t)
                     orderby n.NodeID descending
                     select n;
        return items.FirstOrDefault<Node>();
    }
}

--- WORKING SOLUTION  ---
I needed to adapt the solution of Zaid Masud a bit, to get it working. Note that I had to remove the this in the parameter list (now the method definition is public static IQueryable<T> isValidAt<T>(IQueryable<T> query, DateTime time) where T : Validity). Here is the source code:
public class Validity
{
    public int ValidityID { get; set; }

    public DateTime? ValidFrom { get; set; }
    public DateTime? ValidTo { get; set; }

    public static IQueryable<T> isValidAt<T>(IQueryable<T> query, DateTime time) where T : Validity
    {
        return query.Where<T>(c => (c.ValidFrom == null || c.ValidFrom >= time)
            && (c.ValidTo == null || c.ValidTo < time));
    }
}

Comment: what exactly does "isn't working" mean? exception? doesn't compile? what error?
Comment: The `where n.isValidAt(t)` isn't working... as written above.
Comment: Doesn't compile... as I thought I would have written invalid code. But in fact it's valid, as soon as I make isValidAt(...) public! -- Just didn't read the compiler message, because the auto completion didn't even suggest .isValidAt()...
Comment: Additional Question: This isn't able use any database index on validFrom/validTo, right? (Whereas a IQueryable-Solution would be).
Comment: @StefanK. you can use the `this` in the parameter list if you put the method in a separate static class.
Answer: You need to declare your bool isValidAt(DateTime time) method as protected so the derived class can access it:
protected bool IsValidAt(DateTime time)

However, after you get this compiling, I doubt that your LINQ to SQL provider will be able to translate the query to SQL. You will probably need to embed the logic inside your LINQ query and write something like:
var items = from n in db.Nodes
            where (n.ValidFrom == null || n.ValidFrom >= t) && (n.ValidTo == null || n.ValidTo < t)
            orderby n.NodeID descending
            select n;

This will work, but a better alternative is to create the following kind of extension method:
public static class ValidityExtensions
{
    public static IQueryable<T> Valid<T>(this IQueryable<T> validities, DateTime time) where T : Validity
    {
        return validities.Where(v => (v.ValidFrom == null || ValidFrom >= time) && (v.ValidTo == null || v.ValidTo < time));
    }
}

Now you can use this as follows:
var items = from n in db.Nodes.Valid(time)
            orderby n.NodeID descending
            select n;

Comment: That's what I would like to avoid... I mean, to rewrite the SQL-like where-part everywhere. I would like to put it into -one- function that just gives it a name and makes it reusable.
Comment: The last solution is what I wanted and did not get working (with IQueryable). But if I put the method into "Validity" you'll need to replace `from n in db.Nodes.Valid()` by `Node.Valid(db.Nodes, time)`.
Comment: @StefanK. we all would :) Unfortunately that is very difficult to implement in a LINQ provider. See my updated answer for a better alternative.
Comment: @StefanK. if you put the method in a static class you can use the `this` keyword


Dúvida sobre SQL em PHP

Question: Eu neste momento estou a realizar um trabalho que é preciso aceder a base de dados, e tive muita dificuldade em algumas queries, entre elas a query do UPDATE. Mas depois de muito procurar achei uma solução e queria perguntar qual é a diferença, qual a que é melhor, etc.
Eu usei
$sql = mysql_query("UPDATE tabela SET campo1 = ' ".$1." ', campo2 = ' ".$2." ' WHERE user = ' " .$3. " ');

Mas o que funcionou foi :
$sql = mysql_query("UPDATE tabela SET campo1 = '$1', campo2 = '$2' WHERE user=$3");

Ou seja retirei pontos finais, aspas etc.. Faz alguma diferença? Eu usei com os pontos e as aspas em queries do tipo SELECT e INSERT e funcionou.
Comment: Essa pergunta tá fazendo uma confusão danada entre query e operação de _string_ em PHP. Sugiro aprender separadamente cada coisa.
Comment: Sua variável chama `$1`? nenhuma forma é legal pq usa funções obsoletas e removidas das versões mais novas do PHP(7)
Comment: Não. Apenas estava a tentar criar um exemplo haha
Comment: Eu sempre pensei que o ponto era para diferenciar o php da query. as aspas penso que são por causa de ser uma query, porque no Phpmyadmin também é preciso.
Comment: Então, o ponto serve para concatenar(juntar) strings(textos), no php resumidamente a diferença entre as aspas simples e as duplas é, o primeiro tipo não lê o valor de uma variáve dentro já a segunda sim. Exemplo: `$v = 'valor'; echo '$valor'; echo "$valor";` Para mais detalhes veja [essa pergunta](http://pt.stackoverflow.com/q/4652/91). No SQL as diferença entre elas é que geralmente as simples delimitam valores e as duplas podem ser o caracter de escape em nomes de colunas com palavras chaves/reservadas. Se tiver alguma dúvida coloca ai no comentário.
Comment: o erro que esta tendo é que tem um espaço entre as aspas simples e as duplas, troque `' ".$1." '` por `'".$1."'` e nos outros tbm
Answer: Em PHP, o operador . (ponto) concatena strings, e em strings podem ser delimitadas com aspas duplas ou simples. Em MySQL, strings são sempre delimitadas por aspas simples. Nos trechos apresentados, a string de PHP é com aspas duplas.
O primeiro trecho não deve ter funcionado porque, sem querer, acrescentava espaço em branco antes e depois do valor da variável inserida. Ilustrando com código:
$nome = "João da Silva";
"' " . $nome . " '" resulta em ' João da Silva '.
"'$nome'" resulta em 'João da Silva'.
O segundo trecho funciona como se deve. Recomendo trocar $1, $2, etc., por nomes representativos das colunas da tabela.

Dúvida sobre SQL em PHP