The test statistic in the likelihood ratio test for nested linear models

Question: Imagine that we have a family of probability disributions with p.d.f $f_{\theta}(z)$ where
$\theta \in \Theta$. We also know that there is a linear dependence between parameters. As a consequence we can restrict to a nested model with p.d.f $f_{\theta}(z)$, where $\theta \in \Theta_{0} \subseteq \Theta$.
Formally we have such a situation:
\begin{align}
\Theta \subseteq \mathbb{R}^p,~~~~ h:\mathbb{R}^p \to \mathbb{R}^{p-q},~~~~  \Theta_{0} = \{\theta \in \Theta : h(\theta)=0\}.
\end{align}
where h is a linear map onto $\mathbb{R}^{p-q}$ so we can say that:
\begin{align}
h(\theta) = A\theta  = 0,
\end{align}
where $A$ is a $(p-q) \times p$ matrix of a linear map $h$.
As a result we can say that $\Theta_{0} \subseteq \mathbb{R}^q$. HERE BEGINS MY PROBLEM.
I would be very grateful if someone could tell me why we can conclude now that
\begin{align}
\sup \limits_{\theta \in \Theta_{1}}f_{\theta}(z) \overset{\huge{?}}{=} \sup \limits_{\theta \in \Theta}f_{\theta}(z).
\end{align}
Consequently the test statistic of a likelihood ratio test is
\begin{align}
\lambda(z) = \frac{\sup_{\theta \in \Theta_{1}}f_{\theta}(z)}{\sup_{\theta \in \Theta_{0}}f_{\theta}(z)}\overset{\huge{?}}{=} \frac{\sup_{\theta \in \Theta}f_{\theta}(z)}{\sup_{\theta \in \Theta_{0}}f_{\theta}(z)}.
\end{align}
Answer: There is some confusing (to me) notation in your question. If the parameter vector $\theta$ belongs to the $p$-dimensional space $\Theta$ then it is not $\theta$ again that belongs to the $q$-dimensional subspace $\Theta_0$. This is not an issue of values-taken, but of dimensions. (Also it seems that you suddenly change the parameter vector subscript from $0$ to $1$ in the $\sup$ expression).
I understand your question as follows: By assumption, part of the parameters is  a function of the rest. Denote the sub-vector containing the "dependent" elements of the $\theta$ vector as $\theta_{p-q}  \subseteq \mathbb{R}^{p-q}$, and the "independent" parameter vector as $\theta_q\subseteq \mathbb{R}^{q}$. We then have $\theta_{p-q} = g(\theta_q)$.
Then your likelihood function can be written as
$$f(z;\theta) = f(z;\theta_{p-q} , \theta_q) = f(z;g(\theta_q) , \theta_q) $$
Given the assumption of functional dependence among parameters, I believe you don't need to "prove" in any other way that the RHS is the same as the LHS, and so that they will have the same extrema.
The $\sup$-equality expression that you questionmark may be misleading because it could be taken to imply that it holds, irrespective of the existence of the functional dependence, because it does not "reveal" the functional dependence among the parameters. A more clear expression would be
$$  \sup \limits_{\{\theta_{p-q}\}\cup \{\theta_q\} =\theta \in \Theta}f(z;\theta_{p-q} , \theta_q)  \;\;\text{s.t.}\;\; \theta_{p-q} = g(\theta_q)  $$ $$=\sup \limits_{\theta_q \in \Theta_{0}}f(z;g(\theta_q) , \theta_q) $$
In other words, you just transform a maximization problem with equality constraints into an unconstrained maximization problem by inserting the constraint into the objective function.


Pulumi and AKS : Public IP not linked to AKS load-balancer

Question: trying, using pulumi, to setup and AKS cluster with a public ip as load-balancer and a domain name.
I tried several options using the following project : https://github.com/hostettler/pulumi-az-test
I end up with a working AKS cluster (great!) ,  that has a load-balancer (amazing!), on a public ip (fantastic!),  but with an fqdn that is not linked to the public ip of the load-balancer (huh!).
I tried to

extract the public ip to force the domain but I did not manage to do it. I get the resource id of the public id created but I cannot cast it
as a public ip object to set the domain. Meaning how to load a public ip object from a public ip resource-id.
"/subscriptions/XXXXXX-XXX-XX-XXXx-XXXXXXXXXXXX/resourceGroups/MC_XXXXX_XXXXX_aksCluster5632b82_eastus/providers/Microsoft.Network/publicIPAddresses/XXXXX-XXXX-XXX-XXX-XXXXXXXXX"
tries to add a public ip to the cluster but that ip, while having a good fqdn is not used by the load-balancer

Any idea on how to address? Solving either would be ok with me.
Thanks a lot in advance
Comment: Can you share the code you used to provision the cluster?
Comment: @jaxxstorm : you do not have access to the link in the message? https://github.com/hostettler/pulumi-az-test it should be public. Let me double check
Answer: found the problem (or rather a work around). The problem stems from the helm chart I was using. The bitnami nginx chart seemed to ignored the controller.service.loadBalanceIP. Therefore, I replaced it by the ingress-nginx.
Thus, replacing
chart: "nginx",
version: "13.2.10",
fetchOpts: {
    repo: "https://charts.bitnami.com/bitnami",
},

by
chart: "ingress-nginx",
version: "4.3.0",
fetchOpts: {
    repo: "https://kubernetes.github.io/ingress-nginx",
},

solved the problem. Instead of recreating an external ip address for each deployment, it used the one provided in controller.service.loadBalanceIP that is static and with the proper A record.
import * as azure from "@pulumi/azure";
import * as k8s from "@pulumi/kubernetes";
import * as pulumi from "@pulumi/pulumi";
import * as config from "./config";
import * as azuread from "@pulumi/azuread";

const current = azuread.getClientConfig({});

// Create a Virtual Network for the cluster
const aksVnet = new azure.network.VirtualNetwork("aks-net", {
    resourceGroupName: config.resourceGroup.name,
    addressSpaces: ["10.2.0.0/16"],
});

// Create a Subnet for the cluster
const aksSubnetId = new azure.network.Subnet("aks-net", {
    resourceGroupName: config.resourceGroup.name,
    virtualNetworkName: aksVnet.name,
    addressPrefixes: ["10.2.1.0/24"],
    serviceEndpoints : ["Microsoft.Sql"],
},
{dependsOn: [aksVnet]}
);

// Now allocate an AKS cluster.
export const k8sCluster = new azure.containerservice.KubernetesCluster("aksCluster", {
    resourceGroupName: config.resourceGroup.name,
    location: config.location,
    defaultNodePool: {
        name: "aksagentpool",
        nodeCount: config.nodeCount,
        vmSize: config.nodeSize,
        vnetSubnetId: aksSubnetId.id,
    },
    dnsPrefix: `${pulumi.getStack()}-reg-engine`,

    linuxProfile: {
        adminUsername: "aksuser",
        sshKey: {
            keyData: config.sshPublicKey,
        },
    },
    networkProfile: {
        networkPlugin : "azure",
        loadBalancerProfile: {
            managedOutboundIpCount: 1,
        },
        loadBalancerSku: "standard",
        outboundType: "loadBalancer",
    },
    identity: {
        type: "SystemAssigned",
    },
},
{dependsOn: [aksSubnetId]}
);

const publicIp = new azure.network.PublicIp("app-engine-ip", {
    resourceGroupName: k8sCluster.nodeResourceGroup,
    allocationMethod: "Static",
    domainNameLabel : "app-engine",
    sku : "Standard",
    tags: {
        service: "kubernetes-api-loadbalancer",
    },
},
{dependsOn: [k8sCluster]}
);

// Expose a K8s provider instance using our custom cluster instance.
export const k8sProvider = new k8s.Provider("aksK8s", {
    kubeconfig: k8sCluster.kubeConfigRaw,
});

const clusterSvcsNamespace = new k8s.core.v1.Namespace(
    config.namespace,
    undefined,
{ provider: k8sProvider });
export const clusterSvcsNamespaceName = clusterSvcsNamespace.metadata.name;

const regEngineIngress = new k8s.helm.v3.Chart(
    "sample-engine-ingress",
    {
        repo: "kubernetes.github.io",
        chart: "ingress-nginx",
        version: "4.3.0",
        fetchOpts: {
            repo: "https://kubernetes.github.io/ingress-nginx",
        },
        namespace: clusterSvcsNamespace.metadata.name,
        values: {
            controller: {
                replicaCount: 2,
                nodeSelector: {
                    "kubernetes\.io/os": "linux",
                },
                service: {
                    loadBalancerIP: publicIp.ipAddress,
                }
            }
        },
    },
    { provider: k8sProvider },
);

export let cluster = k8sCluster.name;
export let kubeConfig = k8sCluster.kubeConfigRaw;
export let k8sFqdn = k8sCluster.fqdn;
export let externalIp = publicIp.ipAddress;


How to identify and name Full Diminished Seventh Chords?

Question: I made a frightening discovery -- No mater what inversion diminished seventh chords are in, all of the notes are the same interval apart! A minor 3rd. How then is someone to identify what name the chord has? Here is an example from Jesus Paid it All, a song I'm trying to transpose to F.
The chord in question falls on the 3rd beat in the first measure of the 3/4 section -- over "He". The song, and you can't see this in the image, is in Db major.

So Diminished 7 chord here, with the notes listed top to bottom as displayed here, goes
`Db`
`Enat`
`Bb`
`Gnat`

If I were to rearrange these into a more directly transferrable to the keyboard way,
`Gnat`
`Bb`
`Db`
`Enat`

But I can also rearrange the notes like this:
`Enat`
`Gnat`
`Bb`
`Db`

Or however you please...
So heres the question: How do I name this chord? Using Roman Numeral notation, how would I write it for transposition?
Comment: Look at the spelling carefully. A dim 7th *in root position* is a stack of *thirds*. So Gnat Bb Db Enat is *not* in root position, though Gnat Bb Db Fb would be, and so is Enat Gnat Bb Db. Of course there are several different spellings of the same chord - e.g. A# C# E G - and any of the 4 notes can be spelled as the root. That's one reason why dim 7 chords are so useful for making *modulations* between "remote" keys.
Comment: That's the thing about fully dim7:  you can "escape" it to almost any chord :-)
Answer: I would call this a viio7/V chord because of the function and the context of the surrounding chords. The bass note (a G) leads into a V chord (Ab).
To understand the function of the diminished chord, the first step is to determine what chord(s) are in the penultimate measure, so that we know how the diminished chord resolves. In the final measure, there is a I resolution, and the entire penultimate measure is the V chord. Rather than describe this measure as one beat of I6/4 followed by three beats of V, my inclination is to call the entire measure the V chord--a cadential 6-4 progression.
So the final two bars are V-I. The diminished chord has a G in the bass, and it leads to a V chord. This makes it a viio7/V chord, and the progression is IV-viio7/V-V-I.
Comment: Agreed on all counts. It might be worth adding a discussion of spelling here. Any of the four notes of a fully-diminished seventh could be made into a root by different spellings, technically this chord "should" have an Fb instead of E natural. However, notators often use easier-to-read spellings than function would strictly call for.
Comment: I don't like this interpretation. Starting at the diminished 7th, I see G°7-Db/Ab-Ab7 chords-wise. This is vii°7/V-I 6/4-V7 in D flat major, not something that starts with i°7.
Comment: @Dekkadeci, I listened to the song and I agree. I would call the Db/Ab a cadential 6 4 chord, making it part of the V chord (with a double suspension). That would make the diminished chord a Go7 chord leading to the Ab (6-5, 4-3) chord.
Answer: The best way to handle symmetric chords (fully diminished seventh chords or augmented chords) is to check how they are used (good idea with other chords too.) There are two easy to find uses. One is in  a sequence (like if one had C7, F7, xx, e7, a7, d7 G7) one could easily guess that the xx is some type of diminished B chord. The other way is to see if the chords acts like some type of dominant ninth with the root missing. For example, B-D-F-Ab may be treated as a G-ninth with the root missing; particularly if preceded by some type of D-minor harmony and followed by some type of C harmony. Another use is just as a bunch of connecting notes with no particular harmonic significance.
Comment: Note the final two lines of the post: "So heres the question: How do I name this chord? Using Roman Numeral notation, how would I write it for transposition?"
Answer: You identify what Roman numeral notation label a diminished 7th chord should have through context. People can easily use inversions of diminished 7th chords, use root diminished 7th chords in unusual contexts (common-tone diminished 7ths are particularly evil for this), and use diminished 7th chords to modulate between keys (so a single diminished 7th chord can have multiple valid Roman numeral notation labels!).
In this case, your target diminished 7th chord is immediately preceded by a Gb chord (I'm assuming that the F is a passing tone) and followed by a Db/Ab chord, then a Ab7 chord. Your target diminished 7th chord has a G natural for a root--this is consistent with it being vii°7/V (note that V of Db major is Ab major), and the Db/Ab-Ab7 chord progression (I 6/4-V7 in Roman numeral notation) confirms this. (The Gb--or IV--chord beforehand also supports this, as it indicates that the music hasn't strayed from Db major at this point.) The E natural in the diminished 7th chord is just to make the sheet music easier to sight-read.
Answer: I would write it as Gdim7.
If we take the bass line only from the beginning to the end of the above screenshot (taking into account that the whole tune is in Db major), it is:
| Db Db Db Db Db F | Gb G | Ab Ab Ab Ab | Db |
Then on top of bass G you've got notes Bb-E-Db which is an inversion of the Gdim7 chord.
If we add the chords the harmony can be described as:
| Db Gb/Db Db Db Db Dbmaj7/F | Gb Gdim7 | Db/Ab Ab Db/Ab Ab | Db |
In this case Gdim7 acts as a dominant or a passing diminished chord (#ivo7).
If you think of it, if it was Gb and not G in the bass, then it would be Gb-Bb-E-Db = Gb-Bb-Fb-Db which is exactly Gb7. But our composer decided to add a bit more tension keeping the dominant chord, but lifting the bass by 1/2 tone, which eventually adds more beauty in the music and it seems apparently typical for Gospel style music, as mentioned here:  http://iujazztheory.weebly.com/passing-diminished-chords.html
Comment: This was actually the first conclusion that I came to, but I wanted to ask about it as well. Not that that makes it right, necessarily, but this certainly works for transposition.


Equivalent of loginViewShowingLoggedInUser

Question: I am trying to migrate my app from Facebook SDK 3.4 to 4.x.
I used the following import
   #import <FBSDKCoreKit/FBSDKCoreKit.h>
   #import <FBSDKLoginKit/FBSDKLoginKit.h>
   #import <FBSDKLoginKit/FBSDKLoginButton.h>

I used to have two methods
- (void)loginViewShowingLoggedInUser:(FBLoginView *)loginView

- (void)loginViewFetchedUserInfo:(FBLoginView *)loginView user:(id<FBGraphUser>)user

I can't find these methods in 4.x SDK.
I can see FBLoginView changed to FBSDKLoginButtonDelegate. But what is the equivalent of above two methods. I tried looking at Facebook iOS samples but could not figure it out.
Answer: There's a method called loginButton:didCompleteWithResult:error: defined in FBSDKLoginButtonDelegate :
- (void) loginButton:(FBSDKLoginButton *)loginButton
didCompleteWithResult: (FBSDKLoginManagerLoginResult *)result
               error: (NSError *)error;

Source : Facebook SDK Docs
Note : The above delegate is only for a login button, i.e. the delegate will be called only when the user performs a login using the login button. So this delegate will not get called every time the app is launched like loginViewShowingLoggedInUser: used to do.
You have to use FBSDKLoginManager to check if user is aleady logged in :

FBSDKLoginManager works directly with [FBSDKAccessToken currentAccessToken] and sets the currentAccessToken upon successful authorizations (or sets nil in case of logOut).
You should check [FBSDKAccessToken currentAccessToken] before calling logIn* to see if there is a cached token available (typically in your viewDidLoad).

As for retrieving user info, the new SDK does not automatically fetch user info. inside you login success handler, you have to make a graph request :
NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
[parameters setValue:@"id,name,email,gender" forKey:@"fields"];
[[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:parameters]
 startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
     if (!error) {
         NSString *userID = [[FBSDKAccessToken currentAccessToken] userID];
         NSString *userName = [result valueForKey:@"name"];
         NSString *emailid=[result valueForKey:@"email"];
         NSString *gender=[result valueForKey:@"gender"];
         NSString *userImageURL = [NSString stringWithFormat:@"https://graph.facebook.com/%@/picture?type=large", [[FBSDKAccessToken currentAccessToken] userID]];
     }
     else{
         NSLog(@"%@",error.localizedDescription);
     }
}];

Comment: Thanks. Will this method be called when a user has already logged in and it is showing the current logged in user.
Comment: This method will not be called if when you launch the app and the user is already logged in. I will update answer
Comment: Awesome. Thanks a lot.


Access hook_preprocess_node variables from page controller

Question: I have a custom controller created for a custom URL, where the URL is a URL for an existing node with an additional parameter. The display for the URL defined by the controller needs to use the the same template for the base node route, and the controller just uses a service to get additional data and merge it with the base node data.
To be more specific, I have a node type called product_group. It has an entity reference field called field_products that attaches commerce_product entities. The URL alias pattern for product_group nodes is /products/[node-title]. My controller is for the URL /products/[node-title]/[sku], where sku is the commerce_product sku. The controller gets the data from the URL, loads the base product_group node object, uses the sku value to get the commerce_product object, and then I have a custom service that gets a bunch of additional data from the product and associated variation.
The tricky part is that the display at the /products/[node-title]/[sku] URL is the same as the display at the /products/[node-title] URL, with some additional data from the product itself added in. Therefore, I need to get all of the $variables data that is available in hook_preprocess_node() function in my controller and add my new data on top of it. The problem is, I can't figure how to access it. From what I've seen, you can't access data in a preprocess hook directly from a controller, but I'm guessing there has to be some way I can render the product_group node and get the variables that are available in hook_preprocess_node. Am I correct, and if so, how do I do it?
Comment: Are there specific variables you want? my first thought is that preprocess is theme layer, and controller is below that, so they probably don't share any information.
Comment: What exactly you want to access there? Can't you simply retrieve it from the node object in the controller?
Comment: No, all I really want is what is available as the `$variables` parameter that is available in the preprocess function - I don't want to have to re-create the wheel and generate it all myself again.
Comment: Yeah, basically just the `$variables['content']`element.
Answer: So the problem turned out to be an incorrect #theme template name in my returned render array. The node type I was adding content to was called product_group, but in my controller, I returned this:
 return [
   '#theme' => 'node__product_resource__full',
   '#product_group' => $content,
   '#node' => $pg_node,
   '#view_mode' => 'full',
 ];

product_resource is a valid content type in the site. Once I changed it to
'#theme' => 'node__product_group__full',

It worked fine.
Comment: Don't forget to accept your answer.
Comment: I will when it allows me to. I have to wait 2 days, and as of now, I can't do it until tomorrow.


Sobrescrever CSS de compontente calendar no Richfaces

Question: Estou usando um componente calendar porém somente a data (omitindo a hora), e sobrescrevendo o CSS pra reduzir o tamanho em tela. Segue abaixo:
<rich:calendar value="#{_sessao.dtSessao}" showFooter="false" enableManualInput="true" locale="pt_BR" datePattern="dd/MM/yyyy" style="width:80px;"/>

Porém, não está aplicando.
Até aonde sei, em JSF, Primefaces e similares, está certo.
Comment: qual a versão do richfaces ?
Answer: Localizei a solução, que era relativamente simples, mas como eu não utilizo o Richfaces tive que ver os componentes que ele contém.
Ao invés de utilizar:
<rich:calendar ... style="width:80px;"/>

Verifiquei que existe a tag inputStyle que resolveu diretamente no componente, exatamente como o style faz no JSF, ficando então:
<rich:calendar ... inputStyle="width:80px;"/>

Verifiquei e existem outros casos parecidos no Richfaces, então é interessante verificar cada componente pois a solução pode ser similar.
Answer: Amigo o ideal era fazer essa modificação de script em um css. Pois esse componente gera diversos codigos HTML para o efeito.
de uma olhada na documentação e verifique a parte que você deseja alterar o estilo.
Também verifique nos estilos aplicados se não tem nenhum outro estilo sendo sobreescrito.
Lembre-se css com !important tem precedencias até sobre estilos do atribulo style.
Exemplo:
Tendo o calendario
<rich:calendar value="#{calendarBean.selectedDate}" id="calendar" locale="#{calendarBean.locale}"
  popup="#{calendarBean.popup}" datePattern="#{calendarBean.pattern}"
  showApplyButton="#{calendarBean.showApply}" cellWidth="24px" cellHeight="22px"
  style="width:200px" disabled="#{calendarBean.disabled}">
</rich:calendar>

E um css de alteração de fonte:
    .rich-calendar-tool-btn {
      font-family: Arial, Verdana;
    }

Comment: obrigado pela ajuda, mas vi a solução que postei abaixo, que acaba sendo mais simples.
Comment: Sim. só não é uma boa pratica misturar o css junto ao código.
Comment: concordo contigo dependendo da situação, pois como é um ajuste simples, me parece mais interessante agir assim do que criar um _CSS_ à parte, mas em casos que requerem mais customização ou aplicação em diversos lugares, realmente é mais adequado para deixar o código mais limpo. No meu caso preferi diretamente no componente pois ele é utilizado em outros pontos da tela, que não necessitavam desta alteração.


SQL show only results that have both items

Question: I have a SQL table with names and fruits that the persons ate.
I only want the result to show the Names of people who ate both an apple and a banana. But if i use "Where Item='Banana' and item='Apple', the data shows nothing.
If i use: Where item in('banana','apple'), it shows the result as shown in the table.

Name
Item

John
Apple

David
Banana

John
Banana
Comment: GROUP BY, HAVING
Comment: Which DBMS product are you using? "SQL" is just a query language used by all relational databases, not the name of a specific database product. Please add a [tag](https://stackoverflow.com/help/tagging) for the database product you are using. [Why should I tag my DBMS](https://meta.stackoverflow.com/questions/388759/)
Answer: You can use DISTINCT with an EXISTS clause to get what you need.
SELECT DISTINCT name
           FROM table1 a
          WHERE a.Item = 'Apple'
            AND EXISTS (SELECT *
                          FROM table1 b
                         WHERE b.Item = 'Banana'
                           AND b.Name = a.Name)

Answer: WITH CTE_Apple AS
(
    SELECT * FROM Table where Item = 'Apple'
)
,
CTE_Banana AS
(
    SELECT * FROM Table WHERE Item = 'Banana'

)
SELECT
           A.Name
FROM
           CTE_Apple AS A
    JOIN
           CTE_Banana AS B ON B.Name = A.Name

Basically create two sub-sets of the data and join them together where the data intersects.  There are plenty of other ways to do this but I find CTE (Common Table Expressions) the most elegant
Answer: Using a subquery should work in any RDBMS:
select distinct Name
from table_name
where Item = 'Apple'
and Name in
(select Name from table_name where Item = 'Banana');

Answer: We can do a GROUP BY and then select only the person who has eaten 2 fruits from the list, ie both of them

CREATE TABLE eaten(
person VARCHAR (10),
fruit VARCHAR (10));

INSERT INTO eaten VALUES
('John','apple'),
('Bill','apple'),
('Bill','pear'),
('David','banana'),
('David','banana'),
('John','banana');

SELECT person
FROM eaten
WHERE fruit IN ('apple','banana')
GROUP BY person
HAVING COUNT(DISTINCT fruit) =2;

| person |
| :----- |
| John   |

db<>fiddle here


Grabbing value from column and show everything from that row depending if value is correct (LINQ - c# web API)

Question: I have a database that looks something like this:
[ID] [5TypeOfIntegers] [TEXT] [name ID]

5TypeOfIntegers has 5 integers. ( 1 - 5).
I wanna grab 2 values from my 5 types(value 2 and 4), and grab the data if name ID match, the other 3 values (values 1,3 and 5) I wanna grab that data if the name ID does not match.
Example:
[ID] [5TypeOfIntegers] [TEXT] [nameID]  = User logged is 1.
 0         2             bla     1         - GRAB DATA (Type is correct and user is correct))
 1         3             bla     1         - DONT GRAB DATA (Type is wrong and user is correct)
 2         3             bla     2         - GRAB DATA (Different ID from the person logged in, Type is correct)

My idea of LINQ code is something like:
db.Where(e => e.nameID == 1).Select( e => e.5TypeOfIntegers == 2 && e.5TypeOfIntegers == 4)

But after that I'm kinda lost and that doesn't even work. :(
Thanks for the help!
Comment: So, to be clear, you have the Column `5TypeOfIntegers`. You want to rows with 2 and 4 if the NameId matches the NameID you supply, and then grab rows with 1, 3, and 5 when the NameID does not match what you supply. In that case, you could do something like (where the nameID you pass in is nameIdVar `db.Table.Where(e => (e.5TypeOfInterger in (2, 4) && e.nameID = nameIdVar) || (e.5TypeOfInterger in (1,3,5) && e.nameID != nameIdVar)`
Comment: What @chadk said is literally what you asked for not IMO either the question is unclear or it's https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem, can you please elaborate on what is the use case?
Answer: So, in other words you want "not(type 1,3,5 and nameId = currentlyloggedin)"
var types = new[]{1,3,5};
context.Whatever.Where(x => !(types.Contains(x.Type) && x.UserId == currentlyLoggedInUserId));


Exponential irrationality

Question: I want to prove that there are only finitely many rational solutions to
$$\left|\frac{\log(5)}{\log(7)}-\frac{a}{b}\right|\le \frac{1}{7^b}$$
And once I have done this, I would like to put a bound on how many solutions there are. Any thoughts?
Edit:
Since for any $x$ and large $b$, $7^b>b^x$, if my equation has infinitely many solutions, then
$$\frac{\log(5)}{\log(7)}$$
Must have infinite irrationality measure. Can we prove this isn't true?
Comment: what is the source of the problem? And, what is your background as relates to this one?
Comment: What do you mean by *rational solutions*? You mean that $a,b\in\mathbb Q$ or $a,b\in\mathbb N$?
Comment: @YiorgosS.Smyrlis, these will be convergents of the simple continued fraction for the irrational target number given (that is $a,b$ positive integers). There probably are none satisfying the inequality, which is very strong.
Comment: Chances are, your number has irrationality measure 2 --- almost all number do --- but I doubt there's a proof known for your number.
Answer: Assuming $a,b$ are integers, it can be verified by brute-force search that if there are any solutions, then $a\ge4000$ or $b\ge2000$.
Checked with Mathematica with following code:
Monitor[Do[If[Abs[Log[5]/Log[7] - a/b] <= 1/7^b, Print[{a, b}]], {b, 1, 1999}, {a, 1, 3999}], {b, a}]

Using Will Jagy's advice, checking continued fractions up to 19 terms no solutions found (more than 19 terms Mathematica overflows).
Do[t = FromContinuedFraction@ContinuedFraction[Log@5/Log@7, a]; If[Abs[Log@5/Log@7 - t] <= 1/7^Denominator@t, Print@a], {a, 1, 19}]

Comment: Theorem 19 in Khinchin's little book, if the absolute value is less than $1/(2 b^2)$ for coprime $a,b,$ then $a/b$ must be a continued fraction convergent of the irrational, here $\alpha = \frac{\log 5}{\log 7}$
Comment: So to prove there are no solutions we must examine the CF? How could one prove that no convergent satisfies our condition?
Answer: I believe Bakers theorem can put a bound on the number of solutions to this equation.

Exponential irrationality


VAR lag selection heavily depends on maximum lag investigated

Question: I am fitting an Error Correction Model with two monthly price time series.
In Stata I am using the varsoc command to determine the number of lags that are appropriate.
varsoc variable1 variable2

If I run varsoc with the default 4 maxlags, the suggested lag length using AIC/FPE is 3.
However, if I run varsoc with maxlag(12) option, 12 lags are suggested.
If I use maxlag(20), 13 lags are suggested.

Why is varsoc so sensitive to the number of maxlag?
If this is the case, how should I decide which maxlag to use? Running varsoc on the time series seperately yields 8 lags (if a larger maxlag is chosen).
Comment: Regarding the close vote, I don't think this question belongs to Stack Overflow because the issue seems to be statistical rather than programming-specific. Regarding error correction model, it seems to be vector error correction model (VECM) rather than single-equation error correction model (ECM); if this is so, I suggest editing the post accordingly.
Comment: Low, let me know if something is still unclear. Otherwise, consider accepting the answer.
Answer: The function varsoc considers full (unrestricted) VAR or VECM models with lags 1 through maxlag. It may happen that the user sets maxlag to a relatively low number such that the best model in AIC or FPE sense is excluded. This seems to be happening for maxlag(4) and maxlag(12). However, I suspect the AIC- or FPE-suggested lag order would not grow infinitely. It might just be the case that a VAR(13) model fits the data relatively better than a VAR(3) or VAR(12), even after penalizing the number of parameters in the model. You should also not be surprised that a VAR(3) is selected rather than a VAR(4) when you set maxlag(4). AIC and FPE need not decrease monotonically until the "optimal" lag and increase monotonically after that.
If you think that a VAR(13) is nonsensical and the lag order is too high, then perhaps you have excluded a relevant variable or neglected seasonality or a structural change, or the model suffers from yet another fault.


Estou com um problema no meu repositório no Github - Diretórios vazios

Question: Estou com um problema depois de enviar meu projeto no Github, que contem dois diretórios. No entanto após enviar e fazer o commit, o repositório no Github fica com as pastas vazias e com uma setinha. O que pode ter acontecido. Detalhe: já removi a pasta .git da raiz e fiz tudo de novo, mas continua dessa forma:
Answer: Verifique se dentro da sua pasta (backend e frontend) têm um diretório .git.
Caso você tenha, é considerado um Git aninhado, pois o SHA1 é registrado com um gitlink.
O que você vê no GitHub é o gitlink. Isso é usado para submodulo também.
Para resolver então:

remova o .git dentro do diretório backend
remova o .git dentro do diretório frontend
o .git do diretório principal (seu root) não deve ser removido
Comment: Era isso mesmo amigo. Obrigado


Find a group to which $A_4/V_{4}$ is isomorphic

Question: I have a question that states to find a familiar(fairly common) group that is isomorphic to $A_4/V_{4}$, where $V_{4}$ is the Klein-4 group.  I am probably just having a mental break, but either the answer or some guidance to get to a possible solution would be greatly appreciated.
Thanks
Answer: Hint: the order of $A_{4}/V_{4}$ is $12/4 = 3$. How many groups of order $3$ are there up to isomorphism? (Feel free to comment if you need more).
Comment: So would it be $\Z / 3 \Z$?
Comment: @BrandonKlein: indeed, the only group of order 3 up to isomorphism is the cyclic group of order $3$, $\mathbb{Z}/3\mathbb{Z}$.


Não consigo utilizar o método FirstOrDefault em um tipo IWebElement

Question: Não estou conseguindo utilizar o método FirstOrDefault com o selenium
public IWebElement RetornaRegistro(string titulo)
{
    var trs = _driver.FindElement(By.CssSelector("table tbody tr"));
    var alvo = trs.FirstOrDefault(tr => tr.Text.Contains(titulo));

    if (alvo == null)
    {
        throw new System.ArgumentException("Erro ao buscar a tarefa cadastrada.");
    }

    return alvo;
}

Apresenta o seguinte erro:

Severity  Code    Description Project File    Line    Suppression State
  Error   CS1061  'IWebElement' does not contain a definition for 'FirstOrDefault' and no extension method 'FirstOrDefault' accepting a first argument of type 'IWebElement' could be found (are you missing a using directive or an assembly reference?) Mark7   C:\Users\rodrigo.rebes\source\repos\Mark7\Mark7\Pages\TaskPage.cs   33  Active
Answer: Isso se dá porque você está usando o FindElement() na atribuição da variável trs, onde o mesmo apenas retorna um único elemento, levando em consideração que o FirstOrDefault() é usado para Enumerables.
FindElement():

Procura o primeiro elemento IWebElement usando o método passado.

FindElements():

Uma coleção ReadOnlyCollection de todos WebElements que combinam com os critérios atuais ou então uma lista vazia caso não combine.

Então troque o FindElement() por FintElements():

var trs = _driver.FindElements(By.CssSelector("table tbody tr"));

Mais informações:
https://seleniumhq.github.io/selenium/docs/api/dotnet/html/T_OpenQA_Selenium_IWebElement.htm


Como definir alternadamente a cor de background de sections de uma página com CSS?

Question: Dentro do body do meu documento HTML tenho uma sequência de 5 sections, esse número pode variar dependendo da situação.
Gostaria de definir um destaque (background) diferente para cada section "par", ou seja, pular 1 section e aplicar um background-color, pular outra e aplicar novamente o mesmo estilo, sucessivas vezes até a ultima section da página.
Answer: Existem seletores especificos para apanhar os elementos pares e impares, que permitem fazer o que quer com facilidade.
Pode começar por formatar todos os elementos normalmente e sobrepõe a formatação para os pares com o seletor:
section:nth-child(even)

Ou para os impares com:
section:nth-child(odd)

Exemplo:

section {
  background-color:lightBlue;
  height:80px;
}

section:nth-child(even){ /*pares com fundo azul*/
  background-color:blue;
}

Documentação para o nth-child no MDN
Answer: Usando :nth-child(even) ou :nth-of-type(even), você pode facilmente obter o resultado desejado. Ele vai selecionar todos que foram "even", ou seja, todos os pares.
Observe esse exemplo em http://cssdeck.com/labs/rib8dumb:

/* Propósito Estético */
section {
  color: white;
  padding: 2em 1.5em;
}

/* Pares */
section:nth-child(even) {
  background-color: #333;
  color: #ccc;
}

/* Impares */
section:nth-child(odd) {
  background-color: #ccc;
  color: #333
}

Section #1

Section #2

Section #3

Section #4

Section #5

Lembrando que existem mil e uma maneiras de usar essas pseudo-classes. Esse site lista quase todas as maneiras que você pode usar: http://nthmaster.com


Apple HTML5 progressive streaming

Question: Is there a copy of the file saved to the ipad/ipod when using progressive http download (apple segmented) that the user could potentially copy off the device?
meaning, is this scenario considered 'safe' from a content protection pov:
1. user comes to websites with movies behind paywall
2. user selects a movie to watch online (progressively downloaded or 'pseudo-streamed')
3. segments are downloaded seamlessly by html5 video tag as part of .m3u8
4. movie plays/ends.
is there any full copy of this movie on the device that can be transferred off? anyone know apple's stance on this?
Comment: Even if Safari automatically deletes movies as users watch them (I doubt it), I can pretty much guarantee someone has or will write a Firefox addon to save these kinds of movies.
Comment: brendan, very true. i should have clarified that i think we're talking about ONLY apple devices, i.e  not serve to firefox user agent.
Answer: I'd worry less about people obtaining the files from some hidden-away cache, and more about the fact you've got an http URL which allows the file to be directly downloaded onto any device.
You can dance around this and check for user-agent strings, session cookies etc, but there's not much you can do prevent someone from figuring it out, and writing an easy way around it.
Comment: ok. now, lets say we're at a low-enough resolution where the people who go to steal movies dont care about your 360 or  480p master and go easily rip from DVDs.
Answer: I believe you can segment using mediafilesegmenter in such a way that the files can only be viewed from the online location. I could be wrong about that, but if you check out the mediafilesegmenter docs, there appears to be many security options. That's where I'd look.

Apple HTML5 progressive streaming


How Can I get muitiple files selected to the same application launch from a "right click" context menu (windows explorer)

Question: I am able to get a shell registry type context menu function to work , see below . But is there a way to tell windows to send multiple files selected to the same application , perhaps instead of %1 or %L some other parameter . What happens now is that it launches the associated application for each file in the list .
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT*\shell]
[HKEY_CLASSES_ROOT*\shell\sendtomyapp]
@="&Upload to (File*Pics)Mojo"
[HKEY_CLASSES_ROOT*\shell\sendtomyapp\command]
@="c:\Program Files\app_directory\App.exe -n \"%1\""
Is there a way to send an array of names like sys.args in python ?
Comment: I think this question should be asked at superuser.com
Comment: This is a developer question, so no.
Answer: My guess is to look into DDEExec instead of shell\open\command.  http://msdn.microsoft.com/en-us/library/bb165967(VS.80).aspx
Answer: Seems like a superuser.com question, but I think these kind of operations require a bit of code. e.g. you write a proxy program that accepts the files, and adds them to an execution queue or batch of another program (like adding several files to a media player) I don't know if what you are looking for is supported inherently in Windows
Answer: You will need a full shell extension DLL to do what you want to do here. So the answer is programming even if the question was not.


can't make Genesis footer widgets stack when page resizing for responsive theme

Question: For days Ive been trying to correct an error in my CSS for this website. Everything is fine except for the footer area. It looks fine on desktop but as soon as its seen on small screen the footer area doesn't respond, the background colour disappears and and it gets very messy. If someone could help me id greatly appreciate it. Im no expert on CSS and am shooting in the dark.... the site is a test @ http://test.apinchofsalt.ie/wp/
All i need is the simplest solution to fix it. thanks very much. Below is the relevant CSS (it includes footer widgets, site footer and media queries)
/* Footer Widgets
---------------------------------------------------------------------------------------------------- */
<code>    .footer-widgets {
    background-color: #222;
    color: #c8c8c8;
    clear: both;
    font-size: 14px;
    font-size: 1.4rem;
    }
   .footer-widgets .wrap {
    overflow: hidden;
    padding: 60px 30px 30px;
    }
    .footer-widgets-1,
    .footer-widgets-2,
    .footer-widgets-3 {
    padding: 0 2.8%;
    width: 33.3333333333%;
   }
  .footer-widgets-1,
  .footer-widgets-2 {
   float: left;
   }
   .footer-widgets-3 {
   float: right;
   }
  .footer-widgets .widget {
   margin-bottom: 30px;
   word-wrap: break-word;
   }
   .footer-widgets a:focus {
   color: currentColor;
   }
  .footer-widgets li {
  background: url(images/icon-li-footer.png) no-repeat 0 7px;
  background-size: 8px 8px;
  }
   .footer-widgets .search-form {
   width: 100%;
    }
   /* Site Footer
</code>
---------------------------------------------------------------------------------------------------- */
<code>   .site-footer {
   color: #222;
   font-size: 12px;
   font-size: 1.2rem;
   padding: 40px 0;
   text-align: center;
   text-transform: uppercase;
   }
   .site-footer a {
   color: #222;
   }
   .site-footer p {
    margin: 0;
   }
  /* Media Queries
</code>
---------------------------------------------------------------------------------------------------- */
<code>    @media only screen and (-webkit-min-device-pixel-ratio: 1.5),
    only screen and (-moz-min-device-pixel-ratio: 1.5),
    only screen and (-o-min-device-pixel-ratio: 3/2),
    only screen and (min-device-pixel-ratio: 1.5) {
    .search-form input[type="search"] {
    background-image: url(firstname.lastname@example.com);
    }
    .sidebar li {
    background-image: url(firstname.lastname@example.com);
    }
    .footer-widgets li {
    background-image: url(firstname.lastname@example.com);
    }
    .content #genesis-responsive-slider .flex-direction-nav li a {
    background-image: url(email@example.com);
    }
    .content #genesis-responsive-slider .flex-control-nav li a {
    background-image: url(firstname.lastname@example.com);
    }
    .genesis-nav-menu > .rss > a {
    background-image: url(email@example.com);
    }
    .genesis-nav-menu > .twitter > a {
    background-image: url(firstname.lastname@example.com);
    }
    }
    @media only screen and (max-width: 1200px) {
    .site-container {
    max-width: 960px;
    }
    .site-header .widget-area {
    width: 700px;
    }
    .content {
    width: 660px;
    }
    .sidebar-primary {
    width: 300px;
    }
    .title-area {
    width: 260px;
    }
    .breadcrumb {
    margin: -30px -40px 30px;
    }
    .content {
    padding: 30px 40px 10px;
    }
    .site-header .genesis-nav-menu a {
    padding: 38px 14px 40px;
    }
    .content #genesis-responsive-slider .flex-control-nav,
   .content #genesis-responsive-slider .flex-direction-nav li a,
   .content #genesis-responsive-slider .flex-direction-nav li a.prev {
    display: none;
    }
    }
    @media only screen and (max-width: 1023px) {

    .site-container {
        max-width: 768px;
    }

    .content,
    .sidebar-primary,
    .sidebar-secondary,
    .site-header .widget-area,
    .title-area,
    .wrap {
        width: 100%;
    }

    .header-image .title-area,
    .header-image .site-title,
    .header-image .site-title a {
        background-position: center !important;
        float: none;
        margin: 0 auto;
    }

    .genesis-nav-menu li,
    .site-header ul.genesis-nav-menu,
    .site-header .search-form {
        float: none;
    }

    .genesis-nav-menu,
    .site-header .search-form,
    .site-header hgroup,
    .site-title {
        text-align: center;
    }

    .genesis-nav-menu a,
    .genesis-nav-menu > .first > a,
    .genesis-nav-menu > .last > a,
    .site-header .genesis-nav-menu a {
        padding: 16px;
    }

    .site-header .search-form {
        margin: 16px auto ;
    }

    .genesis-nav-menu li.right {
        display: none;
    }

    .content #genesis-responsive-slider .slide-excerpt {
        display: none;
    }

    .sidebar .widget {
        padding: 30px;
    }

    .comment-list li.depth-1,
    .ping-list li.depth-1 {
        margin: 30px 0;
    }

    .footer-widgets .widget-area {
        padding: 0;
    }

    .site-footer p {
        padding-left: 30px;
        padding-right: 30px;
    }

}

@media only screen and (max-width: 800px) {

    .site-container {
        max-width: 630px;
    }

    .five-sixths,
    .footer-widgets-1,
    .footer-widgets-2,
    .footer-widgets-3,
    .four-sixths,
    .home-middle .widget,
    .home-top .widget,
    .one-fourth,
    .one-half,
    .one-sixth,
    .one-third,
    .executive-pro-portfolio .portfolio,
    .three-fourths,
    .three-sixths,
    .two-fourths,
    .two-sixths,
    .two-thirds {
        margin: 0;
        width: 100%;
    }

    .site-title {
        margin-bottom: 20px;
    }

    /* Genesis Responsive Menus */
    .js .site-header nav .wrap {
        padding: 0;
    }

    nav.genesis-responsive-menu {
        background: #fff;
        display: none;
        position: relative;
    }

    .genesis-skip-link .skip-link-hidden {
        display: none;
        visibility: hidden;
    }

    .menu-toggle,
    .sub-menu-toggle {
        border-radius: 0;
        border-width: 0;
        color: #64c9ea;
        display: block;
        margin: 0 auto;
        overflow: hidden;
        text-align: center;
        visibility: visible;
    }

    .menu-toggle:focus,
    .menu-toggle:hover,
    .sub-menu-toggle:focus,
    .sub-menu-toggle:hover {
        background-color: #fff;
        color: #222;
        border-width: 0;
    }

    .menu-toggle:focus,
    .sub-menu-toggle:focus {
        outline: 1px solid #ccc;
        outline-offset: -1px;
    }

    .menu-toggle {
        background-color: #fff;
        line-height: 20px;
        margin-bottom: 1px;
        position: relative;
        z-index: 1000;
        width: 100%;
    }

    .menu-toggle::before {
        margin-right: 10px;
        text-rendering: auto;
    }

    .sub-menu-toggle {
        background-color: transparent;
        float: right;
        padding: 14px 10px 13px;
        position: absolute;
        right: 0;
        top: 0;
        z-index: 100;
    }

    .sub-menu .sub-menu-toggle {
        padding: 9px 10px;
    }

    .sub-menu-toggle::before {
        display: inline-block;
        margin-top: 5px;
        text-rendering: auto;
        -webkit-transform: rotate( 0 );
        -ms-transform:     rotate( 0 );
        transform:         rotate( 0 );
        -webkit-transition: transform .25s ease-in-out;
        -ms-transition:     transform .25s ease-in-out;
        transition:         transform .25s ease-in-out;
    }

    .sub-menu-toggle.activated::before {
        -webkit-transform: rotate( 180deg );
        -ms-transform:     rotate( 180deg );
        transform:         rotate( 180deg );
    }

    .genesis-responsive-menu ul {
        border-bottom: 2px solid #f2f2f2;
    }

    .genesis-responsive-menu .genesis-nav-menu .menu-item {
        display: block;
        float: none;
        position: relative;
        text-align: left;
    }

    .genesis-responsive-menu .genesis-nav-menu .menu-item:focus,
    .genesis-responsive-menu .genesis-nav-menu .menu-item:hover {
        background: transparent;
        position: relative;
    }

    .genesis-responsive-menu .genesis-nav-menu a:focus,
    .genesis-responsive-menu .genesis-nav-menu a:hover {
        color: #64c9ea;
    }

    .genesis-responsive-menu .genesis-nav-menu .menu-item a {
        background: transparent;
        border: none;
        color: #222;
        margin-bottom: 1px;
        padding: 15px 20px;
        width: 100%;
    }

    .genesis-responsive-menu .genesis-nav-menu .sub-menu {
        border: none;
    }

    .genesis-responsive-menu .genesis-nav-menu .menu-item > a:focus ul.sub-menu,
    .genesis-responsive-menu .genesis-nav-menu .menu-item > a:focus ul.sub-menu .sub-menu {
        left: 0;
        margin-left: 0;
    }

    .genesis-responsive-menu .genesis-nav-menu > .menu-item-has-children > a::after {
        content: none;
    }

    .genesis-responsive-menu .genesis-nav-menu .sub-menu {
        clear: both;
        display: none;
        margin: 0;
        opacity: 1;
        padding-left: 15px;
        position: static;
        width: 100%;
    }

    .genesis-responsive-menu .genesis-nav-menu .sub-menu .sub-menu {
        margin: 0;
    }

    .home-middle,
    .home-top,
    .genesis-pro-portfolio .pro-portfolio.entry .entry-header .entry-title {
        text-align: center;
    }

    .home-cta .button.alignright {
        float: none;
        margin: 16px 0 0;
    }

    .footer-widgets-1 {
        margin: 0;
    }

}

@media only screen and (max-width: 500px) {

    .entry-title {
        font-size: 24px;
        font-size: 2.4rem;
    }

    .content .entry-header .entry-meta .entry-comments-link {
        display: none;
    }

}

@media only screen and (max-width: 270px) {

        .header-image .site-title a {
        background-size: contain !important;
    }
        .site-title {
        font-size: 26px;
        font-size: 2.6rem;
    }

}
</code>
Comment: just to say that the child theme comes with 3 footer widgets. I added an extra 2 through the functions.php. That may be where the problem lies.
Answer: In your media queries pls include the following code. The footer widgets are floated and thus need clearing for the background to wrap around properly.
<code>.footer-widgets .wrap:after {
content: "";
display: table;
clear: both;}
</code>
Comment: thats great Shivanand ill try it now
Comment: that doesnt seem to be working at all and the site footer hasnt changed - it seems to be in the way and doesnt drop beneath the footer widgets.
Comment: I tested your site in firefox and the footer widgets are responsive: they collapse below each other on smaller resolutions. Looks perfectly responsive. Is that not what you are expecting?
Comment: yep i changed a bit around...went into w3schools and looked up position values and thanks to you concentrated on the wrap - still dont understand what your code means though...but your help has been invaluable


Sharp upper bounds for sums of the form $\sum_{p \mid k} \frac{1}{p+1}$

Question: Are there known sharp upper bounds for sums of the form $\sum_{p \mid k} \frac{1}{p+1}$ for $k > 1$ subject to the constraint $\sum_{p \mid k} \frac{1}{p+1} < 1$? (The factor of +1 in the denominator and the constraint of the sum of inverse "shifted prime divisors" is bounded by 1 are both necessary.)
A related question: Suppose $(p_i)$ is a set of $n$ consecutive primes which minimizes $1 - \sum_{i = 1}^{n} \frac{1}{p_i+1} > 0$ for a given $n > 1$. Are there known bounds for $1 - \sum_{i = 1}^{n} \frac{1}{p_i + 1}$ from below in terms of $n$, e.g., $n^{-\delta n}$ for some fixed $\delta > 0$?
Thanks!
Comment: You might want to ask these questions on MO if you don't get an answer here.
Comment: Thanks. I posted the same questions on MO under the same header.
Answer: Actually, there is a bound for $\displaystyle \frac{1}{p}$. Perhaps, this should help. You can find this result in a standard Analytic Number theory textbook.(I have taken this from Apostol's Analytic Number Theory textbook!)
Proposition: There is a constant $A$ such that $$\sum\limits_{p \leq x} \frac{1}{p}= \log\log{x} + A + \mathcal{O}\Bigl(\frac{1}{\log{x}}\Bigr)$$ for all $x \geq 2$, where the constant $A$ is given by $$A = 1 -\log\log{2} + \int\limits_{2}^{\infty} \frac{ R(t)}{t \log^{2}{t}} \ dt$$
Comment: @user02138: If you had considered this, then you should mention it!
Answer: My answer on MO:
If we are allowed to consider somewhat weaker bounds, both answers depend only on the number of unitary divisors of $k$, which is $2^{\omega(k)}$. By the quoted result of O. Izhboldin and L. Kurliandchik (see Fedor's and Myerson's comments here), for any set of $n$ positive integers {$a_{1}, \dots, a_{n}$} such that $\sum_{i = 1}^{n} \frac{1}{a_{i}} <1$, we have
\begin{eqnarray}
\sum_{i = 1}^{n} \frac{1}{a_{i}} \leq \sum_{i = 1}^{n} \frac{1}{d_{i}} = \frac{d_{n+1} - 2}{d_{n+1} -1} < 1,
\end{eqnarray}
where $d_{i}$ is the $i^{\text{th}}$-Euler number, which satisfies the quadratic recurrence $d_{i} = d_{1} \cdots d_{i-1} + 1$ with $d_{1} = 2$. The first few terms of the sequence are 2, 3, 7, 43, 1807....  (A000058). It is relatively straightforward to show that the aforementioned recurrence is equivalent to $d_{i} = d_{i-1}(d_{i-1}-1) + 1$, and it is known from the recurrence that $d_{i} = \lfloor \theta^{2^{i}} + \frac{1}{2} \rfloor$, where $\theta \approx 1.2640$.... Thus,
\begin{eqnarray}
\sum_{p \mid k} \frac{1}{p + 1} \leq \sum_{i = 1}^{\omega(k)} \frac{1}{d_{i}} = \frac{d_{\omega(k) + 1} - 2}{d_{\omega(k)+1} - 1} = \frac{\lfloor \theta^{2^{\omega(k) + 1}} + \frac{1}{2} \rfloor - 2}{\lfloor \theta^{2^{\omega(k) + 1}} + \frac{1}{2} \rfloor - 1} < 1.
\end{eqnarray}
One can also show that $d_{i} - 1 = \lfloor \vartheta^{2^{i-1}} - \tfrac{1}{2} \rfloor$, where where $\vartheta \approx 1.5979$...., so we have
\begin{eqnarray}
1 - \sum_{p \mid k} \frac{1}{p + 1} \geq 1 - \frac{d_{\omega(k)+1} - 2}{d_{\omega(k)+1} - 1} = \frac{1}{d_{\omega(k)+1} - 1} = \lfloor \vartheta^{2^{\omega(k)}} - \tfrac{1}{2} \rfloor^{-1} > 0.
\end{eqnarray}
Remark E. Deutsche points out that the sequence {$d_{i} - 1$} (A007018) counts the number of ordered rooted trees with out-going degree up to 2 with all leaves at top level.


Every continuous function $f$ on the unit sphere (shell) has a point $p$ such that $f(p)=f(-p)$

Question: The Question:
Define the subset of $\Bbb R^3$
$$S=\{ (x,y,z) \in \Bbb R^3: x^2+y^2+z^2=1 \}$$
Suppose that $f:S \rightarrow \Bbb R$ is a continuous function. Prove that there exists $p \in S$ such that $f(p)=f(-p)$.

My Attempt:
I don't know where to start really. I feel that the following facts might be useful:

Intermediate Value Theorem
$f:S \rightarrow \Bbb R$ is continuous and $S$ is connected $\implies$ $f(S)$ is connected
Path connected $\implies$ connected

Any hints as to how I should tackle this problem?
Answer: This is a special case of the Borsuk-Ulam theorem. That states that if
$f:S^n\to\Bbb R^n$ is continuous, then there is a $p$ with $f(p)=f(-p)$.
In our case just look for a point on $S^1=\{(x,y,0):x^2+y^2=1\}\subset S^2$
with $f(p)=f(-p)$. In this case, Borsuk-Ulam is quite elementary. Just
consider $g(t)=f(\cos t,\sin t,0)-f(-\cos t,-\sin t,0)$. All you need is
the Intermediate Value Theorem to ensure that $g$ has a zero.
Comment: Nice answer! If you may take Borsuk-Ulam for granted (which I doubt), combining $f$ with an embedding of $\mathbb{R}$ into $\mathbb{R}^2$, e.g. $x\mapsto(x,0)$, seems to do the trick.
Answer: If f is continuous, then $T: p\mapsto f(p) - f(-p)$ is continuous. By symmetry $T(p) = - T(-p)$. Since images of connected sets under continuous functions are connected this yields that the image of T is a symmetric interval  containing $0$.


What does the expression "Fail Early" mean, and when would you want to do so?

Question: What does the expression "Fail Early" mean, and under what circumstances is this approach most useful, and when would you avoid the approach?
Comment: @NomeN: I decided to ask this question because when I was supplying the answer http://stackoverflow.com/questions/2800099/options-fetch-i-dont-get-it/2807179#2807179 , I found that "Fail Early" wasn't described well within Stack Overflow. It wasn't meant as a blatant reputation harvest (that's just an added bonus!)
Comment: I read your question and thought that this was an easy one that most people knew. Turns out that at least three persons had the wrong idea... so +1 I guess for documenting for once and for all the right definition.
Answer: Essentially, fail fast (a.k.a. fail early) is to code your software such that, when there is a problem, the software fails as soon as and as visibly as possible, rather than trying to proceed in a possibly unstable state.

Fail Fast
by Jim Shore
edited by Martin Fowler
http://www.martinfowler.com/ieeeSoftware/failFast.pdf

...
Fortunately, there's a simple technique that
will dramatically reduce the number of these
bugs in your software. It won't reduce
the overall number of bugs, at
least not at first, but it'll make
most defects much easier to find.

The technique is to build your
software to "fail fast."

Immediate and
visible failure

Some people recommend making
your software robust by working
around problems automatically.
This results in the software "failing slowly."
The program continues working right after an
error but fails in strange ways later on.

A system that fails fast does exactly the opposite:
when a problem occurs, it fails immediately
and visibly. Failing fast is a nonintuitive
technique: "failing immediately and visibly"
sounds like it would make your software more
fragile, but it actually makes it more robust.
Bugs are easier to find and fix, so fewer go into
production.
...

Also note the related concept of a fail-fast iterator - an iterator that, after certain modifications to the collection outside of the iterator, throws as soon as possible rather than proceed in a potentially unstable, or non-deterministic state.
Comment: To explain via a counterexample, something which does not "fail fast" would be most web browsers and HTML. Consider this invalid HTML: `Bold Text!`
It's missing the ``, but web browsers choose to do the opposite of "fail early" by trying to recover from the problem and hoping it doesn't make things worse. In their case, it's a sensible route to take.
But when you're writing code (rather than a visual presentation layer) going for correctness is probably a better strategy.
Comment: @KonradRudolph: Indeed, if all browsers failed on an unbalanced `` tag, we wouldn't have websites with broken `` tags, because the web developer would have noticed it during development. Unfortunately, once the (then) market-leading browser started accepting broken HTML, the others had to follow suit, or people wouldn't use their product ("Browser X won't show my favorite web site, but it works with browser Y, so I'll use browser Y.")
Comment: @Darien "In their case, it's a sensible route to take." — This claim (known as the "robustness principle" or "Postel's law") was made without supporting evidence and has since been [heavily criticised](https://tools.ietf.org/id/draft-thomson-postel-was-wrong-03.html). It is in fact almost certainly wrong. At the very least it has made maintaining web browser code bases unnecessarily more costly and has prevented these resources from being used for more deserving purposes.
Answer: "Fail Early" means that the program should raise an exception and stop working if something goes wrong. (It is described in the Pragmatic Programmer's list of tips as Crash Early)
In my bioinformatics work, I tend to use a "Fail Early" approach because my highest concern is ensuring correctness. By contrast, Rails allows you to hide failures. For example, Rails' try allows you to call something on an object, and it won't raise an exception if that object is nil. I guess this is because with web sites, ensuring that the program keeps running is more important than correctness.
Comment: @Michael Andrew is adding value to SO and sharing his work here, I don't anything wrong nor silly with that. And yes, you could even use SO as a blog and it is even encouraged. See http://meta.stackexchange.com/questions/17463/should-i-ask-a-question-i-know-the-answer-to and http://meta.stackexchange.com/questions/2706/moving-a-personal-technical-blog-to-stackoverflow-serverfault
Comment: I specifically said "It's ok for people to answer their own questions", but I think that FAQ entry is intended mostly for people who ask a question, search around for a while, find the answer, and then post it on their own question because nobody else knew. Based on how fast you answered, it looks like you posted the question *already knowing* the answer, which is a bit silly; you might as well have just blogged about it. I could sit here all day posting questions I already know the answers to, and immediately posting those answers
Comment: @Pas I meant "go crazy" colloquially as in "feel free to do so as often as you like", not "I find it crazy that you're doing that"
Comment: Er. Did you set this up? It's ok for people to answer their own questions, but you answered pretty completely, a mere 5 minutes after you asked the question, which makes me think you already knew the answer before you posed the question
Comment: @michael mrozek: To be fair, it is not a complete answer to his original question. But it would be less suspicious as an edit of the question than an answer
Comment: @Michael, @NomeN: Can you link to something in meta expanding on your opinion?
Comment: Yes, exceptions are a perfectly good example, a perfectly good tip of the iceberg of situations where failing early brings the benefit of saving immense expense down the line.  Imagine if Toyota's acceleration system had failed before cars came off the assembly line instead of after.
Comment: @Michael, @NomeN: "It's also perfectly fine to ask and answer your own question, but pretend you're on Jeopardy: phrase it in the form of a question" http://stackoverflow.com/faq
Comment: @Michael: If those questions and answers are worthwhile, they'll be voted up, and that's ok. If they aren't, they won't, you'll stop doing it, and that's ok.
Comment: It's fine, I didn't mean to start an argument, I just asked if he already knew the answer and it got turned into "how dare you post a question you already know the answer to". I think it's silly in most cases, and that meta post was hardly unanimous, but if the majority are fine with it then go crazy
Comment: @Michael I totally fail at understanding what is "crazy" with adding value and knowledge to SO. You've faced a problem and solved it, you realize the problem isn't mentioned on SO, you post your findings as Q&A on SO so that it can potentially help others (because SO is much better ranked than your private blog), what is silly with that? Please, try to convince me.
Answer: Failing early embodies the idea that when building software the earlier you fail or a test fails or you find a bug the easier it is to correct (and cheaper as well). It also applies to your business model. Better to find out early (in beta for example) than after you have launched.
Comment: @NomeN: "The Passionate Programmer" suggests "failing early" should apply to business as well: if there's something going wrong, tell other people, don't cover it up.
Comment: Nope, although what you say is a correct point it is not connected to the term "failing early". Andrew Grimm has the right explanation (to his own question no less!.
Comment: Again, this is the correct answer and it was discovered decades before programming languages evolved to provide structured exceptions at the language level.  (Also this correct answer was posted 2 minutes later than the other correct answer, the one which is falsely asserted to be "Again, not the right answer.)
Comment: Indeed. If a project or business has to fail, it's better to fail it early than late (you'll save some money).
Answer: I once had a junior oracle programmer working for me who put an "ignore everything" exception block around all his code so errors were never seen. This initially made his code look impressive but:
A) Bugs took far longer to find;
and
B) I lost all (well, 80% of my) faith in his abilities after that.
I have since taught people that this is a very bad thing as it hides errors.
Do not confuse this with a code module being able to cope with poor quality inputs (such as HTML which is not also valid XHTML in a browser) - these do not need to result in a failure at all. More likely, they did cause a failure many years ago but the way to resolve it was to make the system take reasonable assumptions about how to recover.
Answer: It means: "Catch bugs as early as possible". If possible, you want to know they are there as soon as they are there =).
The earlier you catch a bug, the cheaper it is to remove it. If you could know the bug right at the time you wrote the buggy line, it would be awesome. You would know exactly what you were intending to do, and have the most power to remove that bug quickly.
On the other hand, if you just catch the bug one month later, or after it's released, the damage is a LOT greater. Users already have to deal with it, you won't remember what you were thinking so well (or maybe you won't be even working for the company anymore, so someone will need to find out what your thoughts were).
Comment: Again, not the right answer. You have essentially the same point as Steve Robillard, and the same mistake I'm afraid. Failing early is what you should do with exceptions at runtime!
Comment: @NomeN: To be fair, Samuel's describing the "why", not the "how".
Comment: This is the correct answer and it was discovered decades before programming languages evolved to provide structured exceptions at the language level.


How to render multiple values of node reference in the form of an ordered list without views?

Question: I have a node reference field that references another node and has multiple values. I want to get an ordered list of the output of that field and display it in the custom node template. I am rendering the node reference as a cck block. Any help or guidance would be greatly appreciated. Thanks.
Answer: In D6, you could do something like this:
print '
';
foreach ($node->field_whatever as $foo) {
  print '
';
    $bar=node_load($foo['nid']);
    print l($bar->title, 'node/' . $bar->nid);
  print '
';
}
print '
';

In D7 you'd have to throw in the node language stuff and there might even be something more exciting built in as well but I think they all use divs instead of lists.  (In both you could also create a content field template for this instead of hardcoding it in your node template)
Answer: It sounds like the Text List Formatter module will do what you want.

This module provides a field display formatter to render field values as HTML or comma-separated lists. This can currently be used on all core field types (text, long text, number, list, and taxonomy reference etc..) and some contributed fields. (see below).
For multi-value fields, each field value becomes a list item. For long text fields, each line becomes a list item.


How to set a value on a field collection using entity metadata wrapper

Question: I'm trying to programmatically set a value on a field collection item attached to the user entity.
The field collection field in question is titled, field_user_location.
I initially had this ($usr_wrapper being an entity metadata wrapper of the user entity)
$usr_wrapper->field_user_location->field_land_phone->set($object['Phone Number']);

However that doesn't appear to work.
How do you get data onto a field collection via entity_metadata_wrapper()? There isn't much documentation about how to do this that I am seeing.
Answer: I found the documentation for field collections confusing as well.
Field collections need their own entity metadata wrapper. So, the following code would work for your example:
$collection = entity_create('field_collection_item', array('field_name' => 'field_user_location'));
$collection->setHostEntity('user', $user);
$fc_wrapper = entity_metadata_wrapper('field_collection_item', $collection);
$fc_wrapper->field_land_phone->set($object['Phone Number']);

I hope that helps for anyone else banging their heads over this.
Comment: Just for clarification, what is `$object`? Just a newly-instatiated array named 'object'?
Comment: In this example, we don't know exactly what `$object` was. We only know that it was an array that had a key named 'Phone Number'. The important thing as far as entity metadata wrappers are concerned is that the `set` method receives an argument that matches the data structure of the field to which it's attached. So, if the `field_land_phone` is a textfield that holds a string value, you pass it the string you want to set it to. That line could just have easily read `$fc_wrapper->field_land_phone->set('867-5309');`
Answer: Based on your example, the could should be:
global $user;
$usr_wrapper = entity_metadata_wrapper('user', $user);

// Create the collection entity and set its "host".
$field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_user_location')); // Name of collection field.
$field_collection_item->setHostEntity('node', $usr_wrapper->value());

// Now define the collection parameters.
$collection = entity_metadata_wrapper('field_collection_item', $field_collection_item);
$collection->field_land_phone = "0123"; // array("0123") in case of multi-valued field.
// $collection->field_land_phone->set("0123"); // Version using set(), use: set(array("0123")) for multi-valued field.

// Save.
$collection->save(); // Or: $usr_wrapper->save();

Also check Entity metadata wrappers documentation page (check for Example using field collections).

Here is another example which adds an entry to a node with a field collection named field_activity_log:
  // Load the controller class file.
  module_load_include('inc', 'entity', 'includes/entity.controller');

  // Use the currently logged in user if a $uid argument is not defined.
  global $user;
  if (empty($uid)) {
    $uid = $user->uid;
  }

  $now = gmdate('Y-m-d H:i:s'); // Grab the current time.

  // Setup the values in the structure expected by the field_collection entity.
  $values = array(
    'field_name' => 'field_activity_log',
    'field_activity_log_date' => array(
      LANGUAGE_NONE => array(array('value' => $now)),
    ),
    'field_activity_log_message' => array(
      LANGUAGE_NONE => array(array('value' => $message)),
    ),
    'field_activity_log_user' => array(
      LANGUAGE_NONE => array(array('uid' => $uid)),
    ),
  );
  $entity = entity_create('field_collection_item', $values);

  // Attach the field_collection entity to the application node. This has to
  // happen separately so that it actually works -- you can't just specify
  // this via the $values array.
  $entity->setHostEntity('node', $node);

  // Save the entity. Since it's attached to the right application node, this
  // will both create the field_collection entity and update the application
  // node to point to the new field_activity_log record.
  $entity->save();
?>

Source: Example: Programmatically adding field collection entries to a node
And this example shows updating (loading/editing/saving) an existing field collection in an Entity Wrapper:
<?php
// Load the node by NID
$raw_node = node_load($nid);
// Wrap it with Entity API
$node = entity_metadata_wrapper('node', $raw_node);
// Get the first item from the muli-value field collection
$raw_collection = $node->field_collection->value();
// Wrap it with Entity API
$collection = entity_metadata_wrapper('field_collection_item', $raw_collection);
//dsm the old value
dsm($collection->field_example->value());
// Set a new value on the field_example textfield.
$collection->field_example = 'New value';
// Save the changes to the entity
$collection->save();
?>

Source: Example: Programmatically create and update field collection with Entity API

Troubleshooting
In case of error when setting the data value with set(), be be sure it matches the required data type and format. If your entity won't get saved, check for the logs for any wrapper exceptions (drush ws --tail).
See also: Modifying a field collection programmatically missing hostEntity fields at SO


Confused with Java Objects

Question: I am a beginner with Java, and I am trying the following code:
public class MovieTestDrive {

    public static void main(String[] args) {
        Movie one = new Movie();
        one.title = "Gone with the Stock";
        one.playIt();
        System.out.println(one.title);   // Works!! one.title is equal to Dora

        Movie [] arr = new Movie[2];
        arr[0].playIt();
        System.out.println(arr[0].title); //Error: Null Pointer Exception

    }
}

class Movie {

        String title;

        void playIt() {
             title = "Dora";
        }

 }

Why does the code works in the assignment of a primitive variable while it doesn't when using an array?
Answer: Because all you have in arr is an array of object references, but they're not initialized to point at any actual objects.
You also need to do:
arr[0] = new Movie();
arr[1] = new Movie();

Answer: Nothing is in your movie array yet.  You need to put objects in your array before you can act upon them.
Between "Movie [] arr = new Movie[2];" and "arr[0].playIt();", you need to assign Movie objects to your array in order to perform the .playIt() function and have anything actually occur.
Answer: The NPE is in the previous line, at arr[0].playIt();
It's got nothing to do with your object though, it's the fact that your array is empty.
Answer: Movie [] arr = new Movie[2]; // creates an empty array of two elements [null, null]

// now lets add Movie objects
arr[0] = new Movie();
...

I would suggest to use ArrayList instead of array:
List<Movie> movies = new ArrayList<Movie>();
movies.add(new Movie());
...

Answer: You need to fill your array. All you did so far was allocate space for an array of movie objects. You didn't put any objects into that space. you can use
arr[i]=new Movie(); where i is the array index

Confused with Java Objects


SBJson Conflict with Facebook sdk iOS

Question: I'm developing an application using SBJson framework.
now i want to add the Facebook SDK to my app but i get duplicate classes errors.
probably Facebook using some other version of SBJson source.. but the files name are the same!
i'v tried to change the classes names with the refactor tool.. but it doesn't seems to solve my problem.
Please help.
Thanks.
Answer: Facebook already includes the json-framework. Use what's Already included to handle your json. No need to add another seperate version of it. That's why you're getting duplicate errors.
Comment: I installed facebook-sdk 3.0 and still having problems. I don't see any header for SBJSON, so how can I use it in my own project? I get the duplicate error if I try to add my own SBJSON (as I had before). Thanks!
Comment: do u have any tutorial for this? because the methods that I'm used to are not available in Facebook SDK
Comment: ...and what method's are that?
Comment: skarm thank you, i'v solved it like u said.. i used FB json librar
Comment: I got the same problem with iOS Facebook SDK version 3. Here is my question: [link](http://facebook.stackoverflow.com/questions/12041056/duplicate-symbol-sbjson-on-ios-facebook-sdk-v-3-0)

SBJson Conflict with Facebook sdk iOS


Flutter DateTime , Open Close if

Question: I want to show between 09:00 am - 20:00 pm widget, other time another widget so
for example now 13:00 my shop open I want to show open my shop.
thanks
<code>openSaat() {
  return Container(
    width: 170,
    height: 40,
    decoration: BoxDecoration(color: Colors.black),
    child: Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        CircleAvatar(
          backgroundColor: Colors.green,
          radius: 12,
        ),
        SizedBox(width: 5,),
        Text("Open Now",style: TextStyle(fontSize: 20,fontWeight: FontWeight.bold,color: Colors.white),)
      ],
    ),
  );
}

closeSaat() {
  return Container(
    width: 170,
    height: 40,
    decoration: BoxDecoration(color: Colors.black),
    child: Center(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          CircleAvatar(
            backgroundColor: Colors.red,
            radius: 12,
          ),
          SizedBox(width: 5,),
          Text("Close Now",style: TextStyle(fontSize: 20,fontWeight: FontWeight.bold,color: Colors.white),)
        ],
      ),
    ),
  );
}
</code>
Answer: <code>@override
  Widget build(BuildContext context) {
    return new Scaffold(
    body: currentWidget()
    );
  }
  static DateTime now = DateTime.now();

   Widget currentWidget() {
    var hours = now.hour;

    if (hours >= 09 && hours < 21) {
      return _openSaat();
    } else
      return _closeSaat();
  }

Widget _openSaat() {
  return Container(
    width: 170,
    height: 40,
    decoration: BoxDecoration(color: Colors.black),
    child: Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        CircleAvatar(
          backgroundColor: Colors.green,
          radius: 12,
        ),
        SizedBox(
          width: 5,
        ),
        Text(
          "Open Now",
          style: TextStyle(
              fontSize: 20, fontWeight: FontWeight.bold, color: Colors.white),
        )
      ],
    ),
  );
}

Widget _closeSaat() {
  return Container(
    width: 170,
    height: 40,
    decoration: BoxDecoration(color: Colors.black),
    child: Center(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CircleAvatar(
            backgroundColor: Colors.red,
            radius: 12,
          ),
          SizedBox(
            width: 5,
          ),
          Text(
            "Close Now",
            style: TextStyle(
                fontSize: 20, fontWeight: FontWeight.bold, color: Colors.white),
          )
        ],
      ),
    ),
  );
}
</code>
Comment: You should be careful to do this with `DateTime.utc` rather than `DateTime.now`, and adjust your range appropriately.  Otherwise, it's using the local time, and not reflecting your real-world hours.
Comment: Hi, this work fine, but how can i add in code that on thuesday show always closed? Thank you

Flutter DateTime , Open Close if


Como faço no JavaScript para checar se meu input tem algum texto escrito?

Question: Tentei da seguinte forma:

function aviso() {
  document.querySelector(".registers_button")
  let email_box = document.querySelector(".email")
  if (email_box.innerHTML == '') {
    alert("Por favor, preencha os campos obrigatórios")
  } else if (!email_box.innerHTML == '') {
    alert("Redirecionando...")
  }
}

 E-mail: <input class="email" type="text" placeholder="Ex: firstname.lastname@example.com">

Comment: Não legende seus `` com `` use [``](https://developer.mozilla.org/pt-BR/docs/Web/HTML/Element/label). Ex: ` E-mail:  `. Também veja [](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email)
Comment: Opa amigão, muito obrigado, farei essa alteração no meu código. Aos poucos vou aprendendo HTML semântico.
Answer: Sua pergunta precisa de mais esclarecimentos, mas supondo que seu elemento com a classe "email" é um input e não um elemento como DIV, a forma correta de buscar o valor do campo é usando value, não innerHTML
if (email_box.value == '') {
    alert ("Campo vazio");
} else {
    alert("Redirecionando")
}

innerHTML e innerText são propriedades de elementos como
,
 etc.
Comment: Cara, muito obrigado ! tua resposta foi exatamente oque eu buscava. Quanto a pergunta, preciso mesmo melhorar.
Comment: se a resposta está de acordo com o que procurava marque-a como "Resposta aceita" =)
Answer: Seu código tem duas TAGs um p e um input:
Se quiser obter o texto dentro do
 (um HTMLElement) você pode usar o innerText:

let txt = globalThis.document.querySelector("p.email_text").innerText
console.log("RESULTADO:", txt);

 E-mail: <input class="email" type="text" placeholder="Ex: email@example.com">

<input class="email" type="text" placeholder="Ex: email@example.com">

Se quer obter um texto dentro de um input (HTMLInputElement), você pode usar o value.

let txt = globalThis.document.querySelector("input.email").value
console.log("RESULTADO:", txt);

 E-mail: <input class="email" type="text" placeholder="Ex: firstname.lastname@example.com" value="um valor">


How many cents comprise a quarter-tone in 15-EDO?

Question: My question is from my MUS 204 course, which is the following: How many cents comprise a quarter-tone in 15-EDO?
I believe I am missing one piece of knowledge to answering such a seemingly simple question. First, I understand a quarter-tone is 50 cents and second, I understand the frequency ratio in 15-EDO, correct me if I'm wrong, is 2^1/15 and a cent is 1/1200 of an octave.
I wanted to solve the problem similar to solving for the number of cents in just perfect fifth. (i.e., log of base 2 to the 3/2 = (number of cents)/1200, which is approx. 702 cents.) However, substituting 3/2 for 1/15 produces an incorrect number. (The correct number should be 80 cents.)
What correct steps must be taken to find the correct answer to the question above?
Comment: I find this question dubious. IMO there aren't any quarter tones in 15-edo.
Comment: @leftaroundabout I answered on this basis
Answer: Taking 12-EDO as a starting point...

12-EDO divides the octave into 12 semitones and, therefore, 24 quarter tones.
The purpose of "cents" is to divide the octave using a linear scale rather than an exponential one.
An octave being 1200 cents means that each 12-EDO quarter tone is 1200/24 = 50 cents.

15-EDO is to be treated analogously.

15-EDO divides the octave in 15 "semitones" and, therefore, 30 "quarter tones".
It follows, then, that each 15-EDO quarter tone is 1200/30 = 40 cents.

As pointed out in the comments, the original textbook question is a dubious one. The concepts of "tone", "semitone", "quarter tone", and "perfect fifth" have specific meanings in 12-EDO that don't transfer — or, at least, don't necessarily transfer — to other EDO systems. It's misleading to speak of semitones and quarter tones, etc., in the context of 15-EDO.
Comment: I do not like it. By the same logic, a "quarter-tone in 22-edo" would be 27.3 cents, but that interval certainly shouldn't be called a quarter tone.
Comment: @leftaroundabout It depends on what is considered a "tone" or "semitone" within the context of the particular tuning system. Given that the question originates in Music 204, I take it to be that they're trying to make a simple analogy with nice math rather than a generalized definition across EDOs. Frankly, I don't like the textbook question that prompted this, for exactly the reason you allude to: it's misleading to refer to 12-EDO concepts (semitone, quarter tone, perfect fifth) in the context of 15- or any other -EDO.
Comment: @PiedPiper The underlying frequencies, yes, but the math for cents themselves is linear, which I've understood to be the point of using cents.
Comment: @phoog that would make cent scale rather useless in comparing various temperaments or divisions.
Comment: @leftaroundabout I've added a qualifying explanation to the answer. Would value your opinion on whether it offers an adequate caveat.
Comment: Very adequate IMO!
Comment: @Aaron The JI perfect fifth is 3:2, a concept that utterly transcends any tuning system. Semitones can be constructed as 16:15 (diatonic semitone, perfect fourth minus major third), 25:24 (chromatic semitone, major third minus minor third), and weirder combinations. Anything that claims to be called a "quarter tone" needs to be be somewhere half that, necessarily close to the 50 cent range.
Comment: OP quotes the number 80 cents, which makes me think she already knows the information you provided here, and the question is on deriving the number of cents from frequencies.
Comment: Cents are not a linear division of a semitone (or of an octave). If they were linear, a quarter tone wouldn't be 50 cents.
Comment: @PiedPiper Perhaps I used the wrong term. Cents allow for simple multiplication in that x semitones are, say, 50x cents. Is that not linear?
Comment: @Aaron - Isn't a semitone [100 cents](https://en.wikipedia.org/wiki/Cent_(music))?
Comment: The underlying frequencies are exponential, just as they are with semitones and octaves.
Comment: @Dekkadeci My error in the comment, yes.
Comment: It seems to me that a cent ought to be defined as 100th of a division in whatever EDO system you're using.  In that light, a quarter tone ought to be 62.5 15-EDO-cents
Comment: @user1079505 that's true, but there's no particularly compelling reason to measure all temperaments and divisions against 12-tone equal temperament.  The main point, however, is that it makes less sense to adapt the definition of "semitone" to a different equal division of the octave while keeping "cent" related to 12-EDO, because "semitone" predates equal divisions of the octave altogether.  Is a semitone in 31-EDO the 31st part of an octave?  Of course not.
Comment: @phoog Yes, there is a reason, it's needed if you actually want to tune your instrument given way. Consider also, on this page: https://en.wikipedia.org/wiki/Equal_temperament intervals seem to be named based on their similarity to 12-EDO intervals. Calling a 15-EDO step a semitone seems to agree with this convention.
Comment: @user1079505 how does defining "cent" as 1/1200 of an octave instead of as 1/100 of an octave division help anyone tune a flute or a guitar to 15-EDO?  It's not even possible to tune those instruments to 15-EDO.  It's also not necessary to make reference to cents in order to tune any other instrument in 15-EDO; you can just calculate the frequencies directly.
Comment: Because 1/1200 fraction is already an established standard both for scientific research and in commercially available devices, like tuners. Also, as I mentioned, this lets you compare various tunings easily. Yes, cents are not _necessary_ for anything, if you prefer you can calculate frequencies for every purpose. And by the way, Adam Neely shows how to tune bass for 24-EDO, in a similar way you could get 15-EDO. https://www.youtube.com/watch?v=H4KIwA8O9LU
Answer:
substituting 3/2 for 1/15 produces an incorrect number

This is where you made a mistake. The formula to calculate number of cents between two frequencies f₁ and f₀ is:
1200·log₂(f₁/f₀)

For perfect fifth ratio of frequencies f₁/f₀ = 3/2 (in just intonation). However for a semitone in 15-EDO ratio of frequencies is not 1/15. It is 2¹⸍¹⁵.
Then the formulae are as follows: a semitone in 12-EDO has:
1200·log₂(2¹⸍¹²) = 1200·(1/12)·log₂(2) = 1200·(1/12) = 100 cents

Similarly, a semitone in 15-EDO is
1200·log₂(2¹⸍¹⁵) = 1200·(1/15)·log₂(2) = 1200·(1/15) = 80 cents

For a "quarter-tone", that is half of a semitone, in 15–EDO substitute 2¹⸍¹⁵ with 2¹⸍³⁰ to obtain 40 cents.
Comment: This is a useful answer, but just know, OP does indicate 2^1/15 for the semitone. You may want to revise your description of where OP misunderstood the math.
Comment: @Aaron OP wrote explicitly she "substituted 3/2 with 1/15" and that's a mistake. It might be a random error or maybe misunderstanding of where which numbers should go, but this is where discrepancy in calculations originates.
Comment: Yes, I understand the error you're correcting. I just think you're explanation of what the error was isn't quite clear.
Comment: ...specifically, the second sentence of your explanation. IMO, that could be usefully clarified.
Comment: @Aaron I tried to clarify the answer. However I don't quite understand what is unclear in sentence "For a perfect fifth ratio of frequencies equals 3/2"?
Comment: IMO it reads better now.
Answer: TL;DR: This question is nonsensical.
Quarter tones simply don't exist in 12-EDO, since there is no way whatsoever to play one. They only exist in 24-EDO, and if you've added a ton of extra pitches in the middle, you are, clearly, not using 12-EDO in the first place.
Similarly, 15-EDO literally means one single step is 2^1/15, which comes to 80 cents exactly. That, and all multiples of it, are the only intervals that can even be played.
Whatever meaning you assign to a quarter tone, it's reasonable to assume it's somewhere around 50 cents, maybe a bit higher. By the plain English reading, 4 of these things should add up to a whole tone, 200 cents or so. 80 cents is just way too far off from 50 - it's more than half again as large!
A 31-cent error, for example, stands between the actual 7th harmonic, less 3 octaves, and the major second of 12-EDO. Nobody claims 12-EDO is remotely capable of representing this interval. It just doesn't exist here.
The answer is: in 15-EDO, there is no playable interval that is remotely usable as a "quarter tone".
Comment: This doesn't address the OP's issue all. If you could rephrase it in a more polite way, it could make a valid _comment_ about semantics.
Comment: Surely with guitar, trombone, violin, any extra pitches can be played.
Answer: TBH I'm a musician and piano tuner, and not a mathematician. But my understanding is that equal temperment tuning on a piano reveals a mathematical discrepancy known as the Pythagorian Comma. It has to be said that merely understanding the mathematics of the equally tempered scale does not in and of itself make someone a good piano tuner!
As to quarter-tones, this is not a term used much by musicologists. Instead, the term micro-tones are used. The best examples I can think of where micro-tones are used would be either Arabic music, or Gamalan music (from, say, Bali, Sumatra, etc.).
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://music.stackexchange.com/help/whats-reputation) you will be able to [comment on any post](https://music.stackexchange.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/75177)


Solutions verification and hints for a combinatorics exercises

Question: I have the following exercise: "Find number of ways to sit n people in a long table with n seats":
a. Everyone is seated on one-side of table: This case it's n! (ways).
b. We assume seating left to right is the same as seating right to left (seating A, B, C, ... from left to right is the same as from right to left, we only care about who each person's neighbor is): This case it's n!/2 since we exclude the overlap cases in part a.
c. n is even and half of the people are seated on each side of table: This case I believe it is 2 * (n/2)! since there are n/2 seats and n/2 people in each side.
d. We seat people on both sides as in (c) and all we care about is who a person's neighbors are on each side, as in (b).
e. We are dealing with a seating as in (d), but now we also care about who is sitting
opposite a person as well as who a persons neighbors on each side are.
I would really appreciate if anyone could verify if my answers for part a, b, c are correct as well as give me hints for part d and e.
Thank you.
Comment: Please read this [tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) on how to typeset mathematics on this site.
Answer: Your answers for (a) and (b) are alright.

Proceed in (c) as follows:
Since there are $n$ individuals, the number of ways to select the group of size $\frac{n}{2}$ to sit on one side of the table will be given by $n\choose {n/2}$ (the remaining $\frac{n}{2}$ would sit on the other side). Now once we are done splitting into two groups, we can use the logic behind (a) to obtain the answer as
$${n\choose{n/2}}\times (n/2)!\times(n/2)!$$
$$= n!$$

Proceed in (d) as follows:
The logic from (c) is to be used again. In addition, you have to now think of the cases in which neighbors will be preserved. The list of such cases for a specific arrangement has been provided below.
$\bullet$ The original arrangement
$\bullet$ Arrangement with seat reversal on one side
$\bullet$ Arrangement with seat reversal on other side
$\bullet$ Arrangement with seat reversals on both sides
It is also certain that their respective counterparts obtained by switching the sides of the table also preserve neighbors. Thus a single arrangement is being counted $8$ times.
The answer can now be obtained as
$$\bigg({n\choose{n/2}}\times (n/2)!\times (n/2)!\bigg)\times \frac{1}{8}$$
$$=\frac{n!}{8}$$

Proceed in (e) as follows:
Once again, listing out the cases where both neighbors and opposites are preserved.
$\bullet$ The original arrangement
$\bullet$ Arrangement with seat reversals on both sides
Now, switching sides for the $2$ arrangements above would also preserve neighbors and opposites. Therefore any given arrangement appears a total of $4$ times. The answer can now be obtained as
$$\bigg({n\choose{n/2}}\times (n/2)!\times(n/2)!\bigg)\times \frac{1}{4}$$
$$=\frac{n!}{4}$$
Comment: For (e), interchanging the two sides of the table would also preserve opposites and neighbors, so I think it should be $n!/4$. Of course, I have been wrong before!
Comment: @MikeEarnest I had not considered that case. Hope the edited answer is satisfactory.


When using browser-sync,why is the browser saying cannot get, while everything seems fine

Question: This is the screenshot of cmd:

I wrote
browser-sync start --server --files "app\index.html"

Answer: Looking at your screenshot it appears that your project directory is situated in the Desktop folder and is structured as follows:
confusion
│
└───app
    │
    └───index.html

In which case you could try instructing Browsersync to start a server from the app directory. If you cd to your folder named confusion then run:
browser-sync start --server "app" --files "app/index.html"
Note the addition of "app" after the --server flag.


Busca randômica não funciona

Question: Quero fazer uma busca randômica no banco de dados, porém não ta funcionando.
Quero pegar uma frase, e mostrar na tela, ela vai ser trocada toda vez que atualizar a tela.
Minha view.py:
def busca_tendencia(request):
    tendencias = Frase.objects.all().order_by('?')
    return render(request, 'busca/index.html', {'tendencias': tendencias})

No html:
{{ tendencias.frase }}

Meu models.py
class Frase(models.Model):
    titulo = models.CharField(max_length=300, blank=False)
    frase = models.TextField()
    data = models.DateTimeField(default=timezone.now)

    class Meta:
        verbose_name  = 'Frase'
        verbose_name_plural = 'Frases'

Quando acesso a página não retorna nada, nem erro. E a frase não aparece.
Comment: Possível duplicata de [Como obter resultados randômicos em SQL com diferentes SGDBs?](https://pt.stackoverflow.com/questions/294295/como-obter-resultados-rand%c3%b4micos-em-sql-com-diferentes-sgdbs)
Comment: Acho que não é duplicata @fernandosavio. Faltou o Pedro dar o contexto correto que é de uma aplicação Django e não SQL puro, ou seja, ele está usando o ORM para isso.
Comment: Tem razão @AndréDuarte. Retirei a flag, a dúvida dele me parece mais com QuerySet do que com o random em si. Obrigado!
Answer: Tendencias está retornando todos os objetos ou linhas do banco
faça assim
from random import randint
...
tendencias = Frase.objects.all().order_by('?').first()
#ou entao assim para pegar um registro realmente aleatorio
tendencias = Frase.objects.all().order_by('?')
registro_aleatorio = randint(1, tendencias.count())
tendencia = tendencias[registro_aleatorio]

Answer: Bom dia,
Amigo, dependendo do banco de dados que tu estejas usando, podes colocar uma clásula no WHERE, que jogue o randômico no id da coluna, e dar um TOP 1 (Sql server), Limit 0, 1 (postgres, mysql). Assim, ele sempre vai pegar um valor aleatório de ID, e como está em TOP 1, pegará a primeira ocorrência.
Espero ter ajudado.

Busca randômica não funciona


Como centralizar uma imagem verticalmente dentro de uma div?

Question: Fala pessoal, beleza?
Gostaria de saber existe alguma forma de centralizar uma imagem dependente de um uma outra div (que seria de texto).
Por exemplo: eu vou criar uma div e colocar uma imagem (icon) do lado esquerdo e um texto do lado direto.
O meu intuito é de colocar mais texto dentro dessa div, porém sempre que eu coloco mais texto ou tiro, tenho que centralizar a imagem de acordo com o texto "Manualmente" alterando o margin-top para que fique visualmente bonito! Queria saber como "centralizar" a imagem verticalmente na dentro da div.

.tabel{width: 100%;height: 90%;}
#espeesquertop {width: 60%;height:80%;margin-top: 5%;display:display: inline-block;}
#espeesquertop img{width:15%;margin-top: 25%;margin-left: 3%;display:}
#cont1 {float:right;width:70%;margin-right:5%;}
#cont1 p{font-size: 1em;line-height: 170%;font-family: Cambria, Cochin, Georgia, Times, 'Times New Roman', serif;}
#cont1 h2{margin-left:5%;}

Bem vindos ao Egito

Egito 1

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc

Answer: Para alinhar uma imagem no centro, primeiramente você deve definir a altura e largura dela, utilizando os atributos WIDTH E HEIGHT
Depois de definir a altura e largura, é importante você definir a posição dela, através do seguinte atributo: position:absolute
Você deverá definir uma margin-top e margin-left negativas com a metade do valor da altura e largura, por exemplo:
Se minha imagem tem 200px de altura e 200px de largura, defino margin-top:-100px; margin-left:-100px;
Depois disso você defini top:50% left:50%
Aqui é a resposta completa:

#centralizar{
    width:200px;
    height:200px;
    position:absolute;
    margin-top:-100px;
    margin-left:-100px;
    top:50%;
    left:50%;
}

Existe outros meio de centralizar as imagens:
  left: 50%;
  position: absolute;
  transform: translateX(-50%);

Caso se faça necessário centralizar dentro de um div:
div img {
    display: block;
    margin-left: auto;
    margin-right: auto;
}

Answer: Está um pouquinho bagunçado!!
É só usar display flex na div container dos itens, e em cada elemento, coloque uma div para cada e coloque um flex-basis com a porcentagem para cada elemento. Nesse caso eu coloquei somente o display flex na div pai e a imagem já centralizou, aí é só distanciar o texto ou com o flex-basis ou com o margin-left.

.tabel{width: 100%;height: 90%;}
#espeesquertop {
width: 60%;height:80%;margin-top: 5%;
display: flex;}
#espeesquertop img{width:15%;margin-top: 25%;margin-left: 3%;}
#cont1 {float:right;width:70%;margin-right:5%;}
#cont1 p{font-size: 1em;line-height: 170%;font-family: Cambria, Cochin, Georgia, Times, 'Times New Roman', serif;}
#cont1 h2{margin-left:10%;}

Bem vindos ao Egito

Egito 1

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc