Removing columns in Pandas

Question: I work on a big Python dataframe and notice that some columns have same values for each row BUT columns' names are different.
Also, some values are text, or timeseries data.
Any easy was to get rid of these columns duplicates and keep first each time?
Many thanks
Comment: are the values are partially duplicated or completely duplicated?
Comment: completely as far as i can see (300 000 rows), including the format
Comment: Welcome to SO. Please read https://stackoverflow.com/help/mcve and post your attempted code.
Comment: Does this answer your question? [python pandas remove duplicate columns](https://stackoverflow.com/questions/14984119/python-pandas-remove-duplicate-columns)
Answer: Let create a dummy data frame, where two columns with different names are duplicate.
import pandas as pd
df=pd.DataFrame({
    'col1':[1,2,3,'b',5,6],
    'col2':[11,'a',13,14,15,16],
    'col3':[1,2,3,'b',5,6],

     })

    col1    col2    col3
0   1       11      1
1   2       a       2
2   3       13      3
3   b       14      b
4   5       15      5
5   6       16      6

To remove duplicate columns, first, take transpose, then apply drop_duplicate and again take transpose
df.T.drop_duplicates().T

result
    col1    col2
0   1       11
1   2       a
2   3       13
3   b       14
4   5       15
5   6       16

Comment: thanks Talha, no need to place an inplace=true somehwere to definitely modifiy the original df?
Comment: yes, you can place it, if you want to replace the original df instead of creating a new one
Comment: where exactly can i place it?
Comment: `df.T.drop_duplicates(inplace=True).T`

Removing columns in Pandas


Angular material reactive forms validation

Question: I want to use form validators, but I don't exactly know how, I'm trying to set a validation of max-length and required at the same time, but I am not able to, also I had looked for it and found nothing
Here us what I tried to do:
<code>import { literalMap } from '@angular/compiler';
import { Component, OnInit } from '@angular/core';
// import {FormsModule, ReactiveFormsModule} from '@angular/forms'
// import { FormControl } from '@angular/forms';
import { FormGroup, FormControl } from '@angular/forms';
import { Validators } from '@angular/forms';
@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.scss']
})
export class FormComponent implements OnInit {
  profileForm = new FormGroup({
    firstName: new FormControl('',Validators.maxLength(1), Validators.required),
    email: new FormControl('',Validators.email),
  });
  constructor() { }

  ngOnInit(): void {
  }
  onSubmit() {
    // TODO: Use EventEmitter with form value
    console.warn(this.profileForm.value);
  }
  testForm(){
    let a = this.profileForm.get('email').valid
    if (a){
      alert('jalo')
    }
  }
  save(){
    let email = this.profileForm.get('email').value
    if(email != '' ){
      alert('jalo')
    }
  }

}

</code>
Answer: put the two Validators in the table like that
<code> profileForm = new FormGroup({
    firstName: new FormControl('',[Validators.maxLength(1), Validators.required] ),
    email: new FormControl('',Validators.email),
  });
</code>


Converting sql query to ActiveRecord Rails

Question: I have a location table in my database which contains location data of all the users of my system.
The table design is something like
 id| user_id| longitude| latitude| created_at|

I have an array of users. Now I want to select the latest(sorted according to created at) location of all these users.
I am able to figure out the sql query for same
SELECT * FROM   my_table
WHERE (user_id , created_at) IN (
                SELECT   user_id, MAX(created_at)
                FROM     my_table
                GROUP BY user_id
            )
AND user_id IN ('user1', 'user2', ... );

Now as I am working in Ruby On Rails, I  want to write this sql query to activerecord rails. Can anyone please help me with this ?
Answer: I think this will give the correct result:
MyModel.order(created_at: :desc).group(:user_id).distinct(:user_id)

If you want to generate the exact same query, this will do it:
MyModel.where("(user_id, created_at) IN (SELECT user_id, MAX(created_at) from my_table GROUP BY user_id)")

I think the subquery will probably not scale well with a large data set, but I understand if you just want to get it into rails and optimize later.
Comment: This is not generating the same sql query

SELECT DISTINCT "my_models".* FROM "my_models" GROUP BY "my_models"."user_id", "my_models"."id"  ORDER BY "my_models"."created_at" DESC
Comment: I added an edit that should reproduce the existing query exactly - let me know how it goes!
Answer: How about adding a scope, and getting the same result in a slightly different way:
class UserLocation

  def self.latest_per_user
    where("user_locations.created_at = (select Max(ul2.created_at) from user_locations ul2 where ul2.user_id = user_locations.user_id)")
  end

end

Then you just use:
UserLocation.latest_per_user.where(:user_id => ['user1', 'user2'])

... to get the required data set.


Exponential objects in a cartesian closed category: $a^1 \cong a$

Question: Hi I'm having problems with coming up with a proof for this simple property of cartesian closed categories (CCC) and exponential objects, namely that  for any object $a$ in a CCC $C$ with an initial object $0$, $a$ is isomorphic to $a^1$ where $1$ is the terminal object of $C$. In most of the category theory books i've read this is usually left as an exercise, but for some reason I can't get a handle on it.
Comment: Try considering the fact that $a\times 1\approx a$, and use it in the diagram on the definition here: http://en.wikipedia.org/wiki/Exponential_object
Comment: Juan's answer seems to be on the right track here (I'm using Rob Goldblatt's Topoi which doesn't mention functors or adjoints till much much later on, so the other two answers don't really help me). However I'm still not clear as to how making the function $g$ in the diagram an isomorphism gets me much further. Would it be possible to have a little more detail on the proposed solution? Apologies again if this isn't the right place to ask this.
Comment: @Anas: Hi, and welcome to math.SE! Users with any number of "reputation points" [can comment on their own questions and answers](http://meta.stackexchange.com/questions/19756) (once you obtain 50 points, you gain the ability to comment anywhere), but you were not able to comment because you were not signed into the account that asked the question. I've now merged the duplicate account into the original. Here is an [explanation of reputation points](http://meta.stackexchange.com/questions/7237).
Comment: @ZevChonoles thanks for clearing that up and merging the accounts.
Answer: For any object $x$, we have:
$$\operatorname{Hom}(x,a^1)\cong \operatorname{Hom}(x\times 1,a)\cong \operatorname{Hom}(x,a)$$
So Yoneda's lemma gives us that $a$ is isomorphic to $a^1$.
Comment: Thanks for the answer, but I was looking for a proof that didn't use Yoneda's lemma, or the Hom notation, since the book I'm working from hasn't introduced either of those yet.
Comment: @Anas: I'm stunned that there's a category theory text that gets to cartesian closed categories before hom-sets or even Yoneda. For one thing, how do you even define exponential objects?
Comment: @ZhenLin Yeah I'm using Robert Goldblatt's Topoi: the Categorial Analysis of Logic, and from what I understand it's a reasonably controversial book amongst category theorists because of its approach to the subject.
Answer: You can also reason as follows, without the Yoneda lemma. But proving uniqueness of right adjoints is cumbersome without using Yoneda, and easy with. Anyway, here it goes:
The functor $(-)\times 1$ is isomorphic to the identity functor. The identity functor is a right adjoint of itself, so the identity functor is also right adjoint to $(-)\times 1$. Then uniqueness of right adjoints gives that $(-)^1$ is isomorphic to the identity functor.
Answer: I know that this is a bit late, but I'm readong the book right now and found this post, so i'll give my solution anyway, which doesn't use the Yoneda Lemma, or adjunctions, etc.
The idea is to notice that $id_a : a\to a$ is a terminal object in the comma category $C\to a$. But the definition of the exponential allows you to show that $ev : a^1 × 1 \to a$ is also a terminal object, and therefore isomorphic to the first one. It is then easy to conclude that $a^1×1 \simeq a$ and so $a^1 \simeq a$


PCA versus other ways of feature selections?

Question: I have been using many approaches like the random forest, ANOVA, chi^2, etc. to select the most important features for machine learning. After I read more on the feature selection and dimensionality reduction, I find that there is no one method that fits all cases. I find that many books about machine learning mention the principal component analysis. I find a dataset with 60 features (independent variables) and 1 dependent variable,  I apply the PCA on it and find that 8 features' variance contributing to 95% of the total variance. As many books explain, PCA is an unsupervised method, while most ML-based feature selection methods are supervised approaches. In this sense, I do not see how PCA could help to reduce the dimensionality (by removing those low-variance variables). I find one thing very interesting. I apply a random forest method and PCA on the same datasets, which turns out that the most important features from the random forest are totally different from those given my PCA. I prepare two data sets, one with variables, suggested by random forest, removed and one with variables suggested by PCA, removed, and then fit them into the same regression model with the machine learning method. The one with the random forest has an accuracy of 20% higher than that on PCA. I am not sure if the result makes sense or not, but if it is true, how could one use PCA for features selection?
Answer: You mention it in the question, but this is basically the difference between supervised and unsupervised feature selection methods. Supervised methods select features that are best for a particular task, usually for discriminating between groups of samples. With unsupervised methods, you have no knowledge of any groups in the data, so you just want to select features that capture the most variability. There's no particular reason to expect that the variables that capture the most variance will also be the best for discriminating between particular groups, or vice versa. If you already know the groups you're trying to describe with fewer features, supervised methods will likely be preferable.
Do be careful to not bias your model output by performing feature selection too early, though - you should split the data into train/test cohorts, select features on the training data, train your model on the training data, and finally evaluate on the test data. Do not perform feature selection and then split into train/test, or evaluate accuracy/other metrics on the training data. The way you describe your training procedure, it sounds like there is some bias in one or both of the feature selection or evaluation.


Imprimir arquivo do word pelo c#

Question: Ola pessoal estou tentando imprimir um arquivo word.doc, estou usando o seguinte código.
using Microsoft.Office.Interop.Word;
Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application();
        string CaminhoContrato ="C:\\arquvio.doc";
        Document document = application.Documents.Open(CaminhoContrato);

Dessa forma eu consigo abri-lo, mas preciso mesmo imprimir o arquivo sem que ele seja aberto. Alguém pode me ajudar?
Answer: Já tentou isso aqui?
Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application();
string caminhoContrato ="C:\\arquvio.doc";
Document document = application.Documents.Open(caminhoContrato);
document.Activate();
document.PrintOut();

Comment: Assim está dando erro na linha  application.Documents.Open(...)oMissing);
Comment: @FabrícioSimoneAlanaMendes que erro?
Comment: ele não aceita o código
Comment: Deixa só o application.Documents.Open(CaminhoContrato); então
Comment: @FabrícioSimoneAlanaMendes fiz umas mudanças ali
Answer: Usei esse código.Nãousing Microsoft.Office.Interop.Word;
Meu código ficou assim.
string CaminhoArquivo = "C:\\arquivo.doc";

 Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
        wordApp.Visible = false;

            Microsoft.Office.Interop.Word.Document doc = wordApp.Documents.Add(CaminhoContrato);
            wordApp.ActiveDocument.PrintOut(true, false, Microsoft.Office.Interop.Word.WdPrintOutRange.wdPrintAllDocument,
Item: Microsoft.Office.Interop.Word.WdPrintOutItem.wdPrintDocumentContent, Copies: "2", Pages: "1",
PageType: Microsoft.Office.Interop.Word.WdPrintOutPages.wdPrintAllPages, PrintToFile: false, Collate: true,
ManualDuplexPrint: false);
            doc.Close(SaveChanges: false);
            doc = null;
            ((Microsoft.Office.Interop.Word._Application)wordApp).Quit(SaveChanges: false);
            wordApp = null;

Dessa forma ele não abre a caixa de dialogo da impressora.
Imprime diereto
Comment: Olá Amigo blza?
Você conseguiu imprimir mais de uma página dessa maneira que voce postou, Estou tentando aqui, mas só funciona quando tem uma pagina. Agradeço se puder dar uma dica.

Imprimir arquivo do word pelo c#


Contextual filter with taxonomy term that is not in the url

Question: I'm hoping someone could please help me tame the beast that is known as contextual filters. :) I have a series of nodes that all have a specific taxonomy term assigned to them (all from the same vocab), but for my url path I do not include those:
For example:
Vocabulary name = videos
A node has terms:
-food
--vegetable
---carrot

assigned to it, but the only url that I want is:
site.com/videos/title-of-node

And then all other nodes which have terms on them will all be under the 'videos' directory:
site.com/videos/title-of-another-node
site.com/videos/title-of-yet-another-node

I created a view that has a contextual filter where I want to display only the nodes that have the carrot term. And it that works perfectly when previewed on the views page, but when loading up the actual page I get a listing of ALL the nodes under the "food" term because I have "WHEN THE FILTER VALUE IS NOT IN THE URL --> Display all results for the specified field"
My main problem I think is that "The contextual filter values is provided by the URL." And my terms are not in the url. So somehow I need to pull the terms associated with each node.
Any help would be much appreciated!
Comment: how are you defining the urls? and what is the view path you are using
Comment: @MohammedShameem - My view path is /food. If I were to go to /food/carrot then it works just fine. But I need the url to be /food/title-of-node. My goal is to have all my nodes be under the 'food' term. I'm not sure what you mean by defining the urls? Hope that helps!
Comment: so do you want to filter the node depending on the words in the title of the node? or the terms that the node is associated with?
Comment: The terms would be perfect! So as in my example if i have 10 videos with the term carrot then all 10 would show. But, my url has to be /food/title-of-each-carrot-node. i hope that makes sense.
Comment: and does the node have multiple terms associated with it or a single term?
Comment: i have it set up that when i assign the node a term, that it also assigns it the parent terms. so in this example it would have the terms carrot and vegetable. But these nodes also might have other terms in the future. Any ideas?
Answer: Instead of creating a node view create a taxonomy view.
In that provide two relationships:

Taxonomy term: Content with term;
Taxonomy term: Content using {Name of the taxonomy field in the
content type}*;
Add a contextual filter of the type Content : Title;
Use the first relationship for the contextual filter, Make necessary changes in the more option such as change to lower case turn space to dashes etc;
Add the required fields from the content with the relationship set to 2);

You are good to go.
EDIT : As per the discussion There was another need to also show the nodes under a term and its sub terms.

Create a view of the type content;
Add the required fields;
Add a contextual filter of the type Content: Has taxonomy term ID (with depth) and select the depth a value as deep as the hierarchy you have in the taxonomy.

Now when you pass the term id as the input it would show all the nodes under that taxonomy term including the child nodes.
If you wish to change the url to have the term name instead of the term ID Do the following.

In view give the path as taxonomy/term/% this will override the default taxonomy path;
Install Pathauto Module this depends on Tokens module so have to install that as well;
In Configuration -> URL aliases you have a tab called Patters;
Set the pattern of the "TAXONOMY TERM PATHS" to what you would like it to be. Make sure that the last value is [term:name] so if you want the path to be category/carrot you should give it as category/[term:name];
If you have already added the taxonomy terms then you would need to do the "BULK UPDATE" which is again a tab on the URL Alias page.

Now when you visit the page category/termname you will see all the nodes under the term including the child terms.
Comment: Thanks Mohammed! I'll give that a try. Can you direct me how to create a taxonomy view please. I can then take it from there. Thanks!
Comment: When you create a view there is a dropdown that says "show" which would we selected to content. Change that to taxonomy.
Comment: Mohammed I do not see a "Content using {Vocab name}" as an option. I only see content using catalog, category, keyword, tags, term. Am I missing something?
Comment: I mean you should replace the vocabulary name that you have :-) sorry for not being clear. will update my answer to make it more clear. so if it is category then it should be Content using category etc...
Comment: Ah ok. :) Makes sense. Unfortunately I don't see my vocab named "food" listed as one. Do I need to reference it somewhere else to see it?
Comment: have you created a vocabulary called food? or is food a term ?
Comment: The vocab is called food. And then a list of terms are under that: vegetable, carrot, etc..
Comment: when you click on the taxonomy link from the structures do you see food listed there?
Comment: Still struggling with this one? Do you want to go over it once again?
Comment: Thanks Mohammed, but been trying all day and something is just not right. I hate to waste your time with it.
Comment: No issues I would be more than happy to help you.
Comment: Jump into the chat if you have a sec...
Comment: Have edited the answer to cover your second issue.
Comment: I'm confused, @Mohammed shameem . I can't see where you can get the NOT-IN-PATH term of the current entity (commerce product, in my case. Node in Dan case)


Button gradient borders with transparent background

Question: Here is the result I would get:

So the default button has gradient border with transparent background (as I want to see the parent's background through it).
When the user hover over the button I want to fill it with the same gradient has the borders.
So first I tried with border-image property and with an .svg image of my border:
button {
  background: transparent;
  background-repeat: no-repeat;
  border: 3px;
  border-style: solid;
  border-color: transparent;
  border-image-source: url(assets/images/icons/border.svg);
  border-image-repeat: stretch stretch;
  border-image-slice: 49;
  border-image-width: 100px;
  border-image-outset: 6px;
  padding: 16px 28px;
  border-radius: 100px;
}

So I have more or less the result I was waiting for:

Now, how to manage the hover-over animation and fill the background with no size changes !?
Maybe border-image isn't the best way to do it ?
Thanks for your help, Cheers !
Comment: can you share the SVG you have created?
Comment: @TemaniAfif You can get it in here : https://wetransfer.com/downloads/02be51549919378264f1789c3264d9f520180816002553/0f52af
Comment: @TemaniAfif for now I'm using an svg, but maybe we can reproduce the same effect with colors ... ? Here is my correct linear-gradient: border-image: linear-gradient(-45deg, #2ae88a 0%, #08aeea 100%);
Answer: An idea is to rely on background-attachement:fixed since you are using a background image and we can simulate the transparent effect BUT you will have the scrolling effect on the background:

.container {
  padding:100px 0;
  background:
    url(https://picsum.photos/800/300?image=1069) fixed;
}
.button {
  width:200px;
  height:50px;
  cursor:pointer;
  color:#fff;
  margin: auto;
  border:3px solid transparent;
  border-radius:50px;
  text-align:center;
  font-size:30px;
  background:
    url(https://picsum.photos/800/300?image=1069) padding-box fixed,
    linear-gradient(-45deg, #2ae88a 0%, #08aeea 100%) border-box;
}
.button:hover {
  background:
    linear-gradient(-45deg, #2ae88a 0%, #08aeea 100%) border-box;
}

Some text

Comment: Ok Thanks, it's helped me finding the proper solution, I will update my post.
Answer: SOLUTION
Ok finally I found a workaround to accomplish my desire, it almost all come from the SVG file. I tweak a little my SVG in order to get two different path on with the gradient stroke but not filled, and the other one gradient filled but no stroke. One over an other and the opacity is the master key :)

<svg class="icon" viewBox="0 0 250 100" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <defs>
      <linearGradient x1="0%" y1="100%" x2="100%" y2="0%" id="linearGradient-1">
          <stop stop-color="#08AEEA" offset="0%"></stop>
          <stop stop-color="#2AE88A" offset="100%"></stop>
      </linearGradient>
  </defs>
  <path fill="none" d='M50,95 a45,45 0 0,1 0,-90 h150 a45,45 0 1,1 0,90 h-150' />
  <path class="icon--plain" fill="url(#linearGradient-1)" d='M50,95 a45,45 0 0,1 0,-90 h150 a45,45 0 1,1 0,90 h-150' />
</svg>
Invest now

Here comes the CSS (I am using SCSS btw):
a[type="button"] {
  position: relative;
  padding: 1rem 1.75rem;
  z-index: 0;

  .icon {
    position: absolute;
    top: 0px;
    left: 0px;
    height: 100%;
    width: 100%;
    z-index: -1;

    path {
      transition: opacity 0.4s ease;

      &:first-of-type {
        fill: transparent;
        stroke: url(#linearGradient-1);
        stroke-width: 3;
        opacity: 1;
      }

      &.icon--plain {
        opacity: 0;
        stroke: none;
        stroke-width: 0;
      }
    }
  }

  &:hover {
    path {
      &:first-of-type {
        opacity: 0;
      }

      &.icon--plain {
        opacity: 1;
      }
    }
  }
}

Comment: Probably best to use a CSS-only solution, if you can. You want to avoid the extra complexity and browser-issues involved with SVG.
Comment: which browser-issues with SVG are you talking about ? Honestly there are no complexity in that solution IMO, the "hard" part is to conceive the SVG file, the rest is just easy css stuff.
Answer: This is achievable with CSS gradients. Have a look at my solution below:
.box {
  width: 250px;
  height: 100px;
  background: transparent;
  border: 5px solid transparent;
  -moz-border-image: -moz-linear-gradient(top, #3acfd5 0%, #3a4ed5 100%);
  -webkit-border-image: -webkit-linear-gradient(top, #3acfd5 0%, #3a4ed5 100%);
  border-image: linear-gradient(to bottom, #3acfd5 0%, #3a4ed5 100%);
  border-image-slice: 1;
  color: white;
}

.box:hover {
  background: linear-gradient(to bottom, #3acfd5 0%, #3a4ed5 100%);
}

Note, you will need to add your own gradient into the .btn class under background-image: linear-gradient...
Play around with my solution here:
https://codepen.io/lachiekimber/pen/mjYNeN
Comment: Only issue is the border-radius.
Comment: this is not transparent, he's using an image as background not color


Função e método são a mesma coisa?

Question: Quando falamos em métodos e funções, estamos falando a mesma coisa?
Por exemplo:
function blablabla blabla

Isso é um método?
Comment: [Quais são as definições de método, função e procedimento?](https://pt.stackoverflow.com/q/11848/91)
Comment: "funções: todo procedimento que retorna algo. Métodos: todo procedimento que não retorna nada." Poderia da exemplos disso?
Comment: @LucasCarvalho Leia as respostas dadas, não a pergunta.
Answer: Não é a mesma coisa, mas quase. A funcionalidade de ambos é a mesma. É uma diferença entre terminologia de paradigma procedural e orientado a objeto.
A função é um algoritmo, um conjunto de instruções que faz algum processamento, mínimo que seja. Em geral funções produzem algum resultado (matematicamente deveria ser obrigado, mas em programação há condescendência). Funções podem receber argumentos.
O método é a mesma coisa com a especialização que ela está dentro de uma classe e costuma automaticamente trabalhar com o estado de um determinado objeto. No fundo esse objeto é passado como argumento para a função para que seus dados possam ser manipulados. O método é considerado um membro que tem um comportamento em cima do estado do objeto.
O mecanismo interno no código é idêntico. É praticamente um açúcar sintático para disponibilizar o this no contexto local.
Métodos estáticos no fundo são funções encapsuladas dentro de uma classe, ou seja é só uma organização de escopo de onde a função está.
Algumas linguagens podem usar uma terminologia específica, mas o conceito é igual para todas elas.
Leia mais sobre função: Quem é quem no uso de funções?.
Relacionado: Qual a diferença entre funções e procedimentos?.
Coloquei no GitHub para referência futura.
Answer: A resposta pode ser sim e não isso depende do contexto.
No geral método e função são termos usados para identificar um bloco de código nomeado que pode ser reutilizado em várias partes do programa.
De maneira mais especifica não são a mesma coisa. Funções são utilizadas em linguagens que utilizam o paradigma imperativo e outra caracteristica importante elas (na maioria da vezes) não guardam estados sua execução é atomica ou seja uma vez terminada todas a variáveis locais tem seus valores 'apagados' ou resetados.
Métodos esse termo é mais usado com o orientação a objetos. Um objeto/classe nada mais é que uma estrutura que combina dados (propriedades) com comportamentos (métodos) e diferente de uma função pode guardar estado.

Função e método são a mesma coisa?


Continuity of improper integral with a continuous integrand.

Question: I am a newbie in analysis and am trying to wrap my head around some continuity/compactness/finiteness concepts.
Let $f(x,y):\mathbb{R}^2\mapsto\mathbb{R}$ be a continuous function in both $x$ and $y$ and define
$$
F(x) = \int_0^{\infty}f(x,y)dy.
$$
Assume that $F(x)<\infty$ for all $x>0$. Can I show that $F(x)$ is continuous for $x>0$?
(The original question is different (see details below), but this is the most important part of the proof (thanks to the hint given by Brian))
Given a compact set $\mathcal{X}$ and suppose $0$ is not a member of $\mathcal{X}$. Can I show $\sup_{x\in\mathcal{X}} F(x) <\infty $?
Here are what I tried so far:

Since $\mathcal{X}$ is compact so $\sup_{x\in\mathcal{X}} F(x) = \max_{x\in\mathcal{X}} F(x)$. Moreover, since $F(x)<\infty$ for any $x>0$ and $0\notin \mathcal{X}$, then $\max_{x\in\mathcal{X}} F(x)<\infty$.
(This proof seems okay to me. But the continuity of $f(x,y)$ is not used anywhere, which makes me a little puzzled).
Since $f(x,y)$ is continuous function and $F(x)<\infty$ for all $x>0$, then $F(x)$ is a continuous function for any $x>0$ (is this true?). Since $\mathcal{X}$ is compact so $\sup_{x\in\mathcal{X}} F(x) = \max_{x\in\mathcal{X}} F(x)$. The maximization is finite because it is the maximum of a continuous function in a compact set. (This proof does use all given conditions, but the first assessment is not clear to me. Any reference to existing theorem is appreciated.)

Any help is highly appreciated!
Answer: This fails in general. For example, define
$$f(x,y) =\begin{cases}  0, & x\le 1\\ = \frac{1}{1+(y-1/(x-1))^2}, & x>1 \end{cases}$$
Then $f$ is continuous on $\mathbb R^2,$ but $\lim_{x\to 1^+}F(x) = \pi,$ while $F(1) = 0.$
Comment: Thanks for the example. It is interesting. But $F(x)$ seems to be continuous for $x>0$? Discontinuity is at zeros? Am I missing something?
Comment: No, you're not missing anything. But all we need to do is move this example to the right. I've edited my answer.
Answer: I think you need the extra assumption that the integral is uniformly convergent. Altough I do not have a counterexample, the following argument seems to show where this is needed:
For if we write $\vert F(x)-F(z)\vert \leq \vert \int_0^{M}(f(x,y)-f(z,y))dy\vert +\vert \int_M^{\infty }(f(x,y)-f(z,y))dy\vert$ and let $\epsilon >0$ and then choose $\delta_1 >0$ so that $\vert f(x,y)-f(z,y)\vert <\epsilon $ whenever $d((x,y),(z,y))<\delta_1 .\ $
Then in this case,
$\tag 1\vert \int_0^{M}(f(x,y)-f(z,y))dy\vert\leq M\epsilon$.
Now, $\vert \int_M^{\infty }(f(x,y)-f(z,y))dy\vert \leq \vert \int_M^{\infty }f(x,y)\vert +\vert \int _M^{\infty }f(z,y)dy\vert$.
If the convergence of the integral is uniform we may choose
choose $M$ such that $\tag2\vert \int_M^{\infty }f(x,y)dy\vert<\epsilon $ and $\tag3\vert \int _M^{\infty }f(z,y)dy\vert<\epsilon$.
Take $\delta =\delta_1/2$ and combine $1)$, $2)$, and $3)$ to finish the proof.
If the convergence is not uniform then I do not see how to get $\vert \int_M^{\infty }(f(x,y)-f(z,y))dy\vert< \epsilon $
Comment: Your set is not compact: it contains the strip $(x-\delta_1/4,x+\delta_1/4)\times\mathbb R $. And if it were,  the max would be $f (c,y_0) $ for a fixed $y_0$.
Comment: I meant for fixed y. Anyway, I do not think the claim is true as stated.  I am looking for a counterexample. I think now you need an extra assumption, see my edit.
Comment: Does $f(x, y)\geq 0$ help in any way?
Answer: For part 1, only continuous functions are guaranteed to attain their maximum on compact sets.
Comment: Thanks for your quick reply! So both routes boil down to proving the continuity of F(x)?
Comment: Yes! That's the most important part.
Comment: Can this be shown? It would be great if you can give me some hint or reference to some theorem. Thanks!


How to delete pages created in panels?

Question: I have some testing content that I played with in panels,  but there is only disable options. They are on accessible on this URL:
<code>admin/structure/pages
</code>
How to delete these?
Answer: First, check your user's role has the permission to delete panel pages and or nodes.
When there is no delete button under the clicked triangle, and these are Panel nodes, they might be deleted from the node manager and not from Panels (I used it a long time ago for 2-3 panel-nodes and I don't recall exactly if it's there).
Comment: Yep, was a permissions issue, now why on earth does panels come with permissions disabled for admin to control his own site?....I find this behavior very annoying and it causes issues. Is there a way to have ALL modules set as default permission ON for super admin?

How to delete pages created in panels?


EF6 Code First Unable to Update Foreign Key on Object - referential integrity constraint

Question: I have a one to one relationship between Person and Place. If I try to change the PlaceId, or assign the Place property a new place I get errors. How are you supposed to change the related entities?
The below fails with: A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship.
person.Place.PlaceId = placeId;
_db.Entry(person.Place).State = EntityState.Modified;
_db.Entry(person).State = EntityState.Modified;
_db.SaveChanges();

If I try updating with the below I get same error. Should I just use stored procedures for something like this? It took me several minutes to create a stored proc to do the update but several hours of messing with Entity Framework and I still can't get it to work.
person.Place = Place; //where Place is a valid object

Comment: The "it took me several hours" comment is just because you don't know how to do it.  Not because of anything wrong with EF.  If you didn't know how to do it in SQL, it might take you several hours to figure that out too.  In any event, it's hard to answer your question because you don't say exactly how you've defined your entities.  The way to do it would be different depending on different definitions.  When you say it's a 1:1, are you sure?  EF only supports 1:1 relationships with a shared primary key, and it doesn't look like that's the case here.
Comment: More than likely, you actually have a Many:1 that you only link one item to.  By the way, when you say "I tried xxx, but it didn't work", "didn't work" is vague and doesn't tell us anything... What happened when you did xxx?  Did you get an error?  Did it do nothing?  Did it sing the national anthem?
Comment: I think you misread part of it, I mentioned "If I try updating with the below I get same error." The below is "person.Place = Place;"
Answer: It is a 1:1 relationship.
public class Person
{
  public int PlaceId {get; set;}
  [ForeignKey("PlaceId")]
  public Place Place {get; set;}
}

I finally got it to work by setting the property to null and then setting the FK property after that. Also, if I set the EntityState to modified before I set the FK value then I get the same error so it has to be done in this exact order. Which I am not a fan of because it is not intuitive and I could not find any documentation for how to do this.
 _db.People.Attach(person);
 _db.Entry(person).State = EntityState.Modified;
person.Place = null;
person.PlaceId = placeId;


Abstract Algebra elementary mapping Question 1

Question: Let $F : \mathbb{N} \to \mathbb{N}$ be the mapping defined by $F(n) = n + 1$ for all $n \in\mathbb{N}=\{0, 1, 2, 3, . . .\}$, and let $I : \mathbb{N} \to \mathbb{N}$ be the identity mapping defined by $I(n) = n$ for all $n \in\mathbb{N}$.
(a) Show that there does not exist any mapping $G : \mathbb{N} \to \mathbb{N}$ which satisfies $F \circ G = I$.
(b) Construct one example (or several examples) of mapping $H : \mathbb{N}\to \mathbb{N}$ which satisfies $H \circ F = I$.
Comment: What have you tried so far? Where do you get stuck?
Answer: (a) Suppose there is such a $g$; then:
\begin{alignat}{1}
(fg)(0)=i(0)=0 &\Rightarrow f(g(0))=0 \\
&\Rightarrow g(0)+1=0 \\
&\Rightarrow g(0)\notin \Bbb N \\
\tag 1
\end{alignat}
against the assumption that $g$ is a map from $\Bbb N$ to $\Bbb N$: contradiction. Therefore, such a $g$ doesn't exist.
(b)
\begin{alignat}{1}
(hf)=i &\Rightarrow h(f(n))=n, \forall n\in \Bbb N \\
&\Rightarrow h(n+1)=n, \forall n\in \Bbb N \\
\tag 2
\end{alignat}
Therefore, any $h$ which sends $0$ to any natural and each nonzero natural to its predecessor, fits. Necessarily, none of such $h$ is injective, because there is a natural $\tilde n$ (characterizing $h$, actually) which is image of two distinct ones: $0$ and $\tilde n+1$.
Answer: Hint:  First, this is a somewhat famous example/fact.
The problem you will encounter in part $1)$ is that you will need to subtract $1$ from everything, in order to undo adding $1$.  But $0-1=-1$, so you end up going outside the desired range.
On the other side you don't run into this problem (reason?).
Answer: Suppose that $F\circ G = I$.  Consider more carefully how these functions work on the element $0$.
You have that $I(0)=0$
You would have that $(F\circ G)(0) = F(G(0))=0$... but this is impossible.  Why?

 Clearly, $F(n)>0$ for all $n$, in particular for any possible value that $G(0)$ could have taken.  It follows that no such $G$ could exist.

Suppose that $H\circ F = I$.
Then in particular for any $n$ we have $I(n) = n$ and so $(H\circ F)(n)=n$.  That is, $H(F(n))=n$ and $H(n+1)=n$ for every $n$.

 So, $H(1)=0, H(2)=1, H(3)=2,$ etc...  This information alone is almost enough to fully determine what $H$ is.  The only missing piece of information is how $H$ map's $0$.  We can make any arbitrary choice for $H$ we want and it will be sufficient.

$~$

 $H(n)= \begin{cases} 0&\text{if }n=0\\n-1&\text{otherwise}\end{cases}$ is one such choice for $H$.  In general you could have $H_k(n) = \begin{cases}k&\text{if }n=0\\n-1&\text{otherwise}\end{cases}$ for any natural $k$ also works.


MySQL How do I insert across multiple tables correctly?

Question: If I have an input file like:
US, P1, AgriZone, H, 1000, 1200, 1101, 1210
US, P2, ArgiZone, L, 120, 122, 345, 566
MX, Q4, FarmOne, H, 1120, 2200, 1111, 2345

And I have the following tables.
Tables In SQLFiddle
My Problem: How do I insert these records correctly into the db (considering one row falls into multiple tables)? How do I make sure that I only ever add unique table columns? Example Agrizone above only needs one entry in the table Farm? What is the typical approach here when inserting like this?
 try
      {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = (Connection) DriverManager.getConnection(
            "jdbc:mysql://" + this.getServer() + "/" + this.getDatabase(),
            user, password);

        Statement s1 = (Statement) con.createStatement();
        s1.executeUpdate("INSERT INTO" ??);

        con.close();

      }
  Catch(Exception blah)

How do I manage this type of insert, making sure PKs and FKs are set up correctly?
Thanks greatly stackoverflow community!
Comment: did you try restricting the column to unique? and you can decide what to do in case of duplicate (update or ignore)
Answer: Do implement constraints on your db tables

For example FARM_TITLE in farm table should be UNIQUE (it not possibile to insert twice "Argizone")
Use foreign key to link tables each other. This gurantees that you will be able to reconstruct a row of the file like: US, P1, AgriZone, H, 1000, 1200, 1101, 1210
that has been "splitted" into multiple tables

-Use transactions: so you can do more insert statements on more tables. If an insert fails, rollback transaction so that you won't have a row of the file "partially" inserted on the db:
 try{
   con.setAutoCommit(false);
   //do the multiple queries

   con.commit()
}
catch(Exception e) {
   con.rollback();
}

A pseudo code with the sql insert for the row: US, P1, AgriZone, H, 1000, 1200, 1101, 1210
Is suppose US is an origin not yet in table origin so first insert the origin:
  //this is pseudo code that insert into db table and retreive the id inserted. ID shoul be primary key and autoincrement
 int origin_id = execute( INSERT INTO ORIGIN(ORIGIN_NAME) values ("US");

 //now we insert the P1 stock. Again STOCK_ID primary key auto inc
 int stock_id = execute( INSERT INTO STOCK(ORIGIN_ID, STOCK_TITLE) values (origin_id, "P1");

 //now fill table FARM
 int farm_id = execute (INSERT INTO FARM(STOCK_ID, FARM_TITLE, SIZE, FARM_COMPNENTS) values (stock_id,"Agrizone","H","100");

 //finally a cycle to insert in GATE suppose we have n entries in this case (1200, 1101, 1210). I image to have an array
 for(int i =0; i<n; i++)
     INSERT INTO GATE (FARM_ID, FARM_COMPONENTS) values (farm_id,value[i]);

Comment: Sure but i need to fully understand the file row structure. For example: US, P1, AgriZone, H, 1000, 1200, 1101, 1210.  wich is the corrispondence between file field and db tables filed?
Comment: Could you supply an example of how I would set up the insert on the first row of the input file (considering I would fix the database and create uniques)?
Comment: Ok each row on the file input is an entire represented Origin. The structure is ORIGIN, STOCK, FARM, SIZE, VALUE(1), VALUE(2).... VALUE(n). The tables can be found at http://sqlfiddle.com/#!2/b468b . There can be up to n amount of values following. But the initial value(1) must be inserted into `Farm`, the rest of the values insert into table `GATE`
Comment: please refer to this page http://stackoverflow.com/questions/9830062/mysql-how-do-i-create-this-subquery  for further explanation if needed. I drew diagram and all


Functional vs Safety / Static vs Dynamic instantiations

Question: I'm in a situation where I think that two implementations are correct, and I don't know which one to choose.
I've an application simulating card readers. It has a GUI where you choose which serial port, and speed to use, and a play and stop button.
I'm looking for the best implementation for reader construction.
I have a SimulatorCore class who's living as long as my application
SimulatorCore instantiate the Reader class. And it will be possible to simulate multiple readers on multiple serial port.
Two possibilities:

My Reader is a pointer (dynamic instantiation), I instantiate it when play button is hit, delete it when stop button is hit.
My Reader is an object (static instantiation), I instantiate it in SimulatorCore constructor then create and call Reader.init() and Reader.cleanup() into my Reader class and call these when play and stop are being hit

I personally see the functional side, and I clearly want to use pointer, and do not have any reader instantiate if no reader are simulated.
Someone say me that I should use static instantiation (Reason : for safety, and because "it's bad to use pointer when you have choice to not use them")
I'm not familiar with them, but I think I can also use smart pointer.
Code samples: 1st solution:
class SimulatorCore
{
    play(){reader = new Reader();};
    stop(){delete reader; reader = nullptr;};

private:
    Reader *reader;
}

Code samples: 2nd solution:
class SimulatorCore
{
    play(){reader.init();};
    stop(){reader.cleanup();};

private:
    Reader reader;
}

The code is unstest, I've juste wite it for illustration.
What is the best solution? Why?
Answer: You can easily use shared_ptr/unique_ptr:
class SimulatorCore
{
    play(){_reader = make_shared<Reader>();};
    stop(){_reader = nullptr};

private:
    shared_ptr<Reader> _reader;
}

That will solve your problem right way, I guess.
Dynamic allocation gives some problems, for example, with throwing exception (there can be memory losing if between play() and stop() there will be thrown exception, for example, and stop() will never be called). Or you can just forget somewhere call stop() before destruction of SimulatorCore, it is possible if program is heavy.
If you never tried smart pointers, it is good chance to start doing it.
Comment: Thanks, I've finally use unique_ptr and it's working great. I'll accept the other answer because of the explanations, but you solved my problem.
Answer: You should generally avoid performing dynamic allocation with new yourself, so if you were going to go with the 1st solution, you should use smart pointers instead.
However, the main question here is a question of logic. A real card reader exists in an idle state until it is being used. In the 2nd solution, what do init and cleanup do? Do they simply setup the card reader into an idle state or do they start simulating actually having a card being read? If it's the first case, I suggest that this behaviour should be in the constructor and destructor of Reader, and then creating a Reader object denotes bringing a card reader into existence. If it's the second case, then I'd say the 2nd solution is pretty much correct, just that the functions are badly named.
What seems most logical to me is something more like this:
class SimulatorCore
{
    play(){reader.start();};
    stop(){reader.stop();};

private:
    Reader reader;
}

Yes, all I've done is change the function names for Reader. However, the functions now are not responsible for initialising or cleaning up the reader - that responsibility is in the hands of Reader's constructor and destructor. Instead, start and stop begin and end simulation of the Reader. A single Reader instance can then enter and exit this simulation mode multiple times in its lifetime.
If you later want to extend this idea to multiple Readers, you can just change the member to:
std::vector<Reader> readers;

However, I cannot know for certain that this is what you want because I don't know the logic of your program. Hopefully this will give you some ideas though.
Again, whatever you decide to do, you should avoid using new to allocate your Readers and then also avoid using raw pointers to refer to those Readers. Use smart pointers and their corresponding make_... functions to dynamically allocate those objects.
Comment: Really good explanation, thanks. I'll use smart pointer, I think it's the best solution, and I need to practice them !
The stop button actually stop the simulation, no simulation = no reader, so I think good to delete the reader.
Comment: @MoKaT Okay, if that's your logic, then that sounds okay!
Answer: It clearly depends on how your whole program is organized, but in general, I think I would prefer the static approach, because of responsability considerations:
Suppose you have a separate class that handles serial communication. That class will send and receive messages and dispatch them to the reader class. A message may arrive at any time. The difference of the dynamic and static approaches is:

With the dynamic approach, the serial class must test if the reader actually exists before dispatching a message. Or the reader has to register and unregister itself in the serial class.
With the static approach, the reader class can decide for itself, if it is able to process the message at the moment, or not.

So I think the static approach is a bit easier and straight-forward.
However, if there is a chance that you will have to implement other, different reader classes in the future, the dynamic approach will make this extension easier, because the appropriate class can easily be instanciated at runtime.
So the dynamic approach offers more flexibility.
Comment: Ok, with the first part of this answer I tried to show an example where the "always present and valid" property of static objects are an advantage. Based on what you added here, I think I would use smart pointers, too.
Comment: Thanks, my comunication is part of my reader (as I'll maybe need multiple readers, on different serial port - USB). And I have multiple reader classes, but on another level (where I have an abstract base classe, who is my interface for instantiate different readers). Smart pointer seems perfect for this case.
Comment: I've simplified my question, but the `Reader` we speaking here is a state machine who instantiate the real reader. But it was more a functional question, than a technical one.


Class 'Yajra\DataTables\DatatablesServiceProvider' not found

Question: I've developed Laravel Project in my local computer.
I used Yajra Pakagebox for using bootstrap datatables on it.
Like this :
composer require yajra/laravel-datatables-oracle
php artisan vendor:publish
Then I pushed them all into Hosting Server but it displays errors like below.
(1/1) FatalThrowableError
Class 'Yajra\DataTables\DatatablesServiceProvider' not found
in ProviderRepository.php (line 208)
at ProviderRepository->createProvider('Yajra\\DataTables\\DatatablesServiceProvider')
in ProviderRepository.php (line 144)
at ProviderRepository->compileManifest(array('Illuminate\\Auth\\AuthServiceProvider', 'Illuminate\\Broadcasting\\BroadcastServiceProvider', 'Illuminate\\Bus\\BusServiceProvider', 'Illuminate\\Cache\\CacheServiceProvider', 'Illuminate\\Foundation\\Providers\\ConsoleSupportServiceProvider', 'Illuminate\\Cookie\\CookieServiceProvider', 'Illuminate\\Database\\DatabaseServiceProvider', 'Illuminate\\Encryption\\EncryptionServiceProvider', 'Illuminate\\Filesystem\\FilesystemServiceProvider', 'Illuminate\\Foundation\\Providers\\FoundationServiceProvider', 'Illuminate\\Hashing\\HashServiceProvider', 'Illuminate\\Mail\\MailServiceProvider', 'Illuminate\\Notifications\\NotificationServiceProvider', 'Illuminate\\Pagination\\PaginationServiceProvider', 'Illuminate\\Pipeline\\PipelineServiceProvider', 'Illuminate\\Queue\\QueueServiceProvider', 'Illuminate\\Redis\\RedisServiceProvider', 'Illuminate\\Auth\\Passwords\\PasswordResetServiceProvider', 'Illuminate\\Session\\SessionServiceProvider', 'Illuminate\\Translation\\TranslationServiceProvider', 'Illuminate\\Validation\\ValidationServiceProvider', 'Illuminate\\View\\ViewServiceProvider', 'Yajra\\DataTables\\DatatablesServiceProvider', 'Laravel\\Tinker\\TinkerServiceProvider', 'App\\Providers\\AppServiceProvider', 'App\\Providers\\AuthServiceProvider', 'App\\Providers\\EventServiceProvider', 'App\\Providers\\RouteServiceProvider'))
in ProviderRepository.php (line 61)

The important thing is I can't execute any command on Hosting Server because it is Shared Hosting Server.
I saw many articles for solving this problem but they are all using "artisan" and "composer" command.
But I can't use this command at all.
I can only upload the source code to server with FTP.
Comment: did you try to `composer-dumpautoload`, clear composer and framework cache(on local), and then reupload to server?
Comment: It seems to me that you haven't added the service provider to the `$providers` array in `config/app.php`
Answer: Depending on what version of DataTables you are using, it may be simple capitalization issue.  After version 8 you should use:
Yajra\DataTables\DataTablesServiceProvider

Before version 8 use:
Yajra\Datatables\DatatablesServiceProvider

Upgrade notes reference: https://yajrabox.com/docs/laravel-datatables/master/upgrade#namespace
Comment: I was doing a copy paste from a tutorial that used capitols for L8, but I'm working in L5.1. Thanks!
Answer: Please run below command and try:
composer update
composer dump-autoload

php artisan config:cache
php artisan cache:clear

Comment: I can't access Hosting Server with SSH.
Comment: I Can't Use "Composer" or "Artisan" because I can't access to Hosting Server with SSH. So I uploaded all source. Please Help Me.
Comment: Thanks, I think some of the dependencies cause this problem to happen, I have run all the above script and it works! *P/S: I deleted vendor folder too.
Answer: It is working for email@example.com
Yajra\DataTables\DataTablesServiceProvider::class,
'Datatables' => Yajra\DataTables\Facades\DataTables::class,

Please add this to the config/app.php file.
The first line goes under the "Package Service Providers" section
and the second line goes under the "Class Aliases" section
Answer: replace Datatables with DataTables
Answer: In the project's folder
rm -R vendor/
rm -R bootstrap/cache
mkdir bootstrap/cache
chmod -R 777 bootstrap/*

if your laravel version => 5.4
composer require yajra/laravel-datatables-oracle:"~8.0"
if your laravel version => 5.8
composer require yajra/laravel-datatables-oracle:"~9.0"
@config/app.php
'providers' => [
    ...,
    Yajra\DataTables\DataTablesServiceProvider::class,
]

'aliases' => [
    ...,
    'DataTables' => Yajra\DataTables\Facades\DataTables::class,
]

composer dumpautoload
composer install

It works for me.

Source: https://github.com/yajra/laravel-datatables[https://github.com/yajra/laravel-datatables][1]
Comment: Welcome on StackOverflow, please make sure to put code in ```code boxes```
Answer: REASON ITS NOT WORKING IS:
you installed the library. and added it in config/app.php in providers array.
don't forget to run
php artisan vendor:publish

after that.
Answer: Re install with the plugin along with the buttons plugin and now it's working.
composer require yajra/laravel-datatables-buttons:^3.0
Answer: Try below steps to resolve this issue:

Use composer show to check which version of packages you are using.
Delete all files under bootstrap/cache folder
Delete vendor folder and reinstall all packages using composer install.
Comment: Do this locally and upload through ftp?
Comment: I Can't Use "Composer" or "Artisan" because I can't access to Hosting Server with SSH. So I uploaded all source. Please Help Me
Answer: all the files you know you're changing to ftp (migrations config controller...)
and replaced local files to server with ftp
/composer.json
/composer.lock
/bootstrap/*
/storage/framework/cache/*
/storage/framework/views/*
/vendor/composer/*
/vendor/autoload.php

If the problem persists, I'm need to relay the version of the Laravel.
Tested with
php artisan --version
Laravel Framework 5.4.19

Comment: I can't use any shell command like "artisan" and "composer". Please help me.
Comment: I uploaded completely all source in my local computer.
Comment: @LeeDaniel there is no other solution if it works properly on your local computer and you need to work if you are uploading this working state to the server. And you can use call artisan commands with Artisan::call() in your temp controller. See at https://laravel.com/docs/5.5/artisan#programmatically-executing-commands
Answer: In your [config/app.php] file, edit the aliases array. Change it from
'Datatables' => Yajra\Datatables\Facades\Datatables::class

to
'Datatables' => Yajra\Datatables\DatatablesServiceProvider::class


Distance between two sets

Question: Let $D(A ,B)= \inf_{\alpha \in A,\beta \in B} d(\alpha ,\beta )$ denote the distance between sets in the power set of a given set where $d(\alpha ,\beta )$ is a metric. Prove that $D(A,B )=0$ doesn't imply $A\bigcap B\neq \varnothing$.
My attempt:
Let $D(A,B)= 0$. Then, $\inf_{\alpha \in A,\beta \in B}(d(\alpha ,\beta ))=0$. So there's $a\in A , b\in B$ such that $d(a,b)=0$, which means $a=b$. So, $A\bigcap B\neq \varnothing$.
What's the problem in my proof?
Comment: I think you mean $D(A,B)=...$. It feels like you copied the problem wrong.
Comment: Yes , Sorry for that.
Comment: You still need to edit the other instances of $D(\alpha,\beta)$ to be $D(A,B)$. Specifically, "Prove that $D(\alpha,\beta)=0$..."
Answer: There dont have to be such elements $a$ and $b$
for example take $$A = \left\{ (x,y) \,\vert\, x=0\right\}$$
and $$B = \left\{ (x,y) \,\vert\, x=1/y\right\}$$
Answer: The infimum of a set is not necessarily attained for any particular values of the set (so your claim "there is $a\in A$ and $b\in B$ such that $d(a,b)=0$" is an issue).
Hint: try to construct an explicit example of such sets, for instance in $\Bbb{R}$.
Answer: This statement "Then , $\inf_{\alpha\in A,\beta \in B}(d(\alpha,\beta))=0$. So there's $\alpha \in A, \beta \in B$." is incorrect. It would be correct if we had $\min_{\alpha\in A,\beta \in B}(d(\alpha,\beta))=0$.
Answer: Take $A=[-1,0]$ and $B={1/n:n=1,2,...}$. Then $A$ and $B$ have no intersection but their distance is 0.
Comment: It's a good example, but when answering a three-year old Question, you would be helping your Readers to highlight any significant points raised by your Answer that are not already present in the ones posted previously.

Distance between two sets


if hasclass addclass else removeclass not working

Question: This is my markup

Home

Partners

About

Contact

On page load I am trying to add class borderGap on header if homeSecLink has active class else remove borderGap
Here addClass working but removeClass not working
This is what I have done:
$(document).ready(function() {
    if ($('#homeSecLink').hasClass("active")) {
        $('#header').addClass('borderGap');
    } else {
        $('#header').removeClass('borderGap');
    }
});

Comment: define `not working` ?
Comment: Looks like this works fine ?http://jsfiddle.net/FRaTH/1/ and http://jsfiddle.net/FRaTH/2/
Comment: Please specify what exactly you expect it to do and what it does. "Not working" is not very clear.
Answer: For removeClass to work you need to remove active class
HTML

Home

Partners

About

Contact

Toggle

JavaScript
$(document).ready(function() {
    $('#toggle').click(function() {
        if ($('#homeSecLink').hasClass("active")) {
            $('#header').addClass('borderGap');
            $('#homeSecLink').removeClass('active');
        } else {
            $('#header').removeClass('borderGap');
            $('#homeSecLink').addClass('active');
        }
    });
});

Demo Link
Comment: The `active` class is perhaps added by a server-side script? Meaning this is not in the scope of what the OP wants to happen.


Why is the Galois group for a cyclotomic extension isomorphic to $Z_n^{\times}$ and not to $Z_{n-1}$?

Question: I'm struggling to understand this.  Let $\mathbb{Q}(\xi)$ be the splitting field for $x^n - 1$, so here $\xi$ is the primitive n-th root of unity.  If I consider the possible automorphisms of this field, I will get:
$$\iota \textrm{ (the identity)}, \qquad \textrm{and} \qquad \sigma_k: \xi \mapsto \xi^k, \quad2 \leq k< n.$$
I will have $n-1$ elements, same as $Z_{n-1}$.  How can it be shown that this is actually $Z_n^{\times}$ instead?  What am I missing?
Comment: Why do you have $n-1$ elements?  Can $\xi$ be mapped to any $\xi^k$ or just those $k$'s relatively prime to $n$?
Comment: Write down the composition explicitly. For an example of what can go wrong, take $n = 4$.
Comment: Every $\mathbb Q$-automorphism of $\mathbb Q(\zeta)$ is a permutation of the set $\{1,\zeta,\zeta^2,\zeta^3,\dots\}$ that fixes 1 and preserves the multiplicative structure of $\langle \zeta \rangle \cong \mathbb Z / n \mathbb Z$, as a multiplicative subgroup of $\mathbb C$. So $\mathrm{Gal}(\mathbb Q(\zeta) / \mathbb Q)$ is contained in $\mathrm{Aut}(\mathbb Z / n \mathbb Z) \cong (\mathbb Z / n \mathbb Z)^\times$. Order consideration will get you equality.
Answer: Simply, not all the maps $\sigma_k : \xi \mapsto \xi^k$ are field automorphisms. For example, consider $n = 4$; in this case, we usually denote the primitive root by $i$. Then, $\sigma_2$ maps both $\pm i$ to $-1$, so $\sigma_k$ is not an automorphism of $\Bbb Q[i]$ fixing $\Bbb Q$.
On the other hand, any automorphism must permute the roots of unity, so the map $\xi \mapsto \xi^k$ must be invertible if it is to be an automorphism, but this only holds if $k, n$ are coprime, that is, if $k \in \Bbb Z_n^{\times}$. Note that $\Bbb Z_n^{\times} \cong \Bbb Z_{n - 1}$ iff $k, n$ are coprime for all $1 \leq k < n$, that is, iff $n = 1$ or $n$ prime.
Again for $n = 4$ we have $\Bbb Z_4^{\times} = \{1, 3\}$, so the only two automorphisms are characterized by $i \mapsto i$ (the identity) and $i \mapsto i^3 = -i$ (complex conjugation).
Comment: Another reason is that the degrees are wrong. The degree of the extension gotten by adjoining an $n$-th root of unity $\zeta$ is equal to the degree of the minimal polynomial for $\zeta$, and this degree is not $n-1$, but $\varphi(n)$, the Euler number of integers $\le n$ that are relatively prime to $n$.


Porque é recomendável usar "sp" no lugar de "dp" em tamanhos do texto?

Question: Tendo em vista que quando utilizamos a unidade sp no TextView sempre aparece um warning desta forma:

Should use "sp" instead of "dp" for text sizes

Nesta resposta do SOpt mostra exatamente a diferença entre as unidades de medida: Dúvida sobre px, dp, dip and sp no Android?
sp

Scale-independent Pixels - Idem ao dp, mas também considera o tamanho
  da fonte que o usuário está utilizando. É recomendado que use essa
  unidade quando especificar o tamanho de uma fonte, para que esta seja
  automaticamente ajustada conforme as preferências da tela do usuário.

dip ou dp

Density-independent Pixels - Essa unidade é relativa à resolução da
  tela. Por exemplo se a resolução da tela é de 160 dpi, significa que
  um dp representa 1 pixel em um total de 160. USO: aconselho ao invés
  de usar o px sempre use o dp.

A questão da recomendação é em relação ao tamanho que o usuário define sua fonte em ACESSIBILIDADE nas configurações do dispositivo? Qual o porquê da recomendação? Porque é recomendável usar "sp" no lugar de "dp" em tamanhos do texto?
Comment: Não entendi qual é a sua dúvida.
Comment: @ramaral A duvida é: Porque é recomendável usar "sp" no lugar de "dp" em tamanhos do texto?
Answer: A recomendação decorre do pressuposto que o utilizador quando altera o tamanho do texto na definições de acessibilidade espera que ela sejam repercutida em todos os textos de todas as aplicações.
Para que isso aconteça o tamanho da fonte dos textos terá de ser definido com a unidade sp.
O tamanho do texto não só se ajustará à densidade de pixeis da tela mas também levará em conta a definição escolhida nas opções de Acessibilidade.


How to decide threshold values for AUC?

Question: With respect to the pROC package for R(https://rdrr.io/cran/pROC/man/ggroc.html).
library(pROC)
# Create a basic roc object
data(aSAH)
rocobj <- roc(aSAH$outcome, aSAH$s100b)
roc_obj$thresholds
 [1]  -Inf  1.50  2.50  3.50  4.50  5.50  6.50
 [8]  7.50  8.50  9.50 10.75 12.25 13.50 14.50
[15] 15.50 16.50 17.50 18.50 19.50   Inf

roc_obj$sensitivities
  [1] 0.64919355 0.64919355 0.64919355 0.64919355
  [5] 0.64919355 0.64919355 0.64919355 0.64658635
  [9] 0.64658635 0.64658635 0.64658635 0.64658635
 [13] 0.64658635 0.64658635 0.64658635 0.64658635
 [17] 0.64400000 0.64400000 0.64400000 0.64400000
 [21] 0.64143426 0.64143426 0.63888889 0.63888889
 [25] 0.63888889 0.63492063 0.63492063 0.63492063
 [29] 0.63492063 0.63095238 0.62845850 0.62450593
 [33] 0.62055336 0.61568627 0.61176471 0.60784314
 [37] 0.60784314 0.60000000 0.60000000 0.59765625
 [41] 0.59375000 0.58593750 0.58203125 0.57421875
 [45] 0.57421875 0.56640625 0.56201550 0.55038760
 [49] 0.53488372 0.51162791 0.50000000 0.49615385
 [53] 0.48659004 0.47892720 0.46360153 0.45593870
 [57] 0.45210728 0.44274809 0.42585551 0.41825095
 [61] 0.41064639 0.39923954 0.39015152 0.38257576
 [65] 0.37735849 0.36981132 0.36226415 0.35471698
 [69] 0.34339623 0.34339623 0.33962264 0.32830189
 [73] 0.31698113 0.29811321 0.29433962 0.28679245
 [77] 0.27924528 0.27067669 0.25563910 0.24436090
 [81] 0.23684211 0.23684211 0.22932331 0.22556391
 [85] 0.21428571 0.19172932 0.18421053 0.17669173
 [89] 0.16541353 0.13909774 0.13909774 0.12781955
 [93] 0.12030075 0.10526316 0.07518797 0.06390977
 [97] 0.06015038 0.05263158 0.04135338 0.01879699
[101] 0.00000000
> roc_obj$specificities
  [1] 0.9179612 0.9205811 0.9237084 0.9253372
  [5] 0.9287434 0.9302885 0.9337176 0.9347722
  [9] 0.9362722 0.9377395 0.9388730 0.9408679
 [13] 0.9424358 0.9448931 0.9469697 0.9498818
 [17] 0.9522910 0.9532357 0.9552098 0.9562353
 [21] 0.9581570 0.9586854 0.9615565 0.9620431
 [25] 0.9639513 0.9654206 0.9664492 0.9669306
 [29] 0.9674570 0.9679517 0.9679517 0.9684747
 [33] 0.9694019 0.9694019 0.9699074 0.9713228
 [37] 0.9727357 0.9736842 0.9737206 0.9737569
 [41] 0.9755985 0.9770009 0.9775126 0.9780119
 [45] 0.9794050 0.9812357 0.9812443 0.9821674
 [49] 0.9826325 0.9826484 0.9831358 0.9840692
 [53] 0.9849932 0.9854678 0.9859347 0.9864069
 [57] 0.9873360 0.9886980 0.9896163 0.9896256
 [61] 0.9900812 0.9900856 0.9905405 0.9905405
 [65] 0.9909950 0.9914491 0.9918992 0.9932524
 [69] 0.9937022 0.9937079 0.9937135 0.9946164
 [73] 0.9955137 0.9964109 0.9968596 0.9968610
 [77] 0.9973118 0.9973154 0.9973166 0.9977639
 [81] 0.9977639 0.9982119 0.9982127 0.9982127
 [85] 0.9982127 0.9982143 0.9986613 0.9986613
 [89] 0.9986613 0.9991079 0.9991079 0.9991083
 [93] 0.9991083 0.9991087 0.9991095 0.9995550
 [97] 1.0000000 1.0000000 1.0000000 1.0000000
[101] 1.0000000

Each point on the ROC curve represents a sensitivity/specificity pair corresponding to a particular decision threshold. That means if the output probability value is more than the threshold than the class associated with it become the called class. For example, if the threshold is set to 0.5 and the output probability of a case being diabetic is 0.75 then the case is considered as a disease.
But when you look at the thresholds in the above examples then it ranges from -inf to +inf including values greater than 1. How can thresholds be greater than 1 when the probability values range from 0 to 1?
Also, I am not able to connect the meaning of -inf and +inf, will it behave the same as max and min-cut numbers of probability like 0 and 1.
Answer:
But when you look at the thresholds in the above examples then it ranges from -inf to +inf including values greater than 1. How can thresholds be greater than 1 when the probability values range from 0 to 1?

This appears to stem from a typo in your code.
rocobj <- roc(aSAH$outcome, aSAH$s100b)
roc_obj$thresholds

Note the underscore in roc_obj that is not present in rocobj.
Errors like this are why it's best practice to clear your workspace or start a new session before attempting to construct an example.

But when you look at the thresholds in the above examples then it ranges from -inf to +inf including values greater than 1. How can thresholds be greater than 1 when the probability values range from 0 to 1?

First, the data you're using do not vary between (0,1), so it's not a probability.
summary(aSAH$s100b)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  0.030   0.090   0.140   0.247   0.330   2.070

This is irrelevant, though, because ROC curves don't assume that  inputs are probabilities. ROC curves just care about ranking the inputs; as long as the inputs can be ordered, it's fine.
If you print rocobj$thresholds instead of roc_obj$thresholds, you'll see that it has  values in the range of the data except for the endpoints -Inf and Inf. The thresholds at the endpoints are -Inf and Inf because ROC curves are defined as monotonic increasing curves from (0,0) to (1,1); you need to have thresholds outside of the range of your data to achieve (0,0) and (1,1); hence -Inf and Inf are used. The interpretation of operating points at (0,0) and (1,1) is no different, because these correspond to the TPR and FPR of naïve models which either never raise the alarm or always raise the alarm.
rocobj$thresholds
 [1]  -Inf 0.035 0.045 0.055 0.065 0.075 0.085 0.095 0.105 0.115 0.125 0.135
[13] 0.145 0.155 0.165 0.175 0.185 0.205 0.225 0.235 0.245 0.255 0.265 0.275
[25] 0.290 0.310 0.325 0.335 0.345 0.365 0.395 0.420 0.435 0.445 0.455 0.465
[37] 0.475 0.485 0.495 0.510 0.540 0.570 0.640 0.705 0.725 0.755 0.795 0.840
[49] 0.910 1.515   Inf

Comment: If you never detect, you have a TPR of 0 and an FPR of zero by definition. Likewise, if you always detect, you'll always have a TPR of 1 and an FPR of 1.
Comment: thanking for pointing out my mistake. Can you please elaborate more about the infinity thing. So is it like a manual addition to the thresholds, despite whatever values you take. Which is basically for sensitivity and specificity (1,0) and (0,1) at respective infinite thresholds.
Comment: Imagine that you have a model that produces **finite** outputs; your model produces outputs in $(0,1)$, which is a special case of producing finite outputs. You have a threshold of $-\infty$. What's the TPR and FPR at this threshold? Will your model ever make a prediction that's less than $-\infty$? What's the TPR and FPR for a model with a threshold at $\infty$?
Comment: @Sycorax Does it mean when there is -inf the sensitivity will always be 1 and +Inf the sensitivity will be  0 and similarly vice versa for specificity. So in cases where you are manually finding sensitivity and specificity based on various thresholds, you should consider + inf and -inf threshold values also?
Comment: thanks for the clarification.

How to decide threshold values for AUC?


How can i pragmatically fill a field collection when creating a new node?

Question: I'm creating nodes pragmatically but I don't know how to fill field_collection fields. Most of the examples i've seen have field_collections being updated from existing nodes and i'm not entirely certain they can also be used when creating new nodes.
function createNode($Obj){
  global $user;
  $node = entity_create('node', array(
    'type' => 'event',
    'uid' => 1,
    'status' => 1,
    'comment' => 0,
    'promote' => 0,
  ));
  $body = "
" . (string)$Obj->BuildingCode;
  $body .= " " . (string)$Obj->RoomNumber . "
";
  $body .= "
" . (string)$Obj->Description . "
";

  $entity = entity_metadata_wrapper('node', $node);
  $entity->language(LANGUAGE_NONE);
  $entity->title = (string)$Obj->ActivityName;
  $entity->body->set(array(
    'value' => $body,
    'summary' => (string)$Obj->Description,
    'format' => 'full_html',
  ));
  $entity->field_activityid = (string)$Obj->ActivityId;
  $entity->field_location_room = (string)$Obj->RoomNumber;
  $entity->field_location_building = (string)$Obj->BuildingCode;
  $entity->field_location_address->set(array(
    'country' => '',
    'thoroughfare' => '',
    'premise' => '',
    'locality' => '',
    'administrative_area' => '',
    'postal_code' => '',
  ));
  // $enitity->field_event_organizer->set(array(
  //   'field_event_presenter_name' => (string)$Obj->ContactFirstName,
  //   'field_event_presenter_title' => "TEST",
  //   'field_event_presenter_organizati' => "ORG",
  // ));

  $values = array(
    'field_name' => 'field_event_organizer',
    'field_event_presenter_name' => array(
      LANGUAGE_NONE => array(array('value' => (string)$Obj->ContactFirstName)),
    ),
    'field_event_presenter_title' => array(
      LANGUAGE_NONE => array(array('value' => "PTITLE")),
    ),
    'field_event_presenter_organizati' => array(
      LANGUAGE_NONE => array(array('value' => "PORGANI")),
    ),
  );

  $entity->save();
}

EDIT:
main collection field:

sub fields:

I tried to add a modified version the code below in hopes it would work for me:
$field_collection_item = entity_create('field_collection_item', array(
    'field_name' => 'field_event_organizer'
  ));
  $field_collection_item->setHostEntity('node', $node);
  $field_collection_item->field_event_organizer_name = "PROG NAME";
  $field_collection_item->save();

  $entity->field_event_organizer = $field_collection_item->item_id;

However i got an error
EntityMetadataWrapperException: Unknown data property propertyInfo. in EntityStructureWrapper->getPropertyInfo() (line 354 of /Applications/MAMP/htdocs/sites/all/modules/contrib/entity/includes/entity.wrapper.inc).
EDIT:
Re-tweaked the answer given to me by SN_26 and it manages to create the node with the field_collection filled in but I get the following error message:
The website encountered an unexpected error. Please try again later.
Status message Registration settings have been saved.
Error messageEntityMetadataWrapperException: There can be only numerical keyed items in a list. in EntityListWrapper->get() (line 1038 of /Applications/MAMP/htdocs/sites/all/modules/contrib/entity/includes/entity.wrapper.inc).

full updated code:
function createNode($Obj){
  global $user;
  var_dump($Obj);
  $node = entity_create('node', array(
    'type' => 'event',
    'uid' => 1,
    'status' => 1,
    'comment' => 0,
    'promote' => 0,
  ));
  $body = "
" . (string)$Obj->BuildingCode;
  $body .= " " . (string)$Obj->RoomNumber . "
";
  $body .= "
" . (string)$Obj->Description . "
";

  $entity = entity_metadata_wrapper('node', $node);
  $entity->language(LANGUAGE_NONE);
  $entity->title = (string)$Obj->ActivityName;
  $entity->body->set(array(
    'value' => $body,
    'summary' => (string)$Obj->Description,
    'format' => 'full_html',
  ));
  $entity->field_activityid = (string)$Obj->ActivityId;
  $entity->field_location_room = (string)$Obj->RoomNumber;
  $entity->field_location_building = (string)$Obj->BuildingCode;
  $entity->field_location_address->set(array(
    'country' => '',
    'thoroughfare' => '',
    'premise' => '',
    'locality' => '',
    'administrative_area' => '',
    'postal_code' => '',
  ));
  $entity->field_event_date[0]->set(array(
    'value' => _unix_date_time($Obj->StartDate, $Obj->StartMinute),//Y-m-d H:i:s
    'value2' => _unix_date_time($Obj->EndDate, $Obj->EndMinute),
  ));

  $field_collection_item = entity_create('field_collection_item', array(
    'field_name' => 'field_event_organizer'
  ));
  $field_collection_item->setHostEntity('node', $node);
  $field_collection_item->field_event_organizer_name[LANGUAGE_NONE][0]['value'] = "PROG NAME";
  $field_collection_item->save();

  $entity->field_event_organizer[LANGUAGE_NONE][0]['value'] = $field_collection_item->item_id;

  $entity->save();
}

Answer: This should do the trick to insert a new field collection item:
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_some_collection'));
$field_collection_item->setHostEntity('node', $entity);
$field_collection_item->field_my_field_in_the_fc[LANGUAGE_NONE][0]['value'] = 'hello';
$field_collection_item->save();

$entity->field_some_collection[LANGUAGE_NONE][]['value'] = $field_collection_item->item_id;

Comment: I'm not exactly loading a node. I'm creating a node and filling the fields for a node type that was made using the Drupal UI.
Comment: See above for the edited version.
Comment: Sorry for the delay. This didn't work. The last thing i posted semi worked, it can create a node with the field collection but it also crashes. The code you gave me gives me the following error: `EntityMetadataWrapperException: There can be only numerical keyed items in a list. in EntityListWrapper->get() `
Answer: After much trial and error I found that this works by NOT assigning the $field_collection_item to the entity was the correct way to do this.
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_event_organizer'));
$field_collection_item->setHostEntity('node', $node);
$field_collection_item->field_event_organizer_name[LANGUAGE_NONE][] = array('value' => $fullName);
$field_collection_item->save();


Eigenvalue Sums

Question: Problem 1:
Let A and B be any 2 × 2 matrices.
Compute the sum of the the eigenvalues of the matrix:
C = AB − BA
Hint: your answer should not depend on A or B.
Comment: **Hint:** What function do you know of that gives you the sum of the eigenvalues in a matrix?  What properties does this function have?
Answer: The trace of a matrix is the sum of its eigenvalues.
Plus,  $$tr(AB) = tr(BA)$$
and the trace is a linear operator.
Hence the sum of the eigenvalues of $C$ is equal to the trace of $C$ that is
$$tr(C) = tr(AB) - tr(BA) = 0$$

Eigenvalue Sums


Pure algebraic solution to a bounded area calculus problem?

Question: Given a region $\sigma$ in the Cartesian plane is bounded by the lines
$$x = 1,\>\>\> x = 3, \>\>\>y = m,\>\>\> y = mx + 2$$
With $m > 0$. What does $m$ need to be for the region $\sigma$ to have an area of $9$.
The calculus solution is $a = 1, b = 3$ where
$$\int_a^b dx~(mx - m + 2) = 2m + 4$$
Solving for $m$ yields, $\frac{5}{2}$.
I am interested in how to solve this algebraically, considering that these are lines not curves (yes, I know a line is an instance of a curve but I do not know how else to describe my problem) is it possible?
Comment: Hint:  the region in question is a trapezoid, so you can work out its area via geometry.
Answer: At first i would compute where the intersection point of $$y=mx+2$$ and $$y=m$$ is located:
$$y=mx+2=m$$ so we get $$x=\frac{m-2}{m}$$ and since $m>0$ we get
$$x=\frac{m-2}{m}<1$$ and this is equivalent to $$-2<0$$
Answer: The region is a trapezoid with the two base lengths given by
$$y(1)-m = 2, \>\>\> y(3)-m = 2m+2$$
and the height of the trapezoid is $3-1=2$. Thus, its area
$$\frac 12 \times (2+2m+2)\times 2 = 9$$
which has the solution
$$m=\frac 52$$
Comment: Thank you, I understand. How did you know the region is a trapezoid was it from the equations or did you graph it? I graphed it using desmos and had no clue it was a trapezoid. Silly me, has only ever known about right trapezoids.
Comment: because it is enclosed by a horizontal line $y=m$ and a line with an angle $y=mx+2$.


Samba server: Delay in changed LDAP group membership

Question: After switching from local user-groups to LDAP group memberships on our system, changing the memberships stopped being recognized immediately after performing the modification. Instead, we experience a delay of several minutes before the samba server applies the updated memberships.
Installed is a samba server Version 4.5.16-Debian and OpenLDAP: slapd  (May 23 2018 04:25:19). The relevant section of the smb.conf configuration is:
passdb backend = ldapsam:ldap://localhost
read only = yes
ldap suffix = dc=example,dc=com
ldap user suffix = ou=people
ldap admin dn = cn=admuser,ou=admgroup,dc=example,dc=com
ldap ssl = no
ldap passwd sync = yes

netbios name = EXAMPLE
netbios aliases = EXAMPLE2
obey pam restrictions = Yes

Answer: As per this response of the samba mailing list, nscd caches the entries, which is typically installed alongside if LDAP is used for PAM/NSS as well:
# apt-cache show libnss-ldap |grep ^Recommends
Recommends: nscd, libpam-ldap

To trigger the modifications to be recognised immediately, the corresponding cache table can be invalidated via:
nscd --invalidate group


How to use Selenium.click

Question: So i was working on getting some file from https://www.pbpstats.com/totals/nba/player. Im using selenium with chrome webdriver. I cant quite figure out how to click on the "get stats". I can do this manually but would like to do it through the html and selenium.
Have tried this:
browser = webdriver.Chrome()
browser.get('https://www.pbpstats.com/totals/nba/player')
element = browser.find_elements_by_tag_name('button')
element.click()

But nothing happens. Im not sure how understand the output from find_elements_by_tag_name. Gets something like "this selenium.webdriver.remote.webelement.WebElement (session="14bacd9bab4b484952ba872ea0373663", element="4ef4e9da-b193-46a8-8209-265b8bef3f05"" (it differs in after the equal signs)
Answer: Selenium is a bit over kill here since the data is returned form the api. Just grab the data from there. You'll also get all the data and not have to go through each dropdown  for Scoring, Assists, Rebounds, etc. (all 248 columns)
If you want the per game and/or per 100 possession, then it's just a matter of dividing the numerical int columns by the 'GP' or 'Possessions' * 100 columns once you have the dataframe.
import requests
import pandas as pd

url = 'https://api.pbpstats.com/get-totals/nba'
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.36'}
payload = {
'Season': '2020-21',
'SeasonType': 'Regular+Season',
'Type': 'Player'}

jsonData = requests.get(url, headers=headers, params=payload).json()
df = pd.DataFrame(jsonData['multi_row_table_data'])

df.to_csv('pbpstats_export.csv', index=False)

The data will come with the column in alpha order, so if you want to move them before writing to file, you can put which columns you want to come first. I just choose the name and team since those typically are the first 2 columns in a sports table:
# If you want to reorder the first few columns. Otherwise columns are i alpha order
reorder = ['Name','TeamAbbreviation']
for col in reversed(reorder):
    col = df.pop(col)
    df.insert(0, col.name, col)

Ouput:
print(df)
                  Name TeamAbbreviation  2pt And 1 Free Throw Trips  \
0        Julius Randle              NYK                        35.0
1         Nikola Jokic              DEN                        24.0
2          Buddy Hield              SAC                         3.0
3     Domantas Sabonis              IND                        32.0
4           RJ Barrett              NYK                        21.0
..                 ...              ...                         ...
495      Jontay Porter              MEM                         NaN
496  Ty-Shon Alexander              PHX                         NaN
497      Rayjon Tucker              PHI                         NaN
498     Brian Bowen II              IND                         1.0
499       Jared Harper              NYK                         NaN

     Arc3Accuracy  Arc3Assists  ...  BlockedCorner3  Period3Fouls5Minutes  \
0        0.408284         90.0  ...             NaN                   NaN
1        0.422360         87.0  ...             NaN                   NaN
2        0.365796         22.0  ...             NaN                   NaN
3        0.281818        101.0  ...             NaN                   NaN
4        0.318681         32.0  ...             NaN                   NaN
..            ...          ...  ...             ...                   ...
495      0.500000          NaN  ...             NaN                   NaN
496           NaN          NaN  ...             NaN                   NaN
497      1.000000          NaN  ...             NaN                   NaN
498           NaN          NaN  ...             NaN                   NaN
499           NaN          NaN  ...             NaN                   NaN

     HeaveMakes  Period1Fouls3Minutes  Period2Fouls4Minutes
0           NaN                   NaN                   NaN
1           NaN                   NaN                   NaN
2           NaN                   NaN                   NaN
3           NaN                   NaN                   NaN
4           NaN                   NaN                   NaN
..          ...                   ...                   ...
495         NaN                   NaN                   NaN
496         NaN                   NaN                   NaN
497         NaN                   NaN                   NaN
498         NaN                   NaN                   NaN
499         NaN                   NaN                   NaN

[500 rows x 248 columns]

Comment: Oh i dont quite know what api is. My plan was to get the stats and click export stats in the bottom of the page and then do it for them all. I dont know if that is very impratical compared to using api.
Comment: Well, both ways will get the job done. Sort of depends on what you're trying to do. sort of like if you wanted to drive in a nail. Both a sledge hammer and regular hammer will do it, but one may be a better choice given the options. In this case, the API is more efficient way to do it and will be more robust (it's not reliant on the html structure). I also added the part to write to file, which is essentially what the export to csv is.
Comment: Can see i work more effektive but how do u know how write it up in python?
Comment: What do you mean? Not sure what you're asking here.
Comment: If you mean how I knew about the api. If you go to Dev Tools on the browser, and go to Network -> XHR, you can see the request made. Just a matter of pulling out the url from there and looking at the Preview tab to see what's returned.
Answer: Try that out, should help:
import time

browser = webdriver.Chrome()
browser.get('https://www.pbpstats.com/totals/nba/player')
time.sleep(4)
element = browser.find_element_by_xpath("//button[text()='Get Stats']")
element.click()

or you can use explicitly wait, like that:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

timeout = 30
browser = webdriver.Chrome()
browser.get('https://www.pbpstats.com/totals/nba/player')
myElem = WebDriverWait(browser, timeout).until(EC.element_to_be_clickable((By.XPATH, "//button[text()='Get Stats']")))
myElem.click()

Comment: Ahh okay worked with element*. Just a question. Tried something like that based on previous answer. How do u know it is "text()=get stats" - in the html it does not say text?
Comment: hmm okay just examples i saw where it was explicit what it was like id=somthing. The data-v-... is that of any importance?
Comment: Not sure to confirm where :/
Comment: the last part with timeout does not seem to work tho.
Comment: @Younglolk it works 100%, just double check it, what error did you have?
Comment: @Younglolk it's up to you what wait way using, I suggested both, last one is more flexible and right, but complicated.
Answer: you can perform a click like that :
browser = webdriver.Chrome()
browser.get('https://www.pbpstats.com/totals/nba/player')
time.sleep(5)
element = browser.find_elements_by_xpath('//*
 [@id="totals"]/main/div[3]/div/button[1]')[0]
element.click()

Comment: That won't work as you're using `find_elements_by_tag_name` (note the s in elements) which returns a list.
Comment: Ahh my bad. I have tried element.click but there doesnt happend anything. The webdriver do not update.
Comment: Thanks for it - it helped.
Comment: if it worked then u should accept it as an answer .

How to use Selenium.click


Can't connect to ESXi 5.x with vSphere Client but I can access the ESXi over SSH

Question: Can't connect to ESXi 5.x with vSphere Client but I can access the ESXi over SSH.
I'm not use vCenter, i trying connect directly. When i run services.sh restart then all is ok, and i can connect. After 1-2 days this problem is back, and this is repeated regularly.
Comment: What specific version and build number of ESXi are you running? 5.x could mean 5.1 or 5.5.
Answer: I'd suggest upgrading your ESXi to a newer patch revision. Seeing as you're not using vSphere, you probably haven't upgraded to newer patch revisions.
It's easy to do. See if it resolves this issue.
Edit:
You're using VERY OLD builds of VMware. See this patch and revision chart. We can't even begin to troubleshoot your issues until you take care of your systems. 5.0.0 probably shouldn't even be used anymore, but 2000308 is the current build of 5.0.0. The 469512 build you're using is from 2011 and has been updated SEVENTEEN times...
Same thing for your 5.1.0 installation. The current revision for 5.1.0 is 2000251 instead of the 799733 you have.
For 5.5, you're using an unpatched build 1331820 - The current build is 1892794.
There are many bugs and issues that have been resolved over the years. So updating is a good thing to do.
Obviously <code>/sbin/services.sh restart</code> works for the moment, but I don't know that it's worth digging deeper when we know that the versions are so out-of-date.
Comment: The problem appears to ESXi 5.1, 5.1U1, 5.5. It's too much of a coincidence that the update was required.

Servers will continue to function for a long time, and the problem appears only recently.
Comment: Please provide the build number of your ESXi installation.
Comment: 5.0.0 469512  ||  5.1.0 799733 || 5.5.0 1331820
Comment: @Mateusz See my edit above.
Comment: Ok, i try :) This is big challenge, because we have 50 ESXi servers :)


Rob spent 25% more time on his research project than he had planned. He spent an extra h hours on the project.Khan Academy

Question: The explanation says that he planned to spend $($h$/$25%$)$(100%) hours on the research project. How did they come up with the expression and i don't understand why the h is divided by the 25%. I do understand how it's manipulated to get to 5h but i just don't get how they came up with it in the first place
Comment: The number of hours Rob *actually* spent is in fact $5h$, not as the suggestion would imply $4h$.
Answer: Let $H$ be the hours Bob planned to spend. Then $$h=\frac14 H.$$
Now the total amount of time spent is $$T=H+h=4h +h=5h.$$
With percents written
$$T=\frac{h}{25\,\%}+h.$$


How to read a large number of text files in Python software and convert data into a sample file?

Question: I receive information from an application. I have given a very small example as follows.
import pandas as  pd
df = [{'etelat':{'name' : 'sajjad1' , 'last_name' : 'esma1' },

       'class_id':{'id':101 , 'name_os' : 'win'}},

       {'etelat':{'name' : 'sajjad2' , 'last_name' : 'esma2' },

       'class_id':{'id':102 , 'name_os' : 'mac'}}]
df
type(df)
# Import pandas library
import pandas as pd
# initialize list of lists
data = [['sajjad1', 'esma1',101,'win'], ['sajjad2', 'esma2',102,'mac'] ]
# Create the pandas DataFrame
df_new = pd.DataFrame(data, columns = ['etelat_name', 'etelat_last_name','class_id_id', 'class_id_name_os'])
# print dataframe.
df

1- In this case, it answers correctly, but if we want the data, which is in the form of text, I will have a problem.
2- If the data is in a folder and the number of text files is 50, if we want to call the desire of the files with a code. How is this code?
enter image description here
Comment: Do you want to read the `data` (list of list ) and print it as a pandas df? or do you just want to read from a txt file and print each line?
Comment: @dariyoush I want to read all the text data. Then I convert that read file to dataform.
Answer: If you have your list of lists in a file like the following:
example.txt
[['sajjad1', 'esma1',101,'win'], ['sajjad2', 'esma2',102,'mac'],
['sajjad3', 'esma1',103,'win'], ['sajjad4', 'esma2',104,'mac'] ]

you can read the file and convert it to a pandas dataframe:
import pandas as pd

columns = ['etelat_name', 'etelat_last_name','class_id_id', 'class_id_name_os']
with open('example.txt', 'rb') as file:
    data = eval(file.read())

df = pd.DataFrame(data=data, columns=columns)
print(df)

output:
  etelat_name etelat_last_name  class_id_id class_id_name_os
0     sajjad1            esma1          101              win
1     sajjad2            esma2          102              mac
2     sajjad3            esma1          103              win
3     sajjad4            esma2          104              mac

Edit:
you can load it and convert it to utf-8 and then you get a list of dictionaries that you can deal with.
import ast
lst = []
with open('example.txt', 'rb') as file:
    content = file.readlines()
for item in content:
    temp = item.decode('UTF-8')
    lst.append(ast.literal_eval(temp))
print(last)

output:
[({'etelat': {'name': 'sajjad1', 'last_name': 'esma1'}, 'class_id': {'id': 101, 'name_os': 'win'}},), ({'etelat': {'name': 'sajjad2', 'last_name': 'esma2'}, 'class_id': {'id': 102, 'name_os': 'mac'}},)]

tested file with:
{'etelat':{'name' : 'sajjad1' , 'last_name' : 'esma1' },'class_id':{'id':101 , 'name_os' : 'win'}},
{'etelat':{'name' : 'sajjad2' , 'last_name' : 'esma2' },'class_id':{'id':102 , 'name_os' : 'mac'}},

Comment: My problem is that I can not read as a string. I feel the file is json. The data was received from the twitter search package. Sample data :
    https://drive.google.com/file/d/1QdhQk34A12K-lA8jsShlENtzhdsZ2RmF/view


Unable to run python script from PHP

Question: This particular question has been asked so many times with great suggestions but the sudden abandonment by Askers doesn't really help as they never bothered to return to tell what worked (assuming it must have worked eventually)
I'm trying to run a python script from PHP but haven't been able to. Environment: PHP 7.3, Python 3.8, CentOS 7, Apache 2.4, Bluehost VPS.

Tried both exec and shell_exec

apachectl -S reveals apache server is running as nobody:nobody

Added nobody in sudoer using nobody ALL=(ALL) NOPASSWD: /etc/bin/python3

Added Execute permissions to the Python script and changed the owner
to nobody (same as apache) ls -l testing.py gives -rwxr-xr-x 1 nobody nobody

The Python script on its own runs fine from the shell.

Here's my code:
<?php
error_reporting(E_ALL);
$command = 'python3 /home/uploads/testing.py';
$command = escapeshellcmd($command);
$shelloutput = exec($command,$output, $ret_code);
echo "
";
echo $shelloutput;
echo $output;
echo $ret_code;
echo "
";
?>

The python script:
#!/usr/bin/env python3
import sys
print("Hello")
sys.exit(8)

When I run the PHP file from the browser, I get absolutely nothing.
I would appreciate any help in getting this resolved.
Comment: Your code works for me. Check your httpd settings. increase the log verbosity if needed.
Comment: You don't need a sudo configuration; you don't need to set the .py file to be executable, since your provide it as a parameter to the python3 binary; python3 can be executed by every user.
Comment: `/etc/bin/python3`? are you sure of that filename?
Comment: @DanilaVershinin Good catch. `whereis python3' gives 'python3: /usr/bin/python3` Still didn't work
Comment: @GeraldSchneider Thank you for editing the question, looks perfect now. What should I be looking at in apache config file to run a python from shell? I checked apache error_log file, nothing there. How to increase log verbosity? I thought I already have the max.
Comment: @GeraldSchneider The issue seems to have persisted but in a different way. PHP is able to run scripts from my server, except for the directory which is running a Wordpress site. I looked everywhere to see what could be overriding default php.ini directives but couldn't. Any ideas?
Answer: Found that the issue was with php.ini file, removed disable_functions="" directive and the Python script worked.
As Gerald mentioned in the comments, I did not need to add anything to the sudoers file or change file permissions/users other than the standard +x permission attribute (or 0755)
Comment: Something VERY wrong if enabling execute permissions on the script changed the behaviour, and there are lots of other reasons why this can fail (in case anyone else is confused by your fix not resolving their issue). Use the full path to the python interpreter, check your PHP is not subject to chroot or MAC (apparmor, selinux) constraints, has execute permissions on the interpreter and can read the directory tree and script file.

Unable to run python script from PHP