Como especificar uma class CSS para textos que quebram linha em um elemento HTML?

Question: Na maioria das vezes que trabalho com textos dentro de elementos HTML, utilizo um recurso em CSS chamado line-height. Suponhamos que a altura de um elemento específico seja de 50px, logo, coloco o line-height com 50px também para que o texto fique centralizado. Pois bem, quando esse texto quebra linha, ou seja, acaba sendo maior que o tamanho do meu elemento, não fica uma coisa muito legal. Existe uma forma em CSS que verifique se meu texto quebrou linha para que eu possa adicionar uma propriedade line-height diferente?
Exemplo de um texto em que fica centralizado corretamente, contendo pouco texto:

Agora, um exemplo de como o texto fica quando é um pouco maior, ou seja, que ultrapassa o limite de meu elemento:

Percebam que na imagem acima, o texto caiu e manteve o tamanho do line-height. Isso é ruim pois acaba ultrapassando o limite de altura de meu elemento.
Agora, como gostaria que ficasse quando o texto cai pra linha debaixo:

Seria esse o problema, possibilidades com javascript não são descartadas também caso alguém tenha uma solução bacana.
Comment: Imagino que não... imagina, se isso fosse possível você poderia acabar entrando em loop de CSS.
Comment: Paulo, sua pergunta está confusa. Organize as informações, coloque exemplos práticos e deixe o seu objetivo mais claro.
Comment: Eu achei sua pergunta direta, você quer usar uma condicional dentro do CSS. Lendo isso aqui você vai encontrar sua resposta -> http://dev.w3.org/csswg/css-conditional/
Comment: Reformulei minha pergunta com algumas imagens demonstrativas Caio. Talvez agora melhore o entendimento.
Comment: Acho melhor você usar [outra](http://pt.stackoverflow.com/questions/141/como-centralizar-verticalmente-o-conteudo-de-um-elemento) [técnica](http://pt.stackoverflow.com/questions/2817/melhor-forma-de-centralizar-um-elemento-vertical-e-horizontalmente) para centralizar o texto verticalmente.
Comment: Com certeza não precisa JavaScript. Existem MUITAS alternativas para centralização vertical. Muitas mesmo. Existem até fãs de `display: table`!
Comment: O uso de display:table; no elemento pai, e uso das propriedades vertical-align:middle; e display:table-cell; no elemento que contém o texto, seria uma boa prática?
Answer: No seu CSS você vai precisar declarar altura, display como table-cell e vertical-align middle.
.seletor {
  display: table-cell;
  height: 100px;
  vertical-align: middle;
}

Veja o exemplo: http://jsfiddle.net/QPdLx/1/
Answer: Sugestão:

Diminua o line-heightdo texto, deixando na medida da tua última imagem, onde o texto com quebra de linha aparece bonito.
Envolva esse texto num div ou outro elemento, e aplique vertical-align: middle ao mesmo. (Talvez precise um display: inline-block.)
No elemento que envolve tudo (a data, o texto, o padding), aí sim, atribua um line-height da mesma altura do height para que o alinhamento vertical seja aplicado.


Obter dados do tipo String de um documento CSV

Question: Tenho um documento CSV (Excel) com e-mails válidos e inválidos. E eu queria pegar os valores dos campos em forma de string, mas o seguinte código dá o retorno mostrado mais abaixo:
import csv
import re

ifile  = open('ead.csv', "r")
read = csv.reader(ifile, delimiter=' ', quotechar='|')
csvArray = []

for row in read :
    csvArray.append(row)
print(csvArray[0:10])

Retorno:
[['email@example.com'], ['firstname.lastname@example.com'], ['email@example.com'], ['firstname.lastname@example.com'], ['firstname.lastname@example.com'], ['firstname.lastname@example.com'], ['email@example.com'], ['firstname.lastname@example.com'], ['email@example.com'], ['email@example.com']]
>>>

Mas eu preciso que os resultados apareçam apenas 'email@example.com' sem o '[]', para que eu possa validá-los.
Comment: Podes só `', '.join(ifile.read().splitlines())`, ficas com, "email1, email2, email3, ..."
Answer: Quando você lê um arquivo CSV, o objeto row em:
for row in read: ...

será uma lista com todas as colunas encontradas. Como seu arquivo possui apenas uma coluna com o e-mail, o valor de row será uma lista com um elemento. Ao fazer csvArray.append(row) você adiciona toda a lista em csvArray e não apenas o valor do e-mail. Sabendo que sempre será a primeira coluna o e-mail, poderia fazer:
import csv
import re

ifile  = open('ead.csv', "r")
read = csv.reader(ifile, delimiter=' ', quotechar='|')
csvArray = []

for row in read :
    csvArray.append(row[0])
print(csvArray[0:10])

Veja funcionando no Repl.it
Mas uma solução mais pythonica para o seu problema seria:
import csv

def get_emails_from_csv(filename):
    with open(filename) as stream:
        reader = csv.reader(stream, delimiter=' ', quotechar='|')
        for line in reader:
            yield line[0]

emails = get_emails_from_csv('ead.csv')

print( list(emails) )

Veja funcionando no Repl.it


In CSS file where I applied 16px font size to whole html tag.but now when I am trying to change the footer size by .75rem the size is not changing

Question: I applied font-size: 16px to the html tag but when i'm trying to change other tag's font-size, the fonts are not changing they are still at 16px.
Below as it can be seen that html tag is set to 16px and at down below right there in the footer .content i applied "font-size: 0.75;" but font size is still same and at similarly little up there in quotes-section quote i tried to do the same thing but still i'm unable to change the size.
<!DOCTYPE html>

  <meta name="viewport" content="width=device-width," initial-width="1">
  <link href="https://fonts.googleapis.com/css?family=Damion" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Rubik" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,600,700" rel="stylesheet">
  <link rel="stylesheet" href="./resources/css/reset.css">
  <link href="style.css" rel="stylesheet">
  <link href="reset.css" rel="stylesheet">
  <meta charset="UTF-8">

      Fotomatic

Product detail

About us

Follow us

Join us

Instant

FORMAT CAMERA

              Email us to request a demo and be in our waiting list for the Febuary 2017 release!

Join the waiting list

Advanced, automatic, instant

Shutter speed, apperture and flash output adjust automatically

Beautifully crafted inside-out

From the paint outside to the tiny screw inside, Fotomatic is crafted with love and 20-year of expertise

Over 20+ filters to choose from

Feed your creativity with 20 different filter designed by our eclectic in-house photographers!

        "It's truly something that could create a brand new photography Renaissance"

        © 2016  Fotomatic, All Rights Reserved
        Designed in NYC

/* Universal Styles */

html {
    font-family: "Roboto", sans-serif;
    font-size: 16px;
  }

  footer .content {
    color: white;
    display: flex;
    font-size: 0.75;
    padding: 1.5rem 2rem;
  }

Comment: Please share html codes as well. But checking your CSS, quick question: Do your footer has the ```content``` class itself or it has a class ```content``` inside of it? If the footer itself contains that class then the selector would be ```footer.content``` without the ```space```
Comment: Please read [ask]; in particular the part about providing a [mcve]. What you've provided is neither minimal (it seems to be your entire stylesheet, not **just the parts needed to reproduce the problem**) nor enough to reproduce the problem (the HTML is missing).
Comment: okay i got it. i have edited it and also provided the html code along with the block of CSS code where I'm facing an issue.
Comment: The issue is `font-size: 0.75;` is missing the unit and is an invalid declaration. Should be  `font-size: .75em;` or `font-size: 75%;`
Answer:

.content {
  font-size: 0.75rem; /* Add "rem" as the unit */
}

.quote {
  font-size: 12px; /* Add "px" as the unit */
}
Comment: The issue is `font-size: 0.75;` is missing the unit and is an invalid declaration. I guess this answer was downvoted for not explicitly stating that?
Comment: i think so this could be the reason. but i tried every possible ways but nothing came out


Please help me with this calculus question

Question: The coefficients of the quadratic function $f(x)$ including the constant term, are all
rational and $f(x)$ has a local maximum at $x = 0$.
Let  $g(x) =|f'(x)|e^{f(x)}$ have a maximum value of $4\sqrt{e}$. If $g(x) = 4\sqrt{e}$ has rational solutions then:
a) $\int_{-1}^0g(x)dx=e-\frac{1}{e^{7}}$
b) The value of the sgn$(f(0))=-1$      (where sgn is the sign function)
c) $g(x)$ is not differentiable at one value of $x$
d) The value of $g\left(\tan{\frac{\pi}{4}}\right)=\frac{2}{e^7}$
(Since, I don't yet know how to write integrals on this website)
The entire question is as follows
Comment: Welcome to Math SE.  Please learn to use MathJax to typeset your mathematics since images are highly discouraged for multiple reasons. I already see here that $g(x)$ includes $f(x)$ in your written description but includes $f'(x)$ in the image.  I've edited your question to illustrate the use of typesetting.  Additionally , you will get a far better response if you are able to explain what you tried and where you got stuck.
Comment: Welcome to MSE. Here's [how to ask a good question](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question). Follow these guidelines to get help in this forum. It's particularly important that you share your own work and thoughts on the problem to show that you have made a serious effort by yourself before asking for help, and you're not just trying to get others to solve it for you. [Here](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference)'s a guide so you can learn how to write integrals.
Comment: Hi, welcome to Math SE. Hint: $f(x)=a-bx^2$ for some $a,\,b\in\Bbb Q$ with $b>0$.
Comment: Then what? Also, write your own attempt.
Answer: Let $f(x) = b-ax^2$ ($a$ is positive btw)
$g(x)=|-2ax|e^{b-ax^2}$ = $|2ax|e^{b-ax^2}$
Let $g(m) = 4\sqrt{e}$
$g(m)=|2am|e^{b-am^2}=4\sqrt{e}$
$2a|m|=4$
$a|m|=2$
$a^2m^2=4$
If $g(m) = 4\sqrt{e}$ where $4\sqrt{e}$ is the maximum of $g(x)$
Then $g'(m)=0$
$$g'(x)=\frac{2ax(1-2ax^2)e^{b-ax^2}}{|x|}$$
$$\frac{2am(1-2am^2)e^{b-am^2}}{|m|}=0$$
$$2am(1-2am^2)e^{b-am^2}=0$$
$$1-2am^2=0$$ (We know that $m$ is not equal to 0 so this is legal)
$$1=2am^2$$
$$am^2=\frac{1}{2}$$
Looking back at $a^2m^2=4$,
$$\frac{a}{2}=4$$
$$a=8$$
Thus $m=\pm\frac{1}{4}$
$b-am^2=\frac{1}{2} \space\space\space\space (e^{b-ax^2}=\sqrt{e})$
$b-\frac{1}{2}=\frac{1}{2}$
$b=1$
$f(x)=1-8x^2$
$g(x)=16|x|e^{1-8x^2}$
$$\int_{-1}^0g(x)dx =\int_{-1}^016|x|e^{1-8x^2}dx $$
Since we are integrating from negative values of $x$, $ |x| = -x$
$$\int_{-1}^0-16xe^{1-8x^2}dx $$
$$\int_{-7}^1e^udu $$
$$=e-\frac{1}{e^7}$$
Hence a is the correct option.


Why do I need default while accessing a structure?

Question: I had this VB method which I converted to C#
Public Function GetToricData(ByRef SaveFileName As String) As ToricDataType
        Dim filenumber As Short
        Dim InString As String = ""
        filenumber = FreeFile()
        If System.IO.File.Exists(SaveFileName) Then
            With GetToricData
                FileOpen(filenumber, SaveFileName, OpenMode.Input)
                Input(filenumber, InString)
                If IsNumeric(InString) Then
                    .ToricAppDiam = Convert.ToDouble(InString)
                End If
                Input(filenumber, InString)
                If IsNumeric(InString) Then
                    .NumToricOpticZones = Convert.ToInt16(InString)
                End If
                FileClose(filenumber)
            End With
        Else
            With GetToricData
                .NumToricOpticZones = 20
                .ToricAppDiam = 3
            End With
            SaveToricData(SaveFileName, GetToricData)
        End If
    End Function

Post conversion to C# using Telerik Online Converter I got this
public static FrontEndStructures.ToricDataType GetToricData(ref string SaveFileName)
        {
            var title = ((AssemblyTitleAttribute)System.Reflection.Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false)[0]).Title;
            FrontEndStructures.ToricDataType functionReturnValue =  default(FrontEndStructures.ToricDataType);
            //FrontEndStructures.ToricDataType functionReturnValue = new FrontEndStructures.ToricDataType();

            int filenumber = 0;
            string InString = "";
            filenumber = FileSystem.FreeFile();
            if (System.IO.File.Exists(SaveFileName))
            {
                var _with38 = functionReturnValue;
                FileSystem.FileOpen(filenumber, SaveFileName, OpenMode.Input);
                FileSystem.Input(filenumber,ref InString);
                if (Information.IsNumeric(InString))
                {
                    _with38.ToricAppDiam = Convert.ToDouble(InString);
                }
                FileSystem.Input(filenumber,ref InString);
                if (Information.IsNumeric(InString))
                {
                    _with38.NumToricOpticZones = Convert.ToInt16(InString);
                }
                FileSystem.FileClose(filenumber);
            }
            else
            {
                var _with39 = functionReturnValue;
                _with39.NumToricOpticZones = 20;
                _with39.ToricAppDiam = 3;
                SaveToricData(ref SaveFileName, ref _with39);
            }
            return functionReturnValue;
        }

ToricDataType  is defined as
 public struct ToricDataType
        {
            public double ToricAppDiam;
            public short NumToricOpticZones;
        }

I want to know that what is the significance of the line

FrontEndStructures.ToricDataType functionReturnValue =
  default(FrontEndStructures.ToricDataType);

why did the online tool use Default keyword and why new keyword couldnt be used ?
As the class is a structure type and Structures are value types so where is the memory allocated (Stack or Heap ) and how data members are initialized ?
I am expecting a detail explanation on this and want to know that using new operator would help me achieve the same purpose or not ?
Comment: "As the class is a structure type".  Um, no.  A class is a class and a structure is a structure.  If you want a word that can refer to either then use "type".
Comment: "Structures are value types so where is the memory allocated".  Where is the memory ALWAYS allocated for value types?  It doesn't matter what value type it is.
Comment: "how data members are initialized".  The whole point of `default` is that it's the default value for the type.  Just like `Nothing` in VB, it's equivalent to populating the variable's stack memory with zeroes.  That means that ever field will also have the default value for it's type.
Answer: The C# null is not quite the same as the VB Nothing.  In VB, Nothing means the default value for a type.  For a reference type that is a null reference and for a value type that is a value with all its fields set to default values. In C#, null means a null reference for reference types but cannot be used to initialise value types.  The default operator does the equivalent job of providing a default value for a value type.
Note also that, unlike VB, C# functions have no default return value.  In VB you can assign to the implicit local variable that is named after the function and that value will be returned if no explicit Return statement is hit.  In C#, you are obliged to explicitly return something, hence the additional local variable.  I would really suggest not using that implicit return in VB anyway.  Explicit returns make your code clearer.
EDIT: You can use the new keyword to create a new instance and have the same effect.  The one scenario where you must use default is when the type you pass it is a generic type parameter, in which case you normally won't know whether it is a reference type or value type.
Comment: what about using the new operator ?
Comment: so where is the memory allocated ?
Comment: As I commented on your question, it's a value type and value types are always stored in the same place.  You don't need me to tell you where that place is.
Comment: @jmcilhinney i encountered this issue for the first time so asked. I knew that new operator allocates memory on heap whereas Structure is a value type so it uses stack. so when using new with a structure type where the memory would be created was a confusion.


How do I enable RDP in EC2 instances after mistakenly disabling rdp from Group Policy?

Question: I mistakenly disabled RDP in one of my EC2 windows instances through Group Policy Editor. Now I cannot RDP to that instance even with administrator account. I get  this message in the login screen now.
I did not enable WinRM in those instances, but not sure if they come enabled by default.
How can I re-enable RDP access in that EC2 instance?
Comment: Sounds like a tough problem.  I'd look at installing another windows machine on the same VPC and try to use administration tools on that new server to administer the other server.
Answer:
Yes, You can able to re-enable RDP using the AWSSupport-ExecuteEC2Rescue Automation (AWS Systems Manager)

Please follow below steps carefully:

Open the AWS Systems Manager console at https://console.aws.amazon.com/systems-manager/.
In the navigation pane, choose Automation.
Choose Execute automation.
In the documents list, choose AWSSupport-ExecuteEC2Rescue. The document owner is Amazon.
In the Document details section verify that Document version is set to the highest default version. For example, 13 (default).
In the Execution mode section, choose Simple execution. Leave the Targets and Rate Control option disabled.
In the Input parameters section, specify the following parameters:
For UnreachableInstanceId, specify the ID of the unreachable instance.
For LogDestination, specify an Amazon S3 bucket if you want to collect operating
system-level logs while troubleshooting your instance. Logs are automatically uploaded
to the specified bucket.
For EC2RescueInstanceType, specify an instance type for the EC2Rescue instance. The
default instance type is t2.small.(Please leave as it is if you are confused and go
ahead)
For SubnetId, specify a subnet in an existing VPC in the same availability zone as the
unreachable instance. By default, Systems Manager creates a new VPC, but you can
specify a subnet in an existing VPC if you want. (Please leave as it is if you are
confused and go ahead)

Note
If you don't see the option to specify a bucket or a subnet ID, verify that you are using the latest Default version of the document.
For Assume Role, if you created roles for this Automation by using the CloudFormation procedure described earlier in this topic, then specify the AssumeRole ARN that you copied from the CloudFormation console.

Choose Execute automation.

It takes sometimes (5-10 minutes) and you are able to access your old instance with new IP.
Here is the official AWS documentation for this issue:
https://aws.amazon.com/premiumsupport/knowledge-center/troubleshoot-remote-desktop-connection-ec2-windows/


Is it possible to get program start and end addresses using GetSystemInfo() in C?

Question: I'm currently learning windows.h lib. According to docs, it is possible to know the minimum and maximum program addresses by means of lpMinimumApplicationAddress and lpMaximumApplicationAddress fields of SYSTEM_INFO structure, GetSystemInfo() function. However, I'm wondering: is it possible to get program start and end address, using GetSystemInfo()? If possible, how?
Thank you for advance.
Comment: No, with `GetSystemInfo()` you can't. Why does it have to be that function? Can't you use [`GetModuleInformation()`](https://learn.microsoft.com/en-us/windows/win32/api/psapi/nf-psapi-getmoduleinformation)?
Comment: What does *"program start address"* and *"program end address"* mean to you?
Comment: Do *"program start address"* and *"program end address"* mean [virtual address space](https://learn.microsoft.com/en-us/windows/win32/memory/memory-limits-for-windows-releases#memory-and-address-space-limits)?
Comment: ...or does it mean `[EntryPoint, EntryPoint + SizeOfImage)`  from [`MODULEINFO`](https://learn.microsoft.com/en-us/windows/win32/api/psapi/ns-psapi-moduleinfo)?
Comment: Why is it important to you that you just use GetSystemInfo() to get the information?
Answer: If you mean the actual address that program terminates on (or whether it terminates at all), no. That is just a variation on the famous halting problem. And that has been proven to not have a general solution.
Minimum and maximum address are just what memory has been assigned to a process, but there could be many places in it that the program would terminate at, depending on the exact run parameters. And it might not even reach any of them.


Find points on $n$-dimensional grid within hypersphere

Question: Given an infinite $n$-dimensional grid, and an arbitrary hypersphere with center c and radius $r$, how can one efficiently generate all points of this n-dimensional grid that are within the hypersphere?
Example on a $2d$ grid:

Points that lie within the hypersphere are green, points outside are red. (Please excuse the messy grid)
One possibility is to enumerate all points within a hypercube of side length $r$, and reject points that aren't within the hypersphere. However, this approach quickly loses efficiency as the ratio between points in the hypersphere and hypercube decreases as dimensionality $n$ increases.
I'm considering a method that finds the closest point, then the $2nd$ closest point, etc. until a point outside the hypersphere is reached, but the details elude me.
Note: For my particular problem, the grid has arbitrary distance between points (ex. $0.5, 1.0, 1.5, ...)$, but I suspect any method that works on a regular grid should generalize easily.
Edit: I've implemented both Paul Sinclair and Anton Sherwood's methods. In my tests (with very similar implementations to minimize other factors), Sinclair's method is faster when dimensionality of the problem is $> 3.$ Although Sinclair's method has greater constant factors due to the use of a square root, it does not require checking points outside the hypersphere. As dimensionality increases, the ratio of points found inside the hypersphere to outside decreases for Sharwood's method. Thank you both for your help.
Answer: One idea would be to order your dimensions, and limit inside loops based on the values outside:
<code>
   for(x1 = ceiling(-r); x1<= r; x1++)
      r2 = sqrt(r^2 - x1^2)
      for(x2 = ceiling(-r2); x2 <= r2; x2++)
         ...
</code>
Answer: Your "closest point" idea is on the right track.  Start with the closest (n-1)-hyperplane.  Within it, start with the closest (n-2)-plane ... These are much easier to order than the grid points themselves!
Before you begin each plane of any dimension, see whether it intersects the sphere at all.  If not, no further planes of that dimension will either; step to the next plane one dimension up.
This approach requires no square roots, and the number of rejections is at worst proportional to the surface of the hypersphere rather than the volume of (hypercube-hypersphere).
Comment: Let's see if I understand this. To get each (n-k)-hyperplane I compare the k-th component of the center to the k-th component of the grid. By locking a component, and leaving the others variable, I have a hyperplane. Once every component is determined, I have a point on the grid. However, I'm not sure how to efficiently determine if the hyperplane intersects the hypersphere.
Comment: The minimum distance of the hyperplane to the centre is the distance of the point you get by setting the remaining free coordinates to those of the centre (i.e., setting delta in those dimensions to zero).  Is that distance (squared) less than the radius (squared)?
Comment: I managed to successfully implement this method, but it doesn't appear to scale well to higher dimensions. If I understand this correctly, checking if a hyperplane with n fixed coordinates intersects the hypersphere requires n subtraction and n multiplication operations. **v** . **v**, where **v** = **p**' - **c**'. **p**' is the vector of fixed coordinates and **c**' is the vector of corresponding center coordinates.
Comment: Each hyperplane's squared distance is (∆x_i)^2 – which can be precomputed – added to the squared distance found in the next outer loop, so you needn't compute v•v from scratch as often as you suggest.
Comment: Ah, yes. You're right. This is a significant optimization. However, in my tests, this method still does not scale as well to higher dimensions, due to checking a point outside the hypersphere before continuing to the next hyperplane, which Paul Sinclair's method does not require. In my tests, this method is faster for 3 and fewer dimensions.


Parsing large number of HTML files with asyncio aiofiles and parsing them in pandas DataFrame

Question: I have around 40 000 HTML files on disk and function that parses HTML with Beautiful Soup and returns dictionary for each HTML.
During reading/parsing I'm appending all dictionaries to list and creating pandas DataFrame in the end.
It all works ok in synchronous mode but it takes a long time to run so I want to run in with aiofiles
Currently my code looks like this:
<code># Function for fetching all ad info from single page
async def getFullAdSoup(soup):
     ...
     adFullFInfo = {} # dictionary parsed from Beautifoul soup object
    return await adFullFInfo

async def main():
    adExtendedDF = pd.DataFrame()
    adExtendednfo = {}
    htmls = glob.glob("HTML_directory" + "/*.html") # Get all HTML files from directory

    htmlTasks = [] # Holds list of returned dictionaries
    for html in natsorted(htmls):
        async with aiofiles.open(html, mode='r', encoding='UTF-8', errors='strict', buffering=1) as f:
            contents = await f.read()
            htmlTasks.append(getFullAdSoup(BeautifulSoup(contents, features="lxml")))
        htmlDicts = await asyncio.gather(*htmlTasks)
    adExtendedDF = pd.DataFrame(data=htmlDicts, ignore_index=True)

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
</code>
Error I'm getting is:

File "C:/Users/.../test.py", line 208, in getFullAdSoup
      return await adFullFInfo TypeError: object dict can't be used in 'await' expression

I'm finding similar question here but I'm unable to make it work.
I don't know how to transform my parsing function to asynchronous mode and how to iterate over files calling that function.
Comment: Your error clearly happens since await `adFullFInfo` which is a dict, why is that?
Comment: Also asyncio is meant for heavy IO and web requests, to read and proccess mutliple files its much better to use multiprocessing
Comment: I know that. Idea is to convert it to something usable in asyncio.
Answer: Your error happens because you await a dict, I'm guessing you misunderstood, you don't need to await in the return statement for it to be async. I would refactor it like this
<code># Function for fetching all ad info from single page
async def getFullAdSoup(soup):
     ...
     adFullFInfo = {} # dictionary parsed from Beautifoul soup object
    return adFullFInfo #*****1****

async def main():
    adExtendedDF = pd.DataFrame()
    adExtendednfo = {}
    htmls = glob.glob("HTML_directory" + "/*.html") # Get all HTML files from directory

    htmlTasks = [] # Holds list of returned dictionaries
    for html in natsorted(htmls):
        async with aiofiles.open(html, mode='r', encoding='UTF-8', errors='strict', buffering=1) as f:
            contents = await f.read()
            htmlTasks.append(asyncio.create_task( #****2****
                getFullAdSoup(BeautifulSoup(contents, features="lxml"))))
        await asyncio.sleep(0) #****3****
    htmlDicts = await asyncio.gather(*htmlTasks) #****4****
    adExtendedDF = pd.DataFrame(data=htmlDicts, ignore_index=True)

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
</code>
4 changes:

No need to await the dict
Use asyncio.create_task to schedule the task to run ASAP
sleep(0) to release the event loop and let the task start running
Move the gather method outside of the loop, so you can gather all tasks at once instead of one at a time.

2 and 3 are optional, but I find that it makes a lot of speed difference depending on what you are doing
Comment: Applied changes, shortened file list on 5 files. Script is not ending..After several minuted still nothing is written to adExtendedDF.


Complex number to polar and cartesian form

Question: I need to tranform: $$z:=-4e^{{\pi}i/3}$$
to the polar (I know it's almost polar) and cartesian form, i.e. find x and y coordiantes.
$$-4e^{{\pi}i/3}=-4(\cos(\frac\pi3)+\sin(\frac\pi3)i)=4(-1)(\cos(\frac\pi3)+\sin(\frac\pi3)i)=4(-\cos(\frac\pi3)-\sin(\frac\pi3)i)$$
Don't really know how to continue.
So what's the trick behind this complex number?
Comment: Just put $\cos(\pi/3) = 1/2$ and $\sin(\pi/3) = \sqrt{3}/2$.
Comment: it is $$z=-2+2i\sqrt{3}$$
Comment: @GNUSupporter will remember to do it in the future
Comment: There's little to continue. $z$ started out in polar form. To finish cartesian, just distribute the $4$ over the parentheses in your last expression to find the real and imaginary parts. You might explicitly evaluate the trig functions in terms of $\sqrt{3}$.
Comment: Usually by definision the form $$z:=\rho e^{i\theta}$$ is defined with $ \rho \ge0$
Comment: [Fractions in indices are hard to read.](https://math.meta.stackexchange.com/a/5057/290189)  I've [edit]ed your post to improve readability.
Comment: thanks for all comments, was easier than I thought, sorry for such a trivial question
Comment: @Dr.SonnhardGraubner View gimusi's answer.
Answer: Multiplying a complex number by $-1$ is the same as rotating it (if we think of it as an arrow from the origin) 180 degrees in the complex plane, to make it point in the opposite direction. So you can remove the minus sign and compensate the angle by adding (or subtracting) $\pi$.
Answer: Note that

$\cos(\frac\pi3)=\frac12$
$\sin(\frac\pi3)=\frac{\sqrt3}2$

thus
$$4\left(-\cos(\frac\pi3)-\sin(\frac\pi3)i\right)=-2-2\sqrt3\,i$$
Answer: Continue your work by substituting $\sin \frac\pi3 = \frac{\sqrt3}{2}$ and $\cos\frac\pi3 = \frac12$.
$$\begin{aligned}
-4e^{{\pi}i/3}&=-4(\cos(\frac\pi3)+\sin(\frac\pi3)i)\\
&=4(-1)(\cos(\frac\pi3)+\sin(\frac\pi3)i)\\
&=4(-\cos(\frac\pi3)-\sin(\frac\pi3)i)\\
&=4\left(-\frac12-\frac{\sqrt3}{2}i\right)\\
&=-2-2\sqrt3 \,i
\end{aligned}$$


Calculate $\sum_{x=1}^{\infty} \frac{(x-1)}{2^{x}}$

Question: I can prove it converges but I don't know at what value it converges.
$\sum_{x=1}^{\infty} \frac{(x-1)}{2^{x}}$
Comment: Asked zillion times. Try $\sum_{x=1}^{\infty}a_x=\sum_{x=0}^{\infty}a_{x+1}$ and see the connection.
Comment: Your series is a minor modification of a special case of $\sum_{n=1}^\infty na^n$; the answers to [this question](https://math.stackexchange.com/questions/30732/how-can-i-evaluate-sum-n-0-inftyn1xn) illustrate a considerable variety of approaches.
Answer: because all the summands are nonnegative you can actually rearrange the sum like this:$$\sum_{x=1}^\infty \frac{x-1}{2^x}= \sum_{k=2}^\infty \underbrace{ \sum_{x=k}^\infty \frac{1}{2^x}}_{=\frac{1}{2^{k-1}}}$$
Answer: Hint
$$\sum_{x=1}^\infty (x-1)y^x={d\over dy}\sum_{x=1}^\infty y^{x+1}$$
Answer: Start with (for $\lvert u \rvert < 1$ the geometric series converges absolutely, we'll use $u = 1/2$ in the end, so all the manhandling is justified):
$\begin{align*}
  \sum_{x \ge 1} u^x
    &= \frac{u}{1 - u} \\
  \frac{d}{d u} \sum_{x \ge 1} u^x
    &= \frac{1}{(1 - u)^2} \\
  \sum_{x \ge 1} x u^{x - 1}
    &= \\
  \sum_{x \ge 1} x u^x
    &= \frac{u}{(1 - u)^2} \\
  \sum_{x \ge 1} (x - 1) u^x
    &= \frac{u}{(1 - u)^2} - \frac{u}{1 - u} \\
    &= \frac{u^2}{(1 - u)^2}
\end{align*}$
Now replace $u = 1/2$ and get:
$\begin{align*}
  \sum_{x \ge 1} \frac{x - 1}{2^x}
    &= \frac{(1/2)^2}{(1 - 1/2)^2} \\
    &= 1
\end{align*}$


Como emitir Nota Fiscal Eletronica no mode teste no Woocommerce?

Question: Como faço para emitir gratuitamente as notas fiscais, versão teste no Woocommerce? Para testar o plugin, da WebminarBR.
Answer: Rapaz, não sei se já te responderam e se era WebminarBR, sei do WebManiaBR.
Mas no próprio site da webmaniabr tem as instruções https://webmaniabr.com/blog/emita-nf-e-na-sua-loja-virtual-woocommerce/
Espero que ajude.


Backbone - Difference between setting property in intiaiize using this, vs putting it on the object passed to extend

Question: In backbone, what is the difference between these two pieces of code:
var myView = Backbone.View.extend({
  myprop : ...,
  ...
}

and
var myView = Backbone.View.extend({
  initialize: function(){
    this.myprop = ...;
  },
  ...
}

Answer: There is no difference if your variable is a primitive type (a boolean, string or a number) since it is copied to each instance.
However if your variable is a Object/Array, then if you declare it as you have in the first example it will be copied by reference, meaning all instances of that view will share one variable (so if you modify it in any instance, it will effect all the others).
In the second example each instance will have it's own private variable that only it can effect.
var View = Backbone.View.extend({
    hello: {say: 'hello planet'},

    initialize: function() {
        this.goodbye = {say: 'goodbye planet'};
        console.log('Hello:', this.hello.say);
        console.log('Goodbye:', this.goodbye.say);
        console.log('--------');
    }
});

var view1 = new View();
view1.hello.say = 'hello world';
view1.goodbye.say = 'goodbye world';

var view2 = new View();

The output will be:
Hello: hello planet
Goodbye: goodbye planet
--------
Hello: hello world
Goodbye: goodbye planet
--------

Because the first instance modifies "hello" which is shared, so it becomes "hello world". But modifying "goodbye" has no effect since it isn't shared.
http://jsfiddle.net/4rp6kpck/1/


$\lim_{x \rightarrow 0} \frac{(x^2 - x^3) ((x + 1)^\sqrt{2} - 1)}{\log(1 + 4 x) (1 - \cos(2 x))}$

Question: I'm trying to find the following limit:
$$\lim_{x \rightarrow 0} \frac{(x^2 - x^3) ((x + 1)^\sqrt{2} - 1)}{\log(1 + 4 x) (1 - \cos(2 x))}$$
Knowing that:
$$ \lim_{x \rightarrow 0} \frac{\log(1 + x)}{x} = 1$$
and
$$ \lim_{x \rightarrow 0} \frac{1 - \cos(x)}{\frac{x^2}{2}} = 1$$
We have:
$$\lim_{x \rightarrow 0} \frac{(x^2 - x^3) ((x + 1)^\sqrt{2} - 1)}{\log(1 + 4 x) (1 - \cos(2 x))} = \lim_{x \rightarrow 0} \frac{1}{(4 x) \frac{(2 x)^2}{2}} \frac{(x^2 - x^3) ((x + 1)^\sqrt{2} - 1)}{\frac{\log(1 + 4 x)}{4 x} \frac{(1 - \cos(2 x))}{\frac{(2x)^2}{2}}} = \lim_{x \rightarrow 0} \frac{(x^2 - x^3) ((x + 1)^\sqrt{2} - 1)}{(4 x) \frac{(2 x)^2}{2}} = \lim_{x \rightarrow 0} \frac{(1 - x)((x + 1)^\sqrt{2} - 1)}{8 x}  $$
I feel I need to get rid of $((x + 1)^\sqrt{2} - 1)$ in numerator (so that I don't have a $\frac{0}{0}$ indeterminate form), but I don't know how.
Edit:
Knowing that:
$$ \lim_{x \rightarrow 0} \frac{e^x - 1}{x} = 1 $$
We have that:
$$\lim_{x \rightarrow 0} (x + 1)^\sqrt{2} - 1 = \lim_{x \rightarrow 0} \frac{e^{\sqrt{2} \log(x + 1)} - 1}{\sqrt{2} \log(x + 1)} = \lim_{x \rightarrow 0} \frac{e^{\sqrt{2} \log(x + 1)} - 1}{\sqrt{2} \log(x + 1)} \frac{\log(x + 1)}{x} \sqrt{2}  x$$
I think that should solve it.
Comment: Use the formula $\frac{(1+x)^a-1}{x}\to a$.
Comment: You will still still have an indeterminate $\;\frac00\;$ without that factor in the last lines of your post...
Comment: @DonAntonio I could have a $\infty$ limit
Comment: @Jordi With a $\;\frac00\;$ intedeterminate form you can have anything between $\;-\infty\;,\;\;\infty\;$ , including both...or the limit could not even exist.
Comment: You don't need to use the $\exp, \log$ stuff and instead use the formula in my last comment directly. You should get the desired limit as $1/(4\sqrt{2})$.
Answer: This is one using series expansions for elementary functions
$$
\lim_{x \rightarrow 0} \frac{(x^2 - x^3) ((x + 1)^\sqrt{2} - 1)}{\log(1 + 4 x) (1 - \cos(2 x))}=\lim_{x \rightarrow 0} \frac{x^2 ((x + 1)^\sqrt{2} - 1)}{\log(1 + 4 x) (1 - \cos(2 x))}
$$
$$
\\ \ \\ \ \\
(1+x)^n=1+nx+{n(n-1)\over 2!}x^2+\cdots\\
\log(1+x)=x-{x^2\over 2}+{x^3\over 3}+\cdots\\
\cos x=1-{x^2\over2!}+{x^4\over4!}+\cdots
$$
So the limit becomes
$$
=\lim_{x \rightarrow 0} \frac{x^2 (1+\sqrt{2}x+{\sqrt{2}(\sqrt{2}-1)x^2\over2!}\cdots - 1)}{(4x-{16x^2\over2}+\cdots) (1 - (1-{4x^2\over2!}+{16x^4\over4!}+\cdots))}\\
=\lim_{x \rightarrow 0} \frac{x^3 (\sqrt{2}+{\sqrt{2}(\sqrt{2}-1)x\over2!}\cdots )}{x^3(4-{16x\over2}+\cdots) ({4\over2!}+{16x^2\over4!}+\cdots))}={\sqrt{2}\over8}
$$
Comment: the standard limits you used are based on these expansions so same thing
Comment: That minus sign seems to be incorrect...
Comment: oh wait ye mental math bit off
Answer: $$\frac{(x^2 - x^3) ((x + 1)^\sqrt{2} - 1)}{\log(1 + 4 x) (1 - \cos(2 x))}=\frac{(x+1)^\sqrt2-1}x\cdot\frac{x^2}{1-\cos2x}\cdot\frac{x-x^2}{\log(1+4x)}\;(**)$$
and just as Paramanand told you twice, using
$$\lim_{x\to0}\frac{(x+1)^\sqrt2-1}x=\left[\left((x+1)^\sqrt2\right)'\right]_{x=0}=\sqrt2\,(0+1)^{\sqrt2-1}=\sqrt2$$
we get at the end
$$(**)\xrightarrow[x\to0]{}\sqrt2\cdot\frac12\cdot\frac14=\frac{\sqrt2}8=\frac1{4\sqrt2}$$
Answer: Yes you idea by standard limits is fine, after factorization
$$\frac{(x^2 - x^3) ((x + 1)^\sqrt{2} - 1)}{\log(1 + 4 x) (1 - \cos(2 x))}=\frac{(x+1)^\sqrt2-1}x\cdot\frac{x^2}{1-\cos2x}\cdot\frac{4x}{\log(1+4x)}\cdot\frac{1-x}{4}$$
for the first factor we have
$$\frac{(x+1)^\sqrt2-1}x=\sqrt 2\; \frac{e^{\sqrt 2 \log(x+1)}-1}{\sqrt 2 \log(x+1)}\frac{\log(x+1)}{x} \to \sqrt 2\cdot 1 \cdot 1=\sqrt 2$$


Azure Functions - get records by attribute name

Question: I have created a function app to retrieve the records from Azure SQL DB table(loan table). Function app works fine. I want to now add filters and retrieve the records based on loan record attributes ( loan id, loan amount,...). Should I create a new function for each of the attribute that I need or is there any better approach to do it?
Thanks in advance.
Comment: no, use the same function.
Comment: Thank you Thiago
Comment: Hi, any update of this question?
Answer: No, you don't need to create new function of each attribute.
You can put the logic in the body of the function. For example, if you are using httptrigger, you can do something like this:(The below code is just an example, you can use the logic that can achieve your requirement.)
<code>public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            string loan_id = req.Query["loanid"];
            string loan_amount = req.Query["loanamount"];

            if (string.IsNullOrEmpty(loan_id)) {
                //Do something when dont give loan id.
            } else if (string.IsNullOrEmpty(loan_amount)) {
                //DO something when dont give loan amount.
            }

            return new OkObjectResult("This is a test.");
        }
</code>
The example is based on C#, basically you can put the filter logic in the body of the function.


Change the variables in $Q(x,y,z)=(x-y+z-1)^2-2z+4$ to have $Q(f(u,v,w))=u^2+v$

Question: I have a problem with this exercise. Initially, they gave me this polynom, and I had to complete the squares:
$$Q(x,y,z)=x^2-2xy+2xz+y^2-2yz+z^2-2x+2y-4z+5.$$
I've done it, and I've checked with maple (so it's correct). We have:
$$Q(x,y,z)=(x-y+z-1)^2-2z+4$$
Now, they say that I have to find an affine transformation to change the variables to have:
$$Q(f(u,v,w))=u^2+v.$$
So I thought that I could do
$$\begin{cases}
u=x-y+z-1\\v=-2z+4\\w=0
\end{cases}
$$
and solve this system for $\{x,y,z\}$. But obviously it doesn't have a solution.
I'd appreciate any hint, because I don't know how to do this change of variables.
Thanks.
Comment: Why set $w = 0$?  Set it so that the transformation has a solution.
Comment: @Macavity I tried different options but I can't do it.
Answer: What do you means by

But obviously it doesn't have a solution

You don't need to solve this system of equations.
You just find an affine transformation which is
$$\begin{bmatrix}u\\v\\w\end{bmatrix}=
\begin{bmatrix}1&-1&1\\0&0&-2\\0&0&0\end{bmatrix}
\begin{bmatrix}x\\y\\z\end{bmatrix}+
\begin{bmatrix}-1\\4\\0\end{bmatrix}$$
And it works.
Comment: $v=-2z+4$, so $z=-1/2v+2$. Then $u=x-y-1/2v+1$. I choose to set $x=u-1$, so $y=-1/2v$.
Comment: Who is $f(u,v,w)$ then? The image of $f$ has to be in terms of $(u,v,w)$. If not, with your affine transformation, $Q$ is a polynom in $x,y,z$, and I need it to be $u^2+v$. The matrix $$
\begin{bmatrix}1&-1&1\\0&0&-2\\0&0&0\end{bmatrix}
$$

does not have an inverse, and that's where the problem reside.
Comment: But if you solve the system without matrix, directly from the equations. You can get answers like $x=u-1$,$y=-1/2v$,$z=-1/2v+2$. The matrix does also not have an inverse. What do you think?
Comment: how did you get this equations?
Comment: last question, I promise. Why do you choose $x=u-1$?
Comment: Sorry, I just got that an affine transformation must be reversible. So I am totally wrong.


Continuity, constant functions

Question: I am completely stuck and would be delighted if someone could explain an approach. Thanks!
Let $f : \mathbb{R} \to \mathbb{R}$ be a continuous function with $f (x) = f (x^2)$ for all $x \in \mathbb{R}$.
Show that $f(y^{(2^{-n})})=f(y)$ for all $n ∈ \mathbb{N} \cup\{0\}$ (the natural numbers including zero) and $y ≥ 0$ and conclude that $f$ is constant.
Comment: Welcome to MSE. You need to show some kind of attempt. For example, it's obvious that the relation on $y$ holds when $n=0$. Have you tried thinking about what happens when $n=1$?
Comment: welcome to MSE. is this edition true ?
Comment: The question has two parts. First showing that the relation holds. The second part is using it to prove that f is constant. Do you have a problem with both?
Comment: well $f(x)=f(\sqrt{x})=f(\sqrt{\sqrt{x}})$ can you continue ?
Comment: The edition is true.
Comment: I was hoping to get a better suggestion or solution.
Answer: First observe that $f(x)=f(x^2)=f(-x)$ for all $x\in\Bbb R$, because $(-x)^2=x^2$.
Let $x>0$, then $x^{\frac1{2^n}}\to x^0=1$ if $n\to\infty$, so the constant sequence $f(x)=f(x^{\frac12})=f(x^{\frac14})=\dots$ converges to $f(1)$ by continuity, so we must have $f(x)=f(1)$.
Finally, continuity at $0$ implies $f(0)=f(1)$.
Comment: Thanks for you for your answer! How can i conclude that  f  is constant?
Comment: For every $x$, I proved $f(x)=f(1)$.

Continuity, constant functions


How do I toggle my website title when my users have unread messages from their friend?

Question: Like in facebook, when we're chatting with someone and during that time while we're browsing another site in another tab, Facebook tab's title toggles, once it's 'Facebook', then it's 'Rehan messaged you'. How do I achieve this?
document.title = 'Rehan messaged you';

The above javascript code will change my site's title. But how do I make it toggle with the original Title which is the name of my website 'MySite.Com'?
Comment: Conceptually, you save the original title in a variable and then at "unread message" event you set the title to the new title and when on "user has read message" event you set it back to the original title.
Comment: something like this [http://stackoverflow.com/a/3381522/2359055](http://stackoverflow.com/a/3381522/2359055)
Comment: I want to keep it toggling from 'Mysite' to 'User messaged you' and again from 'User messaged you' to 'Mysite', until the user reads the message. After which the title will just be 'Mysite' without any toggling. @limelights
Comment: Ah, okay, I don't have facebook so their concept is unknown to me.
Answer: You can do it using the setInterval function:
var cont = 0;
setInterval(function () {
    if (cont % 2) {
        var myText = 'Text 1';
    } else {
        var myText = 'Another text';
    }
    document.title = myText;

    cont++;
},1000);

http://jsfiddle.net/7bMjN/
I made use of jQuery but it is not needed.
Answer: Here is a relatively robust solution where you can add/remove any number of messages, each of which will be iterated over while displaying the base message in between each at your specified toggle interval.
/***Framework Code***/

//Configs
var BASE_MESSAGE = "MySite.Com";//Message to display every other time
var toggleInterval = 1000;//One second between each toggle

//Private Variables
var otherMessages = [];
var currentMessageIndex = 0;

/**
 * Updates the title, switching between the base text and iterating through
 * the other messages
 */
var updateTitle = function(){
    //Toggle between messages
    if((currentMessage !== BASE_MESSAGE) || !otherMessages.length){
        //Display base message every other time
        document.title = BASE_MESSAGE;
    } else {
        //Display the next message in the list
        currentMessageIndex = currentMessageIndex++ %otherMessages.length;
        document.title = otherMessages[currentMessageIndex];
    }

    //Call again only if there are messages to show
    if(otherMessages.length){
        setTimeout(toggleInterval, updateTitle);
    }
};

/**
 * Adds a title message to display
 */
var addTitleMessage = function(message){
    otherMessages.push(message);

    //Avoid too many title updates
    if(otherMessages.length == 1){
        updateTitle();
    }
};

/**
 * Removes the specified title message from being displayed
 */
var removeTitleMessage = function(message){
    var removeIndex = otherMessages.indexOf(message);

    if(removeIndex != -1){
        otherMessages.splice(removeIndex, 1);
    }
};

.
/*** Your Code ***/
var newMessage = function(messageInfo){
    ..//Your normal new message code

    addTitleMessage(getMyDisplayMessage(messageInfo));
};

var readMessage = function(messageInfo){
    ..//Your normal read code

    removeTitleMessage(getMyDisplayMessage(messageInfo));
};

var getMyDisplayMessage = function(messageInfo){
    return messageInfo.name + " has messaged you.";
}

Answer: Use setInterval() or setTimeout(). In your case, code may be like that:
function toggleTitle() {
    if (document.title == 'MySite.Com') document.title = 'Rehan messsaged you';
    else document.title = 'MySite.Com'
}
var timer = setInterval(toggleTitle, 500);

this code will make your title change every 0.5 seconds. To stop that, use

clearInterval(timer);
Comment: thanks, it worked just fine. And your code is neat and clean and easy to understand. :)


Set Notation - Inclusion and Proper Inclusion

Question: By definition:

If$ \ A$ and $B\ $are sets and every element of$ \ A\ $ is also an element of $ \ B \ $then we can say $ \ A\ $is a subset of $ \ B, \ $and denote this by $ \ A\subset B\ $or $ \ A\subseteq B.\ $Or, equivalently, we can say that$ \ B$ is a super set of $\ A \ $(if every element of A
   is also an element of B), which is denoted by $ \ B\supseteq\ A.\ $If $ \ A \ $ is $\neq\ B \ $(there exists at least one element of $ \ B \ $which is not an element of $ \ A), \ $then $ \ A \ $is a proper subset of $ \ B \ $, which is denoted$ \ A\subsetneq\ B. \ $ Or, equivalently, $ \ B$ is a proper super set of $\ A \  $(if $A\subset B,$ but $A\neq B$) which is denoted by $ \ B\supsetneq\ A.\ $

In the case where where $ \ A \ $ is $\neq\ B, \ $but every element of $A$ is also an element of $B,$ are $ \ A\subset B,\ A\subseteq B,\ B\supseteq A,\ A\subsetneq B,\ B\supsetneq A \ $all equivalent? In the case where where $ \ A=B \ $are $\ A\subset B,\ B\subset A,\ A\subseteq B,\ B\supseteq A,\ A\supseteq B,\ B\subseteq A\ $all equivalent? It's kind of strange to think that if two sets are equal to one another, that they are also both supersets of each other. It seems more "natural," to me at least, that the whole superset "concept," where $ \ A\supseteq B\ $or $ \ B\supseteq A,\ $should be reserved for when $ \ B\neq A\ $(but every element of $B$ is in $A$) or $ \ A\neq B \ $(but every element of $A$ is in $B$). Of course in both of these cases we would use the proper superset notation.
Answer: In fact, one way to prove that two sets are equal is to show that they are both subsets/supersets of each other, i.e. $A = B \iff \left( A\subset B \right)\wedge \left(B\subset A\right)$.
The 'equivalencies' you've written are not exactly the way you are thinking. It's true that if $A$ is a subset of $B$ but not equal to $B$ then $A\subset B$, $A\subseteq B$, $B\supseteq A$, $B\supset A$ are all true but it is sloppy. The most correct thing to write in this case is $A\subsetneq B$ or $B\supsetneq A$. Think about the analogous concepts with numbers, of course $2+2=4$ but we can be sloppy and write $2+2\geq 4$ or $4\leq 2+2$. The proper subset/supset notation is more precise, but if you have a proper subset/supset then yes, you also have subset/supset inclusion as well.
Answer: Note: some authors use $\subset$ and $\varsubsetneq$ interchangeably whereas others use $\subset$ and $\subseteq$ interchangeably.
In the case that $A$ is a proper subset of $B$, you can still write $A \subseteq B$, but this is the same as writing $2\le 3$ instead of $2 < 3$ — both statements are true, but one is more conclusive.


How to set GridViewBrowseColumn (Telerik radgridview in winforms) initial directory

Question: I am using radgridview (telerik controls) in winforms application. One of columns is GridViewBrowseColumn. But I don't know how to set initial directory for this control. Can anyone help me?
Answer: RadGridView offers the CellEditorInitialized event which is fired right after the editor is activated. GridBrowseEditor is the default editor for the GridViewBrowseColumn. If you want to set any initially selected folder in the editor, it is necessary to set its Value to the desired path:
<code>    public partial class RadForm1 : Telerik.WinControls.UI.RadForm
{
    public RadForm1()
    {
        InitializeComponent();

        GridViewBrowseColumn browseColumn = new GridViewBrowseColumn();

        this.radGridView1.Columns.Add(browseColumn);
        this.radGridView1.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill;

        this.radGridView1.CellEditorInitialized+=radGridView1_CellEditorInitialized;
    }

    private void radGridView1_CellEditorInitialized(object sender, GridViewCellEventArgs e)
    {
        GridBrowseEditor browseEditor = e.ActiveEditor as GridBrowseEditor;
        RadBrowseEditorElement el = browseEditor.EditorElement as RadBrowseEditorElement;
        el.DialogType = BrowseEditorDialogType.FolderBrowseDialog;
        FolderBrowserDialog folderBrowserDialog = el.BrowseDialog as FolderBrowserDialog;
        if (el.Value==null)
        {
            el.Value =  @"C:\Projects";
        }
    }
}
</code>
I hope this information helps.
Answer: Thank you Dess. Your answer was helpful. I just edited two lines of your code. I want to have a open file dialog but your was folder browse dialog. I write it here maybe helpful for others:
<code>private void gv_CellEditorInitialized(object sender,
   GridViewCellEventArgs e)
{
    GridBrowseEditor browseEditor = e.ActiveEditor as GridBrowseEditor;
        RadBrowseEditorElement el = browseEditor.EditorElement as
        RadBrowseEditorElement;

        el.DialogType = BrowseEditorDialogType.OpenFileDialog;
        OpenFileDialog ofd = el.Dialog as OpenFileDialog;
        ofd.InitialDirectory = @"D:\";

}
</code>


Using icon and text in html  tag, how do I change the text font?

Question: So I'm writing a personal website to help myself learn html and css, and as part of that, I'm trying to put in some contact links. For these I want them to have an icon and text. I'm using the font awesome icons to achieve this. As of right now, I have the links working properly, but for some reason, the text in the links is a serif font, when the rest of my site is a sans serif font. Additionally, one fo the links is bolded constantly, when it's only supposed to be bolded when hovered over. This is what it looks like (boxes added to protect my info):
Screenshot from webpage
Here's my HTML and related CSS code:

    a {
      color:#263fb9;
      text-decoration:none;
      font-family: "Noto Sans", Monaco, Bitstream Vera Sans Mono, Lucida Console, Terminal, Consolas, Liberation Mono, DejaVu Sans Mono, Courier New, monospace;
      }

    a:hover, a:focus {
      color:#111e5c;
      font-weight: bold;
      }

    .fa {
      padding: 20px;
      font-size: 30px;
      width: 30px;
      text-align: center;
      text-decoration: none;
      border-radius: 50%;
      font-family: "Noto Sans", Monaco, Bitstream Vera Sans Mono, Lucida Console, Terminal, Consolas, Liberation Mono, DejaVu Sans Mono, Courier New, monospace;
      }
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>
     EMAIL ADDRESS

     HANDLE

(Note: all of this was adapted from the Jekyll "Minimal" theme from github pages)
Answer: Don't add the fa class to the a tag, use an extra element:
  EMAIL ADDRESS

Comment: Hi! thank you so much! this fixed the font issue, but now the icons themselves aren't showing up (they're just little boxes). Any idea? EDIT: Nevermind! that was because of something else I had screwed up elsewhere! Thank you!
Answer: Your problem in this case is that the classes you are adding to your link (the FontAwesome classes) end up modifying your font-family definition for the element.
So, what you could do in this case is use something like this:
 HANDLE


Why are the derivatives not treated the same?

Question: It seems to me that derivatives are treated differently in certain places, but I do not understand why.
Here is an example, if
\begin{align}
\frac{d}{dx} (\sqrt{1 + 4x^2}) & = \frac{1}{2\sqrt{1 + 4x^2}} \cdot \frac{d}{dx} (1 + 4x^2) \\
& = \frac{4 \cdot \frac{d}{dx}x^2}{2\sqrt{1 + 4x^2}} \\
& = \frac{4x}{\sqrt{1 + 4x^2}}
\end{align}
then why
$\frac{d}{dx} (1 + 4x^2) = 8x$?
Seems to me that $\frac{d}{dx} (1 + 4x^2)$ has two different answers
Comment: Notice the $2$ on the denominator $2\sqrt{1+4x^2}$disappeared
Comment: It is also 8x in the first example. However due to the 2 in the denominator, 8x/2 reduces to 4x.
Comment: Why do you believe it has two different answers? Where does that belief come from? We can't tell you where you're erring if you don't tell us why you think what you think.
Comment: What I don't get is why $\frac{d}{dx} (1 + 4x^2)$ in the first example is $4x$ but equates to $8x$ in the seconds exmaple
Comment: Because of chain rule. http://en.wikipedia.org/wiki/Chain_rule#First_proof
Comment: I get it... took me a long time to see it, thanks Tianyu
Answer: From
$$\dfrac{1}{2\sqrt{1+4x^2}}\cdot \dfrac{d}{dx}(1+4x^2)$$
you take the derivative in the numerator to get
$$\dfrac{1}{2\sqrt{1+4x^2}}\cdot \dfrac{d}{dx}(1+4x^2) = \dfrac{8x}{2\sqrt{1+4x^2}} = \dfrac{4x}{\sqrt{1+4x^2}}. $$
The $8x$ becomes $4x$ because of the cancellation by $2$ in the denominator.
A property of the derivative is $(f(x)+g(x))' = f(x)'+g(x)'$. So for your example
$$\dfrac{d}{dx}(1+4x^2) = \dfrac{d}{dx}(1)+\dfrac{d}{dx}(4x^2) = 0+ \dfrac{d}{dx}4x^2 = 4\dfrac{d}{dx}x^2 = 8x$$
So they are the same.
Answer: They are the same. Note that in the first derivative, it turned out to be:
$$\frac{d}{dx}\left(\sqrt{1+4x^2}\right)=\frac{\frac{d}{dx}(4x^2)}{2\sqrt{1+4x^2}}$$
$$=\frac{4\cdot \frac{d}{dx}x^2}{2\sqrt{1+4x^2}}$$
$$=\frac{8x}{2\sqrt{1+4x^2}}$$
See how the numerator does turn out to be $8x$, which is what we wanted. But the $8$ turns into $4$ because of the $2$ in the denominator


Regex | Pattern attribute value is not a valid regular expression: Uncaught SyntaxError: Invalid regular expression

Question: I inject some Regex string to input element's pattern attribute via javascript (depending on some form changes out of context) and it works as expected but the thing is, it logs an error to the console when I focus on the input for the very first time.
I've tried to escape the regex as you can see below but then HTML input failed to validate the corresponding value according to the pattern used before.
required regex code
(\(?([\d \-\)\–\+\/\(]+){6,}\)?([ .\-–\/]?)([\d]+))
and that's how i define and inject it via JS
/([\d \-\)\–\+\/\(]+){6,}\)?([ .\-–\/]?)([\d]+)/g
and here's what I tried and failed while trying to escape it for HTML pattern attribute
([\d \-)–+/(]+){6,}\)?([.-–/]?)([\d]+)
I'm really seeking a way to achieve all these without any errors:

regex will be used in JS to match with the input value and only proceed if it's valid
it will also be used in HTML as a pattern attribute to give user feedback about input validation hopefully without any errors like this one; Pattern attribute value /(\(?([\d \-\)\–\+\/\(]+){6,}\)?([ .\-–\/]?)([\d]+))/g is not a valid regular expression: Uncaught SyntaxError: Invalid regular expression: //(\(?([\d \-\)\–\+\/\(]+){6,}\)?([ .\-–\/]?)([\d]+))/g/: Invalid escape
Comment: Before any escaping, your `([\d \-\)\–\+\/\(]+){6,}` makes no sense. You match one or more chars in the char class 6 or more times. What should the pattern match?
Comment: To validate a string, you will need to use `^your_pattern$`, add anchors.
Comment: Thnx for the response @WiktorStribiżew Pattern should match exactly the regex (which addresses the german phone numbers like these https://regex101.com/r/CAVex8/143 ) I'm happy with regex but my input pattern attribute is not :s
Comment: You need `/^\(?[\d +\/()–-]{6,}\)?[ .\/–-]?\d+$/` in `String#match` and `pattern="\(?[\d +\/()–-]{6,}\)?[ .\/–-]?\d+"`
Comment: Why is that? It resolves my needs. I'd love to hear your recommendation that will work well with the pattern attribute.
Comment: I mentioned that it makes no sense to match an *infinite* amount of chars *six or more* times. See my suggestion above.
Comment: Thank you for the suggestion @WiktorStribiżew Somehow i still get an error in console. `Pattern attribute value (?[d +/()–-]{6,})?[ ./–-]?d+ is not a valid regular expression: Uncaught SyntaxError: Invalid regular expression: /(?[d +/()–-]{6,})?[ ./–-]?d+/: Invalid group`
Comment: You are certainly not using them properly. Add the code for each case to the question.
Comment: Anyway, the regexp is not great, as it allows any amount of digits in the string.
Answer: The regex itself is not really validating the phone numbers well, but since you are happy with the pattern, see below how it should be used in JS and HTML5 pattern attribute.
In JS, you need to use

var rx = /^\(?[\d +\/()–-]{6,}\)?[ .\/–-]?\d+$/;
// Test
console.log(rx.test("02162 - 54 91 44 79"));

In a HTML5 pattern attribute, the anchors are redundant and the escaped chars should only be those that are allowed be escaped (i.e. [\(\)] -> [()], etc.):

input:valid {
  color: black;
  border: 5px solid #dadadada;
  border-radius: 7px;
}
input:invalid {
  color: navy;
  outline: none;
  border-color: #ff1050;
  box-shadow: 0 0 10px #ff0000;
}
<form name="form1">
 <input pattern="\(?[\d +\/()–-]{6,}\)?[ .\/–-]?\d+" title="Please enter a valid phone number!" value="(02162) 54 91 44 79" />
 <input type="Submit"/>
</form>
Comment: There, you need `pattern="\s*[A-Za-z]+(?:(?:[.,]? |[-'])[A-Za-z]+)+\.?\s*"` for `name`.  The `phonePattern = new RegExp(/^\(?[\d +\/()–-]{6,}\)?[ .\/–-]?\d+$/);` must be declared as `const phonePattern = /^\(?[\d +\/()–-]{6,}\)?[ .\/–-]?\d+$/;`. And `let resolution = inputValue && !!inputValue.match(this.phonePattern);` must be `let resolution = inputValue && this.phonePattern.test(inputValue);`, but the main trouble is `inputEl.setAttribute('pattern', `\(?[\d +\/()–-]{6,}\)?[ .\/–-]?\d+`);`, it must be `inputEl.setAttribute('pattern', "\\(?[\\d +/()–-]{6,}\\)?[ ./–-]?\\d+");`.
Comment: Ask me a quesion one by one, probably in  chat. There are too many things here. Actually, I do not get it what you mean by *why we have to change the regex string for pattern*. I changed to `^\(?[\d +\/()–-]{6,}\)?[ .\/–-]?\d+$` because hyphens at the end of the character classes does not have to be escaped, `(a+){6,}` makes no sense, anchors are necessary to make the regex be applied to the whole string.
Comment: Thank you for your time. I'll accept your answer but I really wonder what's the problem with my form since I still get this error in console `Pattern attribute value (?[d +/()–-]{6,})?[ ./–-]?d+ is not a valid regular expression: Uncaught SyntaxError: Invalid regular expression: /(?[d +/()–-]{6,})?[ ./–-]?d+/: Invalid group` correspoding html and JS code is in here: https://jsfiddle.net/0td6xrug/2/
Comment: See [this JS fiddle](https://jsfiddle.net/wiktor_stribizew/2ngb37yo/5/)
Comment: Thank you! That pattern worked like a charm now. Since you've got pretty good regex knowledge, can I ask you why we have to change the regex string for pattern? What's the motivation behind it, any links articles are welcome. Once again, thank you very much Wiktor!


How to handle touch event on UIButton added on cell of UITableView?

Question: I m adding UIButton on each cell of UITableView dynamically. I want to handle touch event on this UIButton. Can u plz help me to sort out this issue?
Thanks In Advance,
Vikas
Answer: <code>[myCellButton addTarget:self action:@selector(myCellButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
</code>
Comment: I have added this statement in didSelectRowAtIndexPath method of UITableView but when I touch on Button its not going in didSelectRowAtIndexPath. If I touch cell/row of UITableView outside of button it goes inside didSelectRowAtIndexPath. I  m not getting why  this is happening?.......How to resolve this?
Comment: You would add this target just after the `UIButton` is created, then add the button to the cell when the cell is initialized. The `didSelectRowAtIndexPath` method is for responding to tapping the the cell (row) itself, not the button. This target action is for the button itself. Is this clearer?
Comment: I want to create UIButton on each cell of UITabelView  and  when I click on that UIButton it should change image on UIButton. So where to create UIButton for each cell &  following code so that it will work for each UIButton on every cell of UITableView.                       [myCellButton addTarget:self action:@selector(myCellButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
Answer: If you're doing it all in code...
<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [button setTitle:@"Button" forState:UIControlStateNormal];
        [button addTarget:self action:@selector(cellButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [button sizeToFit];
        [cell.contentView addSubview:button];
    }

    ...

    return cell;
}
</code>
...
<code>- (IBAction)cellButtonPressed:(id)sender
{
    [sender setImage:[UIImage imageNamed:@"newImage"] forState:UIControlStateNormal];
}
</code>
But I would suggest to use a UITableViewCell subclass with delegation.


log.info using log.isInfoEnabled

Question: We are using SLF4J
Based on a recent discussion in the team
if(LOG.isDebugEnabled()){
  LOG.debug("hello " + a + " world" + b);
}

is better than
LOG.debug("hello {} world {}", a, b);

because in the latter case, the String hello {} world {} is created even if "debug" is not enabled. In other words, we are always creating Strings even when it is not required.
I like the latter version as it improves readability significantly.
Can anybody please provide inputs?
Regards,
Shardul.
EDIT
Let me put it differently.
Which is a better approach OR Which is the most widely accepted approach?
Shardul.
Answer: No, the shorter version does not create the "hello {} world {}" string. The string is already created and placed in the constant pool during compilation and class loading. You are always referencing the same instance from the constant pool, it is as cheap as referencing constant int.
But the string is created in the first form since you are using string concatenation.
The only extra overhead is calling LOG.debug with three arguments which does nothing as it  calls isDebugEnabled() internally. Also chances are it will be inlined.
That being said I would go for shorter form in 99% of the cases. The only situation where I would explicitly call isDebugEnabled is when computing the message to be logged has a significant cost:
if(LOG.isDebugEnabled()){
  LOG.debug("hello {} world {}", cheap, veryExpensive());
}

If veryExpensive() is, ekhem, very expensive, then it is smart to avoid calling it if it will be discarded. BTW veryExpensive() should not have any side effects and it is hard to imagine long-running, side-effect free method...
Comment: If you have a "veryExpensive()" then create an anoymous object with a toString() calling veryExpensive() and pass that.
Comment: @ThorbjørnRavnAndersen: Nice trick, however a bit obscure IMHO. In [slf4s](https://github.com/weiglewilczek/slf4s) (Scala wrapper for SLF4J) you can safely call: `LOG.debug("hello " + veryExpensive());` - because the `debug()` argument is a function returning a `String` rather than a `String` itself. That function is only called when logging level is sufficient. So it is pretty similar to your solution - passing a block of code. Pretty neat!
Answer: The performance impact of creating the String would be negligible. But as SLF4J documentation specifies "...this form does not incur the cost of parameter construction in case the log statement is disabled
" meaning that the String is not even created.
After some consideration, the "human overhead", i.e. the importance of code clarity made us decide in favor fo the second example.
More so as there is also overhead involved in calling (and writing and reading) the isXEnabled mehod.

log.info using log.isInfoEnabled


Z-score for binomial distribution does not have $\sqrt{n}$ term

Question: I am looking at Central Limit Theorem. It says that for a series of random sample $W_1,\cdots,W_2$ under the same mean $\mu$ and standard deviation $\sigma$, then the random variable
\begin{equation}
\dfrac{\overline{W}-\mu}{\sigma/\sqrt{n}}
\end{equation}
 follows normal distribution. However, it seems like for Binomial samples, $$\dfrac{\overline{W}-\mu}{\sigma}=\dfrac{\overline{W}-np}{\sqrt{np(1-p)}}$$ is normal. I want to know where the $\sqrt{n}$ term in the denominator went?
Answer: Since the binomial random variable $W$ is the sum of $n$ independent Bernoulli variables, the expression from CLT which is close to the standard normal distribution can be formulated for just one $W$:
$$
\frac{W-np}{\sqrt{np(1-p)}}=\frac{W/n-p}{\sqrt{p(1-p)/n}}.
$$
Here you can interpret $W=X_1+\dots+X_n$ where $X_i$ - i.i.d. Bernoulli variables. For the series of $X_i$ the expression becomes pretty standard:
$$
\frac{X_1+\dots+X_n-np}{\sqrt{np(1-p)}}=\frac{\overline X-p}{\sqrt{p(1-p)/n}}.
$$


Dependence of coin tosses

Question: We are tossing a coin $m$ times
The probability of heads $\Bbb P(H)$ is anywhere in $(0,1)$. It doesn't have to be a fair coin basically.
Random variables $X$ and $Y$ are defined as the total numbers of heads and tails in $m$ tosses.
I am trying to show $X$ and $Y$ are dependent using $\Bbb P(XY)=\Bbb P(X)\Bbb P(Y)$,
but I got stuck on defining $\Bbb P(XY)$.
Comment: Random variables X and Y are defined as the total numbers of heads and tails respectively*
Comment: Suppose that the coin is 80% biased to heads. This means that 80% of the $m$ tosses yield a head.
Comment: Or it means that you'll get heads 8 out of ten times of tossing.
Comment: But one thing : $P(X \text{and} Y) = P(x) \times P(Y|X)$, right ?
Answer: You just need to show that $\mathbb P(X=x,Y=y)\neq \mathbb P(X=x)\mathbb P(Y=y)$ for some $x$ and $y$.
We have that
$$\mathbb P(X=m, Y=0)=\mathbb P(X=m)\neq \mathbb P(X=m)\mathbb P(Y=0)$$

Dependence of coin tosses


Panel data analysis with a lot of missing values and a lot of variables

Question: I want to perform an analysis on panel data I got from an online database. I encounter some problems however. One of them is that the database has a lot of features (110). And the other is that it also contains a lot of missing values. For some of the features the dataset even has more missing values than present values. So my first question is, is it good practice to delete the variables with lots of missing values? And if so, what percentage threshold of missing values is acceptable to still achieve reliable results? Extreme examples: I can imagine that deleting a feature that only has one value for 10,000 observations seems reasonable. After all what does the feature really add to the analysis? On the other hand, I can imagine that deleting a variable with only one missing value for 10,000 observations is very bad practice, since this feature could have still added a lot of information to the dataset (even if you delete the row instead of filling the NA). But where's the turning point? Is there a general rule of thumb?
My next question is, how do we fill in the NAs if we have no information about why they are missing? Is nearest neighbor a reasonable method in this case (and also given the data is panel)? I've read a lot about filling in NAs with the mean, but it seems to me that this ignores the fact that the data is panel, as there might be different trend for each individual over time.
The final question I have is: What are the appropriate order of steps including feature selection? Is it better to first drop the variables with lots of NAs, then feature selection, then filling in NAs in order to save computation, or the other way around because it (perhaps) keeps/adds the most information from the data?
Answer: I think first you would have to diagnose the missing data mechanism (i.e., is it missing completely at random - MCAR, missing at random - MAR, or missing not at random - MNAR).
To illustrate the difference between these three missing data mechanisms, consider the following dataset with the variables disease status, level of exposure, and age. Assume that for some participants, the exposure is missing (e.g., they do have an exposure value, but we do not know what it is).

MCAR: Any two individuals, regardless of their values of disease status, level of exposure, and age, have the same probability of having a missing value for exposure.
MAR: Any two individuals with the same disease status and age have the same chance of having a missing exposure value, regardless of how large or small their actual level of exposure is.
MNAR: Even among individuals with the same disease status and age, the chance of having a missing exposure value depends on their level of exposure.

Generally speaking, MCAR is usually unrealistic, MAR is somewhat plausible, while MNAR is often plausible. As such, MCAR and MAR are typically considered "ignorable" as information about the missing data itself is not included when dealing with the missing data. In contrast, MNAR is typically "non-ignorable" because the missing data mechanism must be modelled while you deal with the missing data.
Finally, you need to know what mechanism you have as this will determine your approach. For example, using multiple imputation (MI) and maximum likelihood (ML), you assume your data is at least MAR. Listwise deletion requires data to be MCAR to reduce/prevent bias in results.
Diagnosing the mechanism: (Source: https://www.theanalysisfactor.com/missing-data-mechanism and https://psyarxiv.com/uaezh)
In the future, it may be worthwhile to consider using methodological approaches to address/plan for missing data in advance of running your research study using planned missingness (see Graham et al. (2006), Rhemtulla & Hancock (2016), Rhemtulla & Little (2012), Wu & Jia (2021)).
Comment: Makes sense, but how can I diagnose the mechanism in place for my dataset? Its just data I found on the internet and have no additional knowledge about. I do trust the data but there is no way in knowing how the missing data became missing. It it national data, so I could imagine that poor countries have less data than richer countries. But is there some way in testing which mechanism applies to my dataset?
Comment: Check out the link below, in the section "diagnosing the mechanism" https://www.theanalysisfactor.com/missing-data-mechanism/
Comment: Thanks for providing this answer, and welcome to Cross Validated! (+1). @Wilko also see Stef van Buuren's [Flexible Imputation of Missing Data](https://stefvanbuuren.name/fimd/), a freely available reference that discusses these issues, several ways to do multiple imputation, and strategies for dealing with MNAR.


Matriz no Forms

Question: Eu estou com dificuldades para criar uma matriz dentro de um JPanel no NetBeans, eu tentei personalizar o código colocando dentro da personalização do NetBeans o código:

           jPanel1.setLayout(new GridLayout(15,15));
           JLabel[][] grid = new JLabel[15][15];
           for(int y=0; y<15; y++){
                   for(int x=0; x<15; x++){
                          grid[x][y]=new JLabel("("+x+","+y+")");
                          jPanel1.add(grid[x][y]);
                   }
           }

Só que não mostra nada, eu queria printar uma matriz na interface pois preciso disso no desenvolvimento de um joguinho.
Comment: Talvez devesse colocar mais do seu código para entender pq que não _printa_ nada, aparentemente esse seu código tb era para funcionar, eu sugeri o MigLayout pois já havia feito um código semelhante com ele antes.
Answer: Como você disse que o programa não printa nada acredito que não é um problema com a escolha do Layout Manager, deve estar faltando adicionar o seu JPanel ao seu JFrame, assim:
setContentPane(jPanel1);

Entretanto, fica minha sugestão de sempre que estiver na dúvida de qual LayoutManager utilizar, vá de MigLayout, por ser mais moderno que os demais, mais flexível e que gera menos código, facilitando caso você precise mexer nas linhas de códigos ao invés de apenas arrastar os componentes. Fonte: MigLayout - Java Layout Manager
Usando MigLayout ao invés do GridLayout seu código ficaria assim:
jPanel1 = new JPanel();
jPanel1.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(jPanel1);
jPanel1.setLayout(new MigLayout("", "[][]", "[]"));
JLabel[][] grid = new JLabel[15][15];
for(int y=0; y<15; y++){
    for(int x=0; x<15; x++){
        grid[x][y]=new JLabel("("+x+","+y+")");
        jPanel1.add(grid[x][y], "cell " + x  + " " + y);
    }
}

Resultado:
Comment: Esse MigLayout é uma biblioteca, ou um programa de Design de Interface Grafica?
Comment: @JoãoCarlos Ele é uma biblioteca, mas isso na verdade é transparente para o desenvolvedor, pois você usa ele assim como qualquer outro Layout Manager. Veja no meu código que estou usando `new MigLayout` ao invés de `new GridLayout`. Esse código funciona para você? Caso negativo, me informe a versão do Java que está utilizando.

Matriz no Forms


Parameterizing an $m$-covered sphere

Question: I will call the $m$-covered circle the map $f:[0,2\pi]\to \mathbb{R}^2$ defined by $f(\theta)=(\cos m\theta,\sin m\theta)$. This is an immersion of the unit circle in $\mathbb{R}^2$. The image of $f$ is the the same as the image of the standard embedding of the unit circle in $\mathbb{R}^2$. However, the difference is that $f$ has degree $m$ as a map $S^1\to S^1$. (Note that $f$ it is not an embedding of $S^1$ in $\mathbb{R}^2$ since $f$ is not injective).
How can I parameterize an $m$-covered $n$-sphere? In other words, I am looking for an immersion $F_m:S^n\to \mathbb{R}^{n+1}$ whose image is the unit $n$-sphere in $\mathbb{R}^{n+1}$ and such that $\mathrm{deg}(F_m)=m$.
My attempt for $n=2$: The standard embedding $[0,2\pi]\times[0,\pi]\to\mathbb{R}^3$ is given by $$(\theta,\phi)\mapsto (\sin\phi\cos\theta,\sin\phi\sin\theta,\cos\phi).$$ Now define $F_m:[0,2\pi]\times[0,\pi]\to \mathbb{R}^3$ by
$$F_m(\theta,\phi)\mapsto (\sin\phi\cos m\theta,\sin\phi\sin m\theta,\cos\phi).$$ Does this work?
Thanks for your help.
Comment: Yes, and that's exactly what I wrote in my answer, before you edited the question, except that (1) my $t$ is your $\cos \phi$, and (2) my answer explains the generalization to higher dimensions.
Answer: You can take the $n-1$-fold suspension of your map. To do so, you'll need to read about suspensions, of course, but that really is the whole story.
For instance, we can write $s_m : S^1 \to S^1$ for the map you called $f$. Writing
$$
S^2 = S^1 \times [-1, 1] / \sim,
$$
where $(P, 1) \sim (Q, 1)$ for any $P, Q \in S^1$, and
where $(P, -1) \sim (Q, -1)$ for any $P, Q \in S^1$. Then the map $s_2$ using coordinates on $S^1 \times [-1, 1]$, is just (the quotient of)
$$
(P, t) \mapsto (s_1(P), t)
$$
Now you can iterate this process to get a map from $S^3 \to S^3$, using essentially exactly the same formula, but replacing $s_1$ with $s_2$, and so on.

Parameterizing an $m$-covered sphere


Is it necessary to scale/process regression targets after PCA?

Question: I have a regression problem where the dimensionality of my targets is too large (40D) so I use PCA to reduce the dimensionality to 15 dimensions. I don't do any more processing to my targets before training, but is it necessary or does it make sense to process the post-PCA targets further?
Answer: If you're wanting to standardize, I would recommend standardizing BEFORE extracting principal components. This can keep scaling differences from weighing some predictors too heavily. At the same time, standardizing may remove important characteristics from the data. It's up to you, but either way, I would do this as a preprocessing step.


Explicit form for $f(n) = 6f(n-1) - 12f(n-2) + 8f(n-3)$ for $n \ge 3, f(0) = 1, f(1) = 0, f(2) = 1$

Question:
Given the recursion
$f(n) = 6f(n-1) - 12f(n-2) + 8f(n-3)$ for $n \ge 3, f(0) = 1, f(1) = 0, f(2) = 1$,
find an explicit form for $f(n)$.

I already solved this excercise in the past, but the solutions I received didn't involve fractions (as they do now), so I believe that I make a mistake at some point.
The equation above is equivalent to
$$f(n+3) - 6f(n+2) + 12f(n+1) - 8f(n) = 0 \ for \ n \ge 0.$$
We identify the polynomial
$$q(z) = z^3 - 6z^2 + 12z - 8 = (z-2)^3.$$
We see that $z = 2$ is the only root with an algebraic multiplicity of $3$, hence, we receive
$$f(n) = (a + bn + cn^2)2^n.$$
Plugging the values in gives us
$$f(0) = a = 1,$$
$$f(1) = (1 + b + c)2 = 0 \equiv 1 + b + c = 0 \equiv c = -1 - b,$$
$$f(2) = (1 + 2b + 4c)4 = 1 \equiv (1 + 2b + 4(-1-b))4 = 1 \equiv -8b = 13 \ \equiv b = - 13/8,$$
which makes $c$ a fraction too. Any ideas were I am wrong here? As I said, I didn't receive any fractions the last time I solved it (but maybe I was actually wrong there, who knows).
Answer: the solution is given by $$a_n=2^{n-3} \left(5 n^2-13 n+8\right)$$ can you get it from here?
Comment: Well, this is exactly the solution I receive when I write $f(n)$ explicitly with the values from above. If this is indeed the correct solution here, I guess I actually made a mistake the last time when I received values without a fraction. Thanks!
Comment: ok the main Thing is you have got your solution


Message Sent To Deallocated Instantce

Question: I'm using game center to send data between two players. For some reason I keep getting a deallocated instance message. Here's the code:
- (void)sendGameMove:(uint32_t)i andj:(NSString *)j {

    MessageMove message;
    message.message.messageType = kMessageTypeMove;
    message.i = 1;
    message.j = @"Testing 1 2 3s";
    NSData *data = [NSData dataWithBytes:&message length:sizeof(MessageMove)];
    MessageMove * messageMove = (MessageMove *) [data bytes];
    NSLog(@"Message I: %i", messageMove->i);
    NSLog(@"Message J: %@", messageMove->j);
    [self sendData:data];

}
(I Filled in the i and j arguments for what i'm passing). In this method the NSLog statements both log what they're supposed to after creating the NSData object but when I sent that NSData object to the method [self sendData:data]:
- (void)sendData:(NSData *)data {
    MessageMove * messageMove = (MessageMove *) [data bytes];
    NSLog(@"Message I: %i", messageMove->i);
    NSLog(@"Message J: %@", messageMove->j);
    NSError *error;
    BOOL success = [[GCHelper sharedInstance].match sendDataToAllPlayers:data     withDataMode:GKMatchSendDataReliable error:&error];
    if (!success) {
        [self matchEnded];
    }

}
In the NSLog statement the first one works fine so I get:
"Message I: 1"

in the console but for the second log statement I get :
"*** -[ respondsToSelector:]: message sent to deallocated instance"

the code to break down the data object is the exact same in the second method as in the first. Any ideas?
Answer: I'm guessing that MessageMove is a struct like:
typedef struct {
    int i;
    NSString *j;
} MessageMove;

The problem is that you're sending only the contents of the struct itself. In memory and on the network, it'd look something like this:
01000000 07FCA700
-----------------
i        j

When the second device receives the message and tries to read the j pointer, it crashes because there's nothing there: that pointer was only valid on the origin device. The struct didn't even contain the contents of the string at all.
To fix this, you need to actually send the string in the message. Flexible array members are one way of storing a string directly in the struct:
typedef struct {
    int32_t i; // explicit integer sizes are a good idea for network protocols
    int32_t j_length;
    char j[]; // the flexible array member
} MessageMove;

Send:
NSString *s = @"Testing 1 2 3s";
NSData *d = [s dataUsingEncoding:NSUTF8StringEncoding];
size_t messageSize = sizeof(MessageMove) + [d length];
MessageMove *mm = calloc(1, messageSize);
mm->i = 1;
mm->j_length = [d length];
memcpy(mm->j, [d bytes], [d length]);
[self sendData:[NSData dataWithBytes:mm length:messageSize]];

Receive:
MessageMove *mm = (MessageMove *)[data bytes];
assert(mm->j_length == [data length] - offsetof(MessageMove, j));
NSString *j = [[NSString alloc] initWithBytes:mm->j length:mm->j_length encoding:NSUTF8StringEncoding];

The assertion prevents reading past the end of the data buffer. offsetof is a macro from <stddef.h>.

For anything more complicated than this, I'd recommend serializing to and sending plist or JSON instead. They handle all the string copying details for you and let you send arrays and dictionary too.
Comment: worked perfectly!!!!! Thank you so much i've had this problem for weeks and no one new the answer!! you're a life saver!!!!!!!!!
Comment: Glad to help! One other suggestion: I'd suggest switching your Objective-C code to compile with ARC. In particular, ARC would have detected storing the `NSString *` pointer in the message struct as potentially unsafe, automatically.

Message Sent To Deallocated Instantce


bash: replace in a string './' for newline

Question: after using find I need to iterate the files
var=`find -name "reg"`
#replace ./ for newline
for file in $var; do
    #something
done

edit: SOLVED with ${string#*/} it takes away the ./
I can survive with that I think
Comment: (1.) `-execdir` is safer than `-exec`.  (2.) `find ... -print0 | xargs -0 ... ` is safer than `-print ...`
Comment: Much easier: `find -name "reg" -exec  \;`. Within "your code", you refer to the current findee as `{}`. Even better is to use `find -name "reg" -print | xargs `, if your command supports that style.
Answer: EDIT:
I am not concerned about how you get the $file, using command line or whatever suits you. I am much more concerned about the #do something part of your question, which I believe is the main question and all those who are posting various find -name 'reg' | xargs ... should think twice before complicating the matters for OP.

use sed
var=`find -name "reg"`
#replace ./ for newline
for file in $var; do
    sed -i 's|\./|\n|g' $file
done

remove the -i options to get output on the screen, if satisfied output is obtained use -i to actually change the line.
On second read, maybe I am replacing the other way round, perhaps you want to replace newline with ./ ? Its bit complicated
sed -i ':a;N;$!ba;s|\n|./|g' $file

as always, test without -i option and then decide if you want to modify the file.
For explanation of second sed magic, read this SO . Its exactly same, except for the ./ character for replace string.
Comment: thanks I solved it with ${string#*/} I'll try to survive with this
Answer: find -name "reg" | while read file; do ...; done

Answer: while IFS= read -r line; do
  var="${line#./}"
  echo "$var"
done < <(find . -name reg -print)

Answer: ok I finally solved it guys, i could delete the ./
string=./blabla/bla
string=${string#*/} #delete stuff until the first / included
echo $string #got blabla/bla
Comment: and what if your string contains `blah./blabla/bla` ? you will lose the first 'blah.' , and it removes the substring, NOT replace it, I think you did NOT explained your question properly
Comment: it will never start with something before ./   find returns ./some/file   ./some/other/file


increase items in shopping cart using rails and redis

Question: I am having trouble increasing the quantity of items in the cart. It will only add one, then the it switches to the 'remove' button. Is there some way I can reconfigure this so I can add more than one of each item?
carts_controller.rb
<code>def add
  $redis.sadd current_user_cart, params[:item_id]
  render json: current_user.cart_count, status: 200
end
</code>
carts.coffee
<code>$(window).load ->
  $('a[data-target]').click (e) ->
    e.preventDefault()
    $this = $(this)
    if $this.data('target') == 'Add to'
      url = $this.data('addurl')
      new_target = "Remove from"
    else
      url = $this.data('removeurl')
      new_target = "Add to"
    $.ajax url: url, type: 'put', success: (data) ->
      $('.cart-count').html(data)
      $this.find('span').html(new_target)
      $this.data('target', new_target)

  $('#mycart .remove').click (e) ->
    e.preventDefault()
    $this = $(this).closest('a')
    url = $this.data('targeturl')
    $.ajax url: url, type: 'put', success: (data) ->
      $('.cart-count').html(data)
      $this.closest('.cart-item').slideUp()
</code>
Answer: I actually figured this out on my own. The items are now being saved to an array, now more than one can be added to the cart. The 'add to' button is also no longer toggling back and forth between 'add to' and 'remove from'. The 'remove' button is now separate.
<code>  def show
   cart_ids = $redis.lrange current_user_cart, -100, 100
   @cart_items = Item.find(cart_ids)
  end

 def add
  $redis.lpush current_user_cart, params[:item_id]
  render json: current_user.cart_count, status: 200
 end

 def remove
  $redis.lrem current_user_cart, 1, params[:item_id]
  render json: current_user.cart_count, status: 200
 end
</code>


Where are the field labels and descriptions stored?

Question: I have been exploring Drupal 8 and it's tables lately. The config table has the storage information serialized as blob. But it doesn't store the Label or Description of a field. Where can one find these data? Is there a core function which helps in fetching all these data for a particular content type?
Comment: As basically everything is an entity (content + configuration) core's [entity api](https://www.drupal.org/docs/8/api/entity-api/introduction-to-entity-api-in-drupal-8) offers everything you need to fetch the data you are interested in.
Answer: You can try something like this :-
<code>$node = \Drupal::routeMatch()->getParameter('node');
if ($node) {
$field_label = $node->field_file->getFieldDefinition()->getLabel();
$field_desc = $node->field_file->getFieldDefinition()->getDescription();
$field_settings = $node->field_file->getFieldDefinition()->getSettings();
}
</code>


How to group_by and summarize multiple variables using regex?

Question: I want to use regex to identify the variable to use to group_by and to summarize my data efficiently. I cannot do separately because I have a large number of variables to summarize and the variable to group_by needs to be passed dynamically each time. data.table accepts using regex to pass the grouping variable, but not the summarizing variables. My attempts so far using tidyverse have been unsuccessful as well. Any help would be much appreciated.
My data:

    tempDF <- structure(list(d1 = c("A", "B", "C", "A", "C"), d2 = c(40L, 50L, 20L, 50L, 20L),
        d3 = c(20L, 40L, 50L, 40L, 50L), d4 = c(60L, 30L, 30L,60L, 30L), p_A = c(1L,
        3L, 2L, 3L, 2L), p_B = c(3L, 4L, 3L, 3L, 4L), p_C = c(2L, 1L, 1L,2L, 1L), p4 = c(5L,
        5L, 4L, 5L, 4L)), class = "data.frame", row.names = c(NA, -5L))

    View(tempDF)
    lLevels<-c("d1")
    lContinuum<-c("p_A", "p_B", "p_C")

My attempts:

    setDT(tempDF)[ , list(group_means = mean(eval((paste0(lContinuum)))), by=eval((paste0(lLevels))))]
       group_means by
    1:          NA d1
    Warning message:
    In mean.default(eval((paste0(lContinuum)))) :
      argument is not numeric or logical: returning NA

    But a single variable works:
    setDT(tempDF)[ , list(group_means = mean(p_A)), by=eval((paste0(lLevels)))]
    setDT(tempDF)[ , list(group_means = mean(p_B)), by=eval((paste0(lLevels)))]
    setDT(tempDF)[ , list(group_means = mean(p_C)), by=eval((paste0(lLevels)))]

Expected output:

    tempDF %>%
    group_by(d1) %>%
    summarise(p_A_mean = mean(p_A), p_B_mean = mean(p_B), p_C_mean = mean(p_C))

    # A tibble: 3 x 4
      d1    p_A_mean p_B_mean p_C_mean
      <chr>    <dbl>    <dbl>    <dbl>
    1 A            2      3          2
    2 B            3      4          1
    3 C            2      3.5        1

Answer: Though it looks a bit roundabout, reshaping this into a long form will allow to group by not only d1 but also by however many values of p_A ... p_C that are in the dataset.
edit: also added code to keep certain columns (d_cols) by regex.
library(tidyverse)

tempDF <- structure(
  list(d1 = c("A", "B", "C", "A", "C"),
       d2 = c(40L, 50L, 20L, 50L, 20L),
       d3 = c(20L, 40L, 50L, 40L, 50L),
       d4 = c(60L, 30L, 30L,60L, 30L),
       d5 = c("AA", "BB", "CC", "AA", "CC"),
       p_A = c(1L, 3L, 2L, 3L, 2L),
       p_B = c(3L, 4L, 3L, 3L, 4L),
       p_C = c(2L, 1L, 1L,2L, 1L),
       p4 = c(5L, 5L, 4L, 5L, 4L)),
  class = "data.frame",
  row.names = c(NA, -5L))

# columns of d to keep, in strings
d_cols <- str_subset(colnames(tempDF), "d[15]")

tempDF %>%
  pivot_longer(cols = matches("p_")) %>%
  group_by(!!!syms(d_cols), name) %>%
  summarize(mean  = mean(value)) %>%
  pivot_wider(id_cols = d_cols,
              values_from = mean,
              names_prefix = "mean_")
#> # A tibble: 3 x 5
#> # Groups:   d1, d5 [3]
#>   d1    d5    mean_p_A mean_p_B mean_p_C
#>   <chr> <chr>    <dbl>    <dbl>    <dbl>
#> 1 A     AA           2      3          2
#> 2 B     BB           3      4          1
#> 3 C     CC           2      3.5        1

Created on 2019-10-19 by the reprex package (v0.3.0)
Comment: Thanks for this, @shiro. I want to pass the grouping variable `d1` dinamically as well. Any thoughts?
Comment: @Krantz. Ok, edited to that effect using non-standard evaluation.
Answer: Im sure this could be made more efficient / succinct but meets the spec:
summarise_df <- function(df, grouping_var){

  # Store string of the grouping var name:

  grouping_vec <- gsub(".*[$]", "", deparse(substitute(grouping_var)))

  # split apply combine summary - return dataframe:

  tmpdf_list <- lapply(split(df[,sapply(df, is.numeric)], df[,grouping_vec]),
                  function(x){sapply(x, function(y){mean(y)})})

}

tmp <- do.call(rbind, summarise_df(df, df$d1))

df <- data.frame(cbind(d1 = row.names(tmp), tmp), row.names = NULL)

With Summary vars dynamic too:
#
summarise_df <- function(df, grouping_var, summary_vars){

  # Store string of the grouping var name:

  grouping_vec <- gsub(".*[$]", "", deparse(substitute(grouping_var)))

  # split apply combine summary - return dataframe:

  tmpdf_list <- lapply(split(df[,summary_vars], df[,grouping_vec]),
                       function(x){sapply(x, function(y){mean(y)})})

}

tmp <- do.call(rbind, summarise_df(df, df$d1, c("p_A", "p_B", "p_C")))

tmp_df <- data.frame(cbind(d1 = row.names(tmp), tmp), row.names = NULL)

Comment: Great. Thanks for this.
Comment: @Krantz No worries !
Answer: The data.table approach is very simple:
library(data.table)

setDT(tempDF)

tempDF[, lapply(.SD, mean),
         by = lLevels,
        .SDcols = lContinuum]

   d1 p_A p_B p_C
1:  A   2 3.0   2
2:  B   3 4.0   1
3:  C   2 3.5   1

Similar approach in dplyr would be:
library(dplyr)
tempDF%>%
  group_by_at(lLevels)%>%
  summarize_at(lContinuum, mean)

# A tibble: 3 x 4
  d1      p_A   p_B   p_C
  <chr> <dbl> <dbl> <dbl>
1 A         2   3       2
2 B         3   4       1
3 C         2   3.5     1

In either case, you can replace lLevels and lContinuum with regex. The dplyr option also would allow for select helpers such as starts_with() and ends_with():
https://www.rdocumentation.org/packages/tidyselect/versions/0.2.5/topics/select_helpers
.


Can someone help solving the 4th order exponential equation subject to the constraint equations?

Question: Let
$$f(x)=\exp\left(\sum_{i=0}^4\theta_ix^i\right).$$
Given the following constraints:

$\int_{-\infty}^\infty f(x)dx=1$
$\int_{-\infty}^\infty xf(x)dx=0$
$\int_{-\infty}^\infty x^2f(x)dx=1$
$\int_{-\infty}^\infty x^3f(x)dx=s$
$\int_{-\infty}^\infty x^4f(x)dx=k$

where $k$ and $s$ are constants, how one would proceed in finding the parameters $\theta_i$ which satisfy these constraints?
Answer: your question reminds me a Gaussian distribution,
\begin{align}
X\sim G(\mu=0,\sigma=1) = \frac{1}{\sqrt{2\pi}}e^{-\frac{1}{2}x^2}
\end{align}
note that the first integral equals to 1 (due to the nature of density function). The second one is the expectation of the random variable that is zero.  the third one is variance that is one. Others are more moments that are finite. Hope it gives some hints to other solutions.
Comment: The problem that needs to be addressed is;                 finding the parameters θi in the first equation given the later five constraint equations which are respectively the 'density function equation, the mean, the variance, the skewness and the kurtosis'.
Comment: Perhaps you could illustrate your approach--which remains unclear--with a worked example?  (In so doing I suspect you will discover unexpected difficulties.)


Every point in open set belongs to component interval

Question: I'm currently self studying analysis, and I'm reading Apostol's Mathematical Analysis, which proves the following statement about component intervals.
Definition of component interval: Let $S$ be an open subset of $\mathbf{R}^1$, An open interval $I \subseteq S$ is a component interval if there does not exist an open interval $J\ne I$ such that $I \subseteq J \subseteq S$.

Statement. Prove that every point of a nonempty open set S belongs to one and only one component interval of $S$.

Proof. Assume $x \in S$. then $x$ is contained in some open interval $I$ with $I \subseteq S$. There are many such intervals but the "largest" of these will be the desired component interval. We leave it to the reader to verify that the largest interval is $(a(x), b(x))$, where $a(x) =$ inf $\{ a: (a,x) \subseteq S\}$ and $b(x) =$ sup $\{ b: (x,b) \subseteq S\}$. (The proof continues...)
This is intuitively true, since any interval greater than this obviously contains points that are not in $S$. I've tried defining such a point but am unable to show that it doesn't lie in $S$. Can someone prove this for me?
Answer: You want to show that for all $\epsilon>0$, neither $I_{\epsilon}:=(a(x)-\epsilon,b(x))$ nor $J_{\epsilon}:=(a(x),b(x)+\epsilon)$ are contained in $S$.
Since $\epsilon>0$, there is a point $y\in\mathbb{R}$ with $a(x)-\epsilon<y<a(x)$. Since $y<a(x)$, it follows by the definition of the infimum that $(y,x)$ is not a subset of $S$. Since $a(x)-\epsilon<y$, $(y,x)\subset I_{\epsilon}$.  Therefore, $I_{\epsilon}$ cannot be a subset of $S$.
Similarly, one can show that $J_{\epsilon}$ is not a subset of $S$.
Comment: Well, let's suppose that $(y,x)\subset S$. Then, $y\in\{a:(a,x)\subset S\}$. But then $a(x)\leq y$, by the fact that $a(x)$ is the infimum of the set $\{a:(a,x)\subset S\}$. Thus, we have a contradiction since we also have that $y<a(x)$.
Comment: Thanks a lot. Exactly which part of the definition of infimum shows that $(y,x)$ is not a subset?
Comment: (+1) Of course this reasoning implicitly assumed that $S$ is bounded so are the intervals $(a(x),b(x))$.


Android: Changing selected menu item

Question: I am trying to change the selected menu item of a BottomNavigationView from a seperate fragment from the one that I initialize the BottomNavigationView in. I am using
MenuItem item = navigationView.getMenu().findItem(R.id.nav_home);
item.setChecked(true);

The problem is that the navigationView is null because I am in a seperate fragment.
I am using
navigationView = view.findViewById(R.id.navigation); to get the id of the navigationView.
Answer: here when you use view.findViewById(R.id.navigation);, the view is representing the view of that separate fragment, which doesn't have such a view , hence it will return null.
Comment: Ok, thank you. But when I take away the view in front of findViewById, I am getting this: `cannot resolve method 'findViewById' in 'UsersFragment'`
Comment: https://stackoverflow.com/questions/6495898/findviewbyid-in-fragment explained here.

Android: Changing selected menu item