Identify Windows 2012 Server core

Question: I want to detect if a 2012 server is has been setup as a Core install using WMI.  An earlier question, would seem to indicate that I can get the OperatingSystemSKU from Win32_OperatingSystem.  My Windows 2012 Core systems are reporting a OperatingSystemSKU of 7. The article from the other question would seem to indicate is a PRODUCT_STANDARD_SERVER, and if had a core install I should expect to see a value of 0x0000000D instead for PRODUCT_STANDARD_SERVER_CORE.
What am I missing here.  I eventually want to create a policy and use item level targeting to only apply that policy to Windows 2012 Server Core installs.
PS C:\Users\zoredache\Documents> gwmi -Query "select OPeratingSystemSKU,Version,ProductType from Win32_OperatingSystem"

__GENUS            : 2
__CLASS            : Win32_OperatingSystem
__SUPERCLASS       :
__DYNASTY          :
__RELPATH          : Win32_OperatingSystem=@
__PROPERTY_COUNT   : 3
__DERIVATION       : {}
__SERVER           :
__NAMESPACE        :
__PATH             :
OperatingSystemSKU : 7
ProductType        : 2
Version            : 6.2.9200

Comment: As a slight deflection to your question... How would one define server core? I read that server core is just the same with one or two less features installed (the GUI). Could you not query for that instead?
Comment: If you can provide an answer on how to detect that feature is installed via WMI, then I would upvote it, and test it out.  Any answer that can be used to identify Server core with WMI would be helpful in my opinion.
Comment: Try using WMI on the remote machines. `Get-WMIObject Win32_OptionalFeature | Select Name, InstallState` and filter on whether the server has the server GUI bits installed or not.
Answer: In PowerShell:
Get-WMIObject Win32_OptionalFeature | where Name -eq 'Server-Gui-Shell' | Select InstallState

returns 1 on a full server and 2 on a server core install.
Edit:
While my answer above is correct, there are two problems with it:

When using this command on a workstation, it returns nothing, so you have to add an extra check for this.
It is slow, when I tried it, it took between 600 and 3500
    milliseconds.

So the more pragmatic approach is to just check for the existence of a certain file:
(Test-Path "$env:windir\explorer.exe")

This returns $false for a Server Core installations and $true for all others and it takes one millisecond to execute.
Comment: Great answer - I particularly like the workaround you offer with all explanations ;) Perfect.
Answer: Funny, that MSDN article you linked contained the answer:

PRODUCT_*_SERVER_CORE values are not returned in Windows Server 2012.

This is because Server 2012 can be freely converted between "Server Core" and "full" installation simply by adding or removing the appropriate features.
You will want to check for the presence or absence of those features (e.g. Server-Gui-Mgmt-Infra, Server-Gui-Shell, Desktop-Experience).
Answer: As the GUI is just a feature, you can query the list of installed features
Just testing this in powershell on a server here worked well enough:
Dump a list of features to grab the name
Get-WmiObject Win32_OptionalFeature > features.txt

Searching the text of features.txt tells me that the feature is named 'Server-Gui-Mgmt' (other features may be installed too as Michael notes in his answer, so you can test for those too), and we can search to see if that's present
Get-WmiObject -query "select * from Win32_OptionalFeature where name = 'Server-Gui'"

Answer: I would use Win32_ServerFeature, it is a much smaller class and only contains the roles installed on the server.  Queries using Win32_Server feature should return much quicker.
Get-WmiObject -Query "Select * FROM Win32_ServerFeature WHERE Name = 'Server Graphical Shell'"

Answer: I suspect that since they are essentially the same in 2012 with just a few optional features to set them apart, you could query the features instead.
this article is a reference for the Win32_OptionalFeature class, which will allow you to query the features. The optional features are defined as Server-Gui-Mgmt-Infra, Server-Gui-Shell and Desktop-Experience, as outlined in this article.
You can query for the 3 of them and use Boolean AND and NOT logic to select servers which have none of these features installed.
Answer: Some clarification on the answers for local and remote scenarios as performance was discussed. The questioner asked WMI, and his example used PowerShell to invoke WMI.  Using WMI directly from unmanaged code is also quicker.
Please note that the approaches apply effectively to Server 2012 and Server 2012 R2, and may not apply to future releases.
Some trade offs depending on your scenario...  For most cases, Win32_ServerFeature is preferred as a general solution, or the local file check in a pinch.

Local file check: quick and dirty.  Very few moving parts.
MSFT_ServerManagerDeploymentTasks: the underlying WMI provider used by Win32_ServerFeature and Get-WindowsFeature.  It uses a local registry cache and normally returns very quickly unless there's been a configuration change since the last query.  In the event of the cache miss, it's about the same as Win32_OptionalFeature.  This is a very good interface if you're querying lots and lots of machines on a fast network and need lots of details about relationships of components and their status - but for normal use it's a pain.  Use Win32_ServerFeature instead.
Win32_ServerFeature: Generally the best all around choice for local or remote queries, but not as fast as the local file check.  Returns only installed features, and puts little traffic on the network.
Get-WindowsFeature: Very simple to use, assuming you're already using PowerShell as part of your calling path.  When calling against a remote target, this puts upwards of 400K across the network which is overkill when you just want to know if a specific feature is installed.
Win32_OptionalFeature / Get-WindowsOptionalFeature: this queries DISM on the target every time which can be pretty heavy.

That covers online local and remote scenarios.  Some of the above also will target an offline image.
Answer: I just thought I'd chime in with a WMI Filter for this solution, so you can apply GPOs to Core 2012+ systems:
SELECT * FROM Win32_OptionalFeature WHERE Caption = "Microsoft-Windows-Server-Gui-Shell-Package-DisplayName" AND InstallState = "2"

To test this on the command line:
WMIC PATH Win32_OptionalFeature WHERE "Caption = 'Microsoft-Windows-Server-Gui-Shell-Package-DisplayName' AND InstallState = 2"

I stumbled on this thread when trying to find a way to create WMI Filters for Core 2012 servers, and for some reason it didn't occur to me to have WMI check Win32_OptionalFeature (or indeed, that such a path exists). Hope this helps someone else.
Answer: On Windows Server 2012 R2, I'm using the following, performance is good while still being quite explicit.
$gui = (Get-WindowsFeature -Name 'Server-Gui-Shell').Installed

Identify Windows 2012 Server core


SO(2,1) not connected

Question: I am trying to show that $SO(2,1)$ is not connected but I have no idea where to start really, I know that it is connected if there is a path between any two points. My definition of $SO(2,1)$ is:
$SO(2,1)=\{X\in Mat_3(\mathbb{R}) \mid X^t\eta X=\eta, \ \det(X)=1\}$ where $\eta$ is the matrix defined as: $$\left ( \begin{array}{ccc} 1 &0&0\\0&1&0\\0&0&-1\end{array}\right )$$
Thanks for any help
Comment: @DominicMichaelis Lie groups are manifolds, so connectedness does imply path connectedness for $SO(2, 1)$.
Comment: @DominicMichaelis I think I've seen some authors writing on Lie algebra define "connected" as "path connected," so that may be the OP's situation. One prominent example is [Gilmore's text](http://books.google.com/books?id=ePMX38H4DD4C&printsec=frontcover&dq=gilmore+Lie+algebra&hl=en&sa=X&ei=uzqWUYKxL6ONygGc-IC4BA&ved=0CC0Q6AEwAA#v=snippet&q=connected&f=false) (just search for "connected" in the text.) Incidentally, he also uses the convention of calling the tensor product "the direct product".
Answer: Consider the orbit of the vector $(0,0,1)$ under $SO(2,1)$; you should find that it's disconnected (note that there are elements of $SO(2,1)$ which map $(0,0,1)$  to itself, or to $(0,0,-1)$, and then show that it can not be mapped to any vector $(a,b,0)$).  So this gives us a continuous map from $SO(2,1)$ to a disconnected space, which implies that $SO(2,1)$ is disconnected.
Comment: The orbit of $(0,0,1)$ under the action of $SO(2,1)$.  In fact, 'orbit' is a better word than 'image', so let me edit my answer. :-)
Comment: Ok, sorry I am a bit confused, what is the disconnected space that we are mapping to?
Comment: Ah sorry I had misread what you said slightly I understand what you are saying now. Thanks very much
Answer: Consider the transitive action of $O(2,1)$ on $N_{-1}= \{(x,y,z) \in \mathbb{R}^3 \mid x^2+y^2-z^2=-1 \}$ by left multiplication. For some $x \in N_{-1}$, you get a continuous surjection $$\left\{ \begin{array}{ccc} O(2,1) & \to & N_{-1} \\ M & \mapsto & M \cdot x \end{array} \right. .$$
So you have $SO(2,1) \hookrightarrow O(2,1) \twoheadrightarrow N_{-1}$. But $N_{-1}$ is a two-sheeted hyperboloid, and the image of $SO(2,1)$ in $N_{-1}$ is not contained in one sheet of $N_{-1}$ since $\left( \begin{matrix} 1 & 0 & 0 \\ 0 & -1 & 0 \\ 0 & 0 & -1 \end{matrix} \right) \left( \begin{matrix} 0 \\ 0 \\ 1 \end{matrix}\right) = \left( \begin{matrix} 0 \\ 0 \\ -1 \end{matrix}\right)$.

Because a continuous image of a connected set is connected, $SO(2,1)$ has at least two connected components.
In fact, it can be shown that the connected component of $SO(p,q)$ containing $\operatorname{Id}$ is $$SO_0(p,q)= \left\{ \left( \begin{matrix} A & B \\ C & D \end{matrix} \right) \in SO(p,q) \mid A \in GL_p(\mathbb{R}), \ \det(A) >0 \right\}.$$
Therefore, $SO(p,q)$ is connected iff $p=0$ or $q=0$.
Comment: Anybody knows how to center the image?

SO(2,1) not connected


Regular expressions ,php, "AND"

Question: Im trying to search for three pieces of data from a string and they are:
first name, space ,last name  (?=[A-Z][a-z]+\s[A-Z][a-z]+)
//AND
first name ,space ,last name ,and suffix (?=[A-Z][a-z]+\s[A-Z][a-z]+\s[A-Z][a-z]+)
//AND,
age   (?=[0-9]{2})

from several tutorials I've seen it seems that these three patterns:
(?=[A-Z][a-z]+\s[A-Z][a-z]+)(?=[A-Z][a-z]+\s[A-Z][a-z]+\s[A-Z][a-z]+)(?=[0-9]{2})

together should be my solution, but its not working.... any suggestions....(its a php script and im using preg_match_all)
my script:
$content = file_get_contents('http://www.somesite.com');
$pattern = '/(?=[A-Z][a-z]+\s[A-Z][a-z]+)(?=[A-Z][a-z]+\s[A-Z][a-z]+\s[A-Z][a-z]+)(?=[0-9]{2}) /';
if(preg_match_all($pattern,$content,$matches))
{
// has the pattern, do something
//$matches has all the matches from preg_match

  }

Comment: Please post your script
Comment: The string "its [sic] not working" is not a built-in error message in PHP.
Comment: Ive posted my script...i am not getting an error in my error console...
Answer: That multiple-lookahead trick is for times when you know certain components must be present, but you don't know what order they'll appear in.  You see it most often in regexes that enforce strong password policies.
Your problem is much simpler; the components always come in the same order, but the last one is optional.  That's much easier:
'/\b([A-Z][a-z]*)\s+([A-Z][a-z]*)(?:\s+([0-9]{2}))?\b/'

The first name is captured in group #1, the last name will be in group #2, and if there's a suffix you'll find it in group #3.
Answer: You're looking for an OR operator, not an AND:
[A-Z][a-z]+\s[A-Z][a-z]+|[A-Z][a-z]+\s[A-Z][a-z]+\s[A-Z][a-z]+|[0-9]{2}

If there can be multiple space characters between words, make sure to quantify the \s:
[A-Z][a-z]+\s+[A-Z][a-z]+|[A-Z][a-z]+\s+[A-Z][a-z]+\s+[A-Z][a-z]+|[0-9]{2}

And don't forget about anchors (^ and $) if you're looking for exact matches.
Answer: You can use non-capturing group (?:...) and question marks to make the groups optional:
[A-Z][a-z]+\s[A-Z][a-z]+(?:\s[A-Z][a-z]+(?:\s[0-9]{2,3})?)?

If you want to extract the data, using named captures is a clean way:
$pattern = <<<'LOD'
~
(?<first_name>[A-Z][a-z]+)
\s+
(?<last_name>[A-Z][a-z]+)
(?:
    \s+ (?<suffix>[A-Z][a-z]+)
    (?: \s+ (?<age> [0-9]{2,3}) )?
)?
~x
LOD;

preg_match_all($pattern, $subject, $matches, PREG_SET_ORDER);

foreach ($matches as $match) {
    echo '
' . $match['first_name'] . ', ' . $match['last_name'];
}

Answer: ([a-zA-Z]+\s+[a-zA-Z]+\s+[a-zA-Z0-9])

You can test your RegEx with tools like http://www.cyber-reality.com/regexy.html

Regular expressions ,php, "AND"


How to reprogram a piano for higher octave

Question: I have a Casio SA-77 piano with limited keys. I want to reprogram a button to increase my octave when I press it. Is it possible? If yes, then how?
Answer: Based on the user manual, the Casio SA-77 does not have the capability of changing octaves. The SA-76 and SA-78 also do not have this feature.
Answer: It's always worthwhile reading through the user manual when questions like this come up. However, at the price this keyboard is, and given that it has 40 odd notes only, and even if you could, you'd lose the other end of the range, it would be impractical on an instrument such as this. If you need a larger range, a 61 'board will be the absolute minimum for practical purposes. Time to go shopping..?!


How to remove .htaccess and/or htpasswd from vultr wordpress installation

Question: I fired up a server on vultr and chose wordpress. It setup htpasswd on the admin login. How can I remove that?
Here is the only .htaccess file I can find:
# Only allow direct access to specific Web-available files.

# Apache 2.2
<IfModule !mod_authz_core.c>
        Order Deny,Allow
        Deny from all
</IfModule>

# Apache 2.4
<IfModule mod_authz_core.c>
        Require all denied
</IfModule>

# Akismet CSS and JS
<FilesMatch "^(form\.js|akismet\.js|akismet\.css)$">
        <IfModule !mod_authz_core.c>
                Allow from all
        </IfModule>

        <IfModule mod_authz_core.c>
                Require all granted
        </IfModule>
</FilesMatch>

# Akismet images
<FilesMatch "^logo-full-2x\.png$">
        <IfModule !mod_authz_core.c>
                Allow from all
        </IfModule>

        <IfModule mod_authz_core.c>
                Require all granted
        </IfModule>
</FilesMatch>

I found this too. Not sure if it is helpful:
vim default.conf

    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ \.php$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;
    #    fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    #    include        fastcgi_params;
    #}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}

Comment: Login to the server and remove it.
Comment: I tried that, but since I didn't put it there I can't find it.
Comment: So this question was asked 3 years ago and it was downvoted, I had to reset it because now, 2019, I was still facing this issue, so this question IS relevant. I found the solution with @webmagnets's edits, so just for future reference.
Answer: I found the culprits here:
/etc/nginx/conf.d/wordpress_http.conf
and
/etc/nginx/conf.d/wordpress_https.conf
I commented out these lines:
#               auth_basic "Restricted";
#               auth_basic_user_file /etc/nginx/htpasswd/wpadmin;
#
#               location ~* \.(htaccess|htpasswd) {
#                       deny all;
#               }

Answer: As Orphans suggests, you do basically just "remove it". You need to remove the relevant code from the .htaccess file (probably in the protected directory), or delete the file altogether if that is the only code in it (although this being WordPress it's quite probable that there are WP specific directives there as well).
The code in .htaccess will also reference a .htpasswd file (possibly in the same directory, but not necessarily). That file should also be removed. Assuming the same file is not being used to protect other directories?
Comment: I tried ```find / -name ".htaccess" -print``` and got ```/var/www/html/wp-content/plugins/akismet/.htaccess```. I added the contents of that file to my original question.
Comment: Well, there doesn't appear to be anything to do with HTTP Authentication in that `.htaccess` file. This could also be enabled in the server config / VirtualHost. Can you find a `.htpasswd` file anywhere?
Comment: ```find / -name ".htpasswd" -print``` doesn't find anything.
Comment: How do I find the config file with the AuthUserFile directive?
Comment: It's either in the main server config file, in a VirtualHost container (which could also be in the main server config, or a separate file that is _included), or in a `.htaccess` file _anywhere_ along the file system path that is being requested (`.htaccess` files work on physical directories, not URLs). Then again, this might be entirely script (PHP) generated and there is no `AuthUserFile`!? Just to clarify, this HTTP Authentication is appearing _before_ the normal WordPress login page?
Comment: Yes. Before the login page.
Comment: I added more to my question above.
Comment: Dang, this is an Nginx server?! (Ah, just seen your tag.) Kind of thrown by your references to `.htaccess` (and `htpasswd`) - which is an Apache feature. (?!)
Comment: Oh, I see. You got me going in the right direction. Thanks.
Answer: Just remove .htpasswd file, it will disable automatically
Comment: find / -name ".htpasswd" -print doesn't find anything.
Comment: .htpasswd file is hidden by default just type  > rm -rf .htpasswd (remain in the folder where this file exist actually)
Comment: ```find / -name ".htaccess" -print``` found that hidden file. Why wouldn't it find .htpasswd?
Comment: ls -ld .?*  This will help you to find .htpasswd
Comment: I don't know what directory it is in.
Comment: It will be in root directory of your site, where you kept files of your site
Comment: The password file is not necessarily called `.htpasswd` - that is just a convention, and neither is it likely to be in the root directory (at least it shouldn't be). The file is whatever is stated in the `AuthUserFile` directive in your config file. Also, deleting the password file won't remove the HTTP Authentication - you'll still get prompted for a username/password which will now fail, and most probably followed by a 500 Internal Server Error.


How to return WebElement having particular CSS property using JavascriptExecutor?

Question: I am working on a scenario where I need to find a WebElement based on its CSS property, like background-color.
I have created the JQuery to find the element as below and it finds the webelement correctly using firefox console.
$('.search-bar-submit').each(function() {
   return $(this).css('background-color') == '#fdd922';
});

Hence, I wrote the code to find this WebElement, i.e. searchbox and then tried to click it.
driver.get("http://www.flipkart.com/");
driver.findElement(By.id("fk-top-search-box")).sendKeys("iphone");

String query ="$('.search-bar-submit').each(function() { "
            + "return $(this).css('background-color') == '#fdd922'; });";

WebElement searchbox = (WebElement) ((JavascriptExecutor)driver).executeScript(query);
searchbox.click();

When I run the program, it gives me Exception in thread "main" java.lang.NullPointerException on line searchbox.click();
Can anyone help me out find the searchbox using JavascriptExecutor and then click on it? Am I missing something silly here?
Any help is appreciated. Thanks in Advance.
Answer:
WebElement searchbox = (WebElement)
  ((JavascriptExecutor)driver).executeScript(query);

The above code calls the function but doesn't do anything with the result, ie. it doesn't return it to the caller.
Add return in the script to return the webelement to the selenium script(webdriver)
return $('.search-bar-submit').each(function() {
   return $(this).css('background-color') == '#fdd922';
});

The return type is List<WebElement>so typecast it to List if you typecast it to  it will throw an ClassCastException as arraylist cannot be cast to a webelement
Code:
 List<WebElement> searchbox = (List<WebElement>) ((JavascriptExecutor)driver).executeScript(query);

    for(int i=0;i<searchbox.size();i++){

    searchbox.get(i).click();

}

EDIT:
The code was not working in firefox because the firefox browser returns a json object of the webelement.Selenium replaced its uses of org.json with gson.So it is not able to understand the response recieved
Screenshot taken from chrome

Screenshot taken from firefox

Solution
We are using Jquery get function to retrieve the DOM Elements matched by the jquery object
$('.search-bar-submit').each(function() {
   return $(this).css('background-color') == '#fdd922';
}).get(0);

Code
    public class jquerytest
    {

        public static void main(String[] args) throws Exception {

      WebDriver driver = new FirefoxDriver();

      driver.get("https://www.flipkart.com");

      driver.findElement(By.id("fk-top-search-box")).sendKeys("iphone");

      String query ="return $('.search-bar-submit').each(function() { "
                  + "return $(this).css('background-color') == '#fdd922'; }).get(0);";

      Thread.sleep(5000);//wait till page loads replace thread.sleep by any waits

      WebElement searchbox = (WebElement) ((JavascriptExecutor)driver).executeScript(query);

      searchbox.click();

    }
}

I have tested the above code on both chrome and firefox it works perfectly
Hope this helps you.Kindly get back if you have any queries
Comment: adding return and changing WebElement to List, new exception showed up: `java.lang.ClassCastException: com.google.common.collect.Maps$TransformedEntriesMap cannot be cast to java.util.List`, I can understand there are some cast issues as in answer by @Fi Horan
Comment: Sorry for the late reply was travelling.I tested the above code it works perfectly.pls refer the above edit.Kindly check and get back
Comment: Thanks for the help. It is working with Chromedriver but for Firefoxdriver, it is showing the same cast error that i mentioned in last comment. Can you help regarding that.
Comment: @Manu Yes definetly will help you...I think this issue is caused as the return of the executescript in firefox is JSONObject but selenium currently supports only com.google.gson.JsonElement.Anyways will chk and get back to you
Comment: @Manu My assumptions turned out to be right.firefox returns webelement as a json object.I have added a solution.pls refer my edit.I tested this in both chrome and firefox it works fine.Kindly chk and get back
Comment: It's working now, thanks a lot! It indeed returned the json that was not casted to WebElement and `.get(0);` did the trick. Nice catch!
Answer: I ran the following code and it all works fine. Your jquery works as well (I love the little message they print to console in the dev view hahaha).
driver.get("http://www.flipkart.com/");
WebElement in = driver.findElement(By.id("fk-top-search-box"));
in.sendKeys("iphone");
WebElement thing = driver.findElement(By.className("fk-font-bold"));
thing.click();

I believe there's a problem with your executeScript and it should be as follows.
System.out.println(((JavascriptExecutor)driver).executeScript(query, driver));

Normally the format for my calling javascript is as follows, this would be to remove the windowed attribute so that a hyperlink would open in the same tab:
String Href = linkObject.getAttribute("href");//located the hyperlink for the documents
Href = Href.substring(0, Href.length()-10)+")";//I remove ",'windowed'" from the link to stop it opening in a new window and having to change the scripts focus
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("return arguments[0].href = \""+Href + "\"", linkObject););

But then you're getting JSON back and WebDriver can't understand that. See the following link for more information on that.
http://grokbase.com/t/gg/webdriver/12ckjcthg8/executing-javascript-that-returns-json-how-best-to-handle
Might I suggest this alternative, it gives the background-color in rgba format:
WebElement pain = driver.findElement(By.className("search-bar-submit");
pain.getCssValue("background-color");

Comment: Your alternative is welcomed, but that will not help me achieve what i intend to.
Comment: Using your code with driver as parameter gives new exception:  java.lang.IllegalArgumentException: Argument is of an illegal type: org.openqa.selenium.firefox.FirefoxDriver. Without using driver, it prints `null`.
Comment: As far as I'm aware that's because it's actually getting a response from the webpage. I'll edit my answer to show how I'd normally call javascript in webdriver.
Comment: Question still remains, why it is throwing null?
Comment: Because you're not getting any response so there's no object to reference.
Comment: Ah ok, so i need to add one more return as @vicky mentioned. But then how to cast it into WebElement?
Comment: I really don't know, it's an interesting question all right.

Might I suggest as an alternative at the end of my answer.


Formatação de gramas ou quilogramas em UITextfield no Swift 5

Question: procurei sobre isso no stack overflow e nao encontrei uma solução plausível. Se puderem me ajudar, ficarei grato!.
O objetivo:
Preciso formatar um textfield para aceitar valores em gramas ou kilogramas. por exemplo:

Valor inserido no Textfield: 0850
Valor formatado no Textfield: 0,850 Kg

Exemplo 2:

Valor inserido no Textfield: 850
Valor formatado no Textfield: 0,850 Kg
Comment: Fala Leonardo, bem vindo ao site. Para facilitar quem for responder de entender sua dúvida, seria legal você editar sua pergunta e adicionar mais alguns detalhes. Como por exemplo: O que você já tentou fazer? Poderia colocar o trecho de código referente? Deu algum erro? Em qual linha? Poderia botar mais exemplos de entrada/saída para mostrar o comportamento desejado? Se puder colocar o comportamento (errado) que você teve quando tentou fazer seria bem útil também. Um abraço e boa sorte!
Answer: Consegui resolver usando o UnitMass.grams

    public func formatWeight(weightInKgs: Double) -> String {
        let mformatter = MeasurementFormatter()
        mformatter.locale = Locale(identifier: "pt_BR")
        mformatter.unitOptions = .naturalScale
        mformatter.unitStyle = .medium
        let weight = Measurement(value: weightInKgs, unit: UnitMass.grams)
        return mformatter.string(from: weight)
    }

Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


How do I implement a single login interface for multiple providers in Azure AD B2C

Question: I have configured multiple external providers for Azure AD B2C. Right now, the user is forced to pick the provider that they want to authenticate with. How do I configure the system so that the user can type an email address, and the system can automatically forward the user to the proper IDP based on their email address. Similar to how the common authentication endpoint works for different azure domains in Azure AD work and student accounts.
Comment: What are examples of the external providers? Are they consumer identity providers such as Facebook etc.? Or do they include enterprise identity providers?
Comment: @ChrisPadgett mostly enterprise providers
Answer: Azure AD B2C does not provide any automatic IDP discovery functionality. You can request this feature in the Azure AD B2C feedback forum
You can implement this yourself by leveraging the domain_hint feature however this would require you keep your own table where you keep track of the username-to-IDP relationship. You'd then build your own page where the user can type his/her username, and based on this mapping table then redirect to B2C with the corresponding domain hint (for example, domain_hint=facebook.com)
Comment: This is similar to how Microsoft Visual Studio account validation currently determines whether the email you entered is a personal account or a business account. You'll notice that as you type in your username/email, it thinks for a bit and then redirects you to the appropriate authentication method.
Answer: I like the idea that @Saca proposed, but here's another option for consideration as well.
Have a "landing" page and let the user decide how to login, similar to how some sites will have a "login with facebook" and "login with google" links.
I would probably set a nonce value to make sure they can't login without first going to the landing page. Set a cookie so you could remember the users preference for that device/browser, and also leave an option for them to choose a different login/authentication method.
Comment: You option is fine when you have a social app that no one cares who uses it. Now tell me how this would work if you were providing services two 2 competing enterprises(and both providing IDP services) and they have to login though the same page. They could see that they are both your customers. That is a scenario that hurts a business. I could imagine 100 others where users from one organization should not know that you provide services to another organization.
Comment: I'm not sure how this approach is any different from what B2C already provides out of the box though. B2C does give you a page with buttons for each IDP...
Comment: @saca The main difference is that it allows you to set the nonce value as well as control which policy the users will use for login.
Comment: @juxhin I had not thought of the competing companies scenario. I've actually been in a scenario like that, and the previous developers had just controlled it using roles and permissions (basically, the answer from @saca). When I came onto the project, it was a permissions and roles management nightmare. It would be better to have a single instance/cluster for each customer if they each have their own IDP. It makes it easier to design when you don't have to worry (as much) about one customer gaining access to the others data.


Field Validation and Highlighting

Question: How can I get custom Form API validation to highlight a field the same way the failed #required validation does?  (See attached graphic)
Note Graphic:
1) (Green Line) Company Name is empty.  '#required' Error is noted and field is highlighted red.
2) (Blue Line) Website is incorrect.  'Custom Validation' Error is noted, but field is NOT highlighted.
How can I automatically highlight the 'Website' field on validation fail and remove it upon success?
Currently using: form_set_error('', t('Your website address is incorrectly formatted.'));
See
Answer: As the first parameter to form_set_error(), pass the name of the field to be highlighted. If it's a nested structure, pass it with square brackets, like so:
form_set_error('[your][nested][field]', 'Your Error Message');

There's a convenience wrapper around this, form_error, which takes the element instead of the string, like so:
form_error($form['your_field'], 'Your Error Message');

Also see the docs to form_set_error() (d7).
Comment: Unfortunately your suggestions did not work for me.  Neither form_error or form_set_error worked in highlighting the error field.  I do get the error message, though.  I am using hook_node_view and drupal_get_form to add a form to a node.  Maybe this is why?  Oh well
Comment: @user785179 - this must be some unrelated problem. It sounds like the FAPI element you mean to work with is not there, or is incomplete, or whatever. I recommend setting a breakpoint on the call to form(_set)_error and examine the variables. Note that `form_error` really only wraps `form_set_error`, all the former does is figure out the first parameter to the latter from the FAPI array.
Answer: Have you tried using hook_field_validate()? (edit) I just realized you are not using the new Field API but instead just the Form API. Perhaps, you can build it as a field? If you are familiar with the Form API in d6, you can pick up the Field API in a couple of hours. The Field API is another level of badassness.
i have a custom field that records business hours. I have it set that if a to day is selected there must be a from day. I more or less just implemented the example giving in api.drupal.org.
*  Implementation of hook_field_validate()
*/
function hours_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
  foreach ($items as $delta => $item) {
    if ($item['end_day'] != '--' && $item['start_day'] == '--') {
      $errors[$field['field_name']][$langcode][$delta][] = array(
        'error' => t('A from day needs to be choosen if a to day is selected. If they are the same -- forexample, Monday and Monday, the whole line when viewed will only be for Monday.'),
      );
    }
  }
}

Comment: This is going at the problem in quite a roundabout way. The Form API has standard ways of highlighting a field that failed validation.
Answer: If your form element is defined like that:
$form['panes']['webform_nid31'][0]['contact_person'] = array( ... );

your form_set_error call should look like that:
form_set_error('panes][webform_nid31][0][contact_person',
                t('You must select a name for this group of settings.'));

You need to set full path to element, without outside [ and ]. You could have many "contact_person" fields in one form, just in different branches of a form tree. Using only last index would made setting errors ambiguous, thus it's not supported. At least officially. Might work, but only as an undocumented feature.
Formatting this string is described in API:

Parameters
$name: The name of the form element. If the #parents property of your form element is array('foo', 'bar', 'baz') then you may set an error on 'foo' or 'foo][bar][baz'. Setting an error on 'foo' sets an error for every element where the #parents array starts with 'foo'.

Copied from form_set_error() field not highlited red

Field Validation and Highlighting


If $g\in{G}$ and G is a group, then the map $G\rightarrow{G}$ given by $x\mapsto{gx}$ is a bijection.

Question: Right now, I am reading Evan Chen's Napkin to study Abstract Algebra and other various topics. In lemma 1.2.5, he states:

Let $G$ be a group, and pick a $g\in{G}$. Then the map $G\rightarrow{G}$ given by $x\mapsto{gx}$ is a
bijection.

to which he asks the reader to prove this lemma. As I am not familiar with this notation, I think the map $G\rightarrow{G}$ given by $x\mapsto{gx}$ is the same as a function $f$ such that $f:G\to{G}$ and $f(x)=gx$, though I am not sure (I used Is there any difference between mapping and function? and Different arrows in set theory: $\rightarrow$ and $\mapsto$ as points of reference). Given that my assumption is right, then surjection would be proven by:

Let $y=f(x)$. Then $y=gx$ and $x=\frac{y}{g}$, demonstrating $\forall{y}\in\mathbb{R},\exists{x}\in\mathbb{R}$ such that $y=f(x)$ and proving surjectivity.

Then for injectivity, suppose $f(x_1)=f(x_2)$. Then $gx_1=gx_2$ and thus $x_1=x_2$, proving injectivity.

Thus, since $f$ is both injective and surjective, then $f$ is bijective. Similarly, this implies the map $G\rightarrow{G}$ given by $x\mapsto{gx}$ is bijective.
My main question is whether the map $G\rightarrow{G}$ given by $x\mapsto{gx}$ is the same as a function $f$ such that $f:G\to{G}$ and $f(x)=gx$. Could you also check my proof to make sure I haven't missed any considerations (such as whether I need to consider the binary operator of G). If my assumption in the main question is correct, this is just the same as proving the function $f(x)=gx$ is bijective (something very easy to do).
Comment: Your interpretation of the symbols is correct. The $\rightarrow$ is used for representing a function between the **sets**. The symbol $\mapsto$ is used to represent an element of the domain **maps to** the corresponding element of the co-domain. Regarding the proofs, the idea is okay but you need to use the inverse element $g^{-1}$ as opposed to $\frac{1}{g}$. So for surjectivity you are claiming that for $y \in G$, there exists $g^{-1}y$ that will map to $y$. Also keep in mind that $g^{-1}y$ need not be the same as $yg^{-1}$.
Comment: There is no such thing as $\frac{y}{g}$ unless the group is Abelan. You can use $g^{-1}y$, though.
Comment: @AnuragA, thanks for the clarification. If I change $\frac{y}{g}$ to $g^{-1}y$ and rewrite that $gx_1=gx_2$ implies $g^-1gx_1=g^-1gx_2$, leading to $1_Gx_1=1_Gx_2$, would the proof be correct.
Comment: @JC12 Yes that would fix it.
Comment: Btw another way to show that a function $f\colon X\to Y$ is bijective is to show that there is a function $g\colon Y\to X$ such that $f\circ g$ is the identity on $Y$ and $g\circ f$ is the identity on $X$. Such a $g$ exists if and only if $f$ is bijective and in this case, $g$ is the inverse of $f$. I think this is often the quicker way to check bijectivity.
Answer: In the surjectivity part, "$\Bbb R$" is out of place. Group definition entails that every element $g\in G$ has an inverse, namely some $g^{-1}\in G$ such that $gg^{-1}=g^{-1}g=1_G$ (here $1_G$ is the identity element of $G$, whose existence is another group axiom, and the omitted operation sign in between elements is group's operation and has nothing to do with the multiplication in $\Bbb R$). Therefore, for every $y\in G$, there is $x:=g^{-1}y$, such that $f(x)=$ $gx=$ $g(g^{-1}y)=$ $(gg^{-1})y=$ $1_Gy=$ $y$ (note that another axiom of group's definition is used in the chain, namely the associativity of group's operation). The injectivity is okay, though it may worth mentioning that the result holds for the cancellation law, which is among the very first lemmata on groups in general.


odd behavior, where cout makes the program work

Question: I have two threads in C++. One thread called alarm thread runs the function raiseAlarm() and the other thread called print thread runs the function called printMetrics. At a fixed interval, raiseAlarm sets an atomic variable to true. When the variable is true, printMetrics thread, which is spinning on the value of this atomic variable, prints some data. When I run this application, nothing happens. But if I put a cout anywhere in raiseAlarm, everything works fine. Why?
void Client::raiseAlarm()
{
    bool no = false;
    while(!stop.load(std::memory_order_acquire))
    {
        //cout << "about to sleep\n";
        this_thread::sleep_for(std::chrono::seconds(captureInterval));
        while(!alarm.compare_exchange_weak(no, true, std::memory_order_acq_rel))
        {
            no = false;
        }
    }
}

void Client::printMetrics()
{
    bool yes = true;
    while(!stop.load(std::memory_order_acquire))
    {
        while(!alarm.compare_exchange_weak(yes, false, std::memory_order_acq_rel) )
        {
            yes = true;
        }

        cout << "Msgs Rcvd: " << metrics.rcv_total.load(std::memory_order_acquire);
        cout << "Msgs Sent: " << metrics.snd_total.load(std::memory_order_acquire);
        cout << "Min latency: " << metrics.min_latency.load(std::memory_order_acquire);
        cout << "Max latency: " << metrics.max_latency.load(std::memory_order_acquire);
        metrics.reset();
    }

}

Comment: You shouldn't busy-poll using atomic variables, instead a better solution would be to use [`std::condition_variable`](http://en.cppreference.com/w/cpp/thread/condition_variable) signaling.
Comment: the classical sleep model introduces lot of latency in my case.
Answer: Just a suggestion because I'm not so savvy with concurrency in C++, but make sure you don't forget to flush your output stream. Either stick a cout << flush; after all of your cout lines or add an << endl to each one (which will automatically flush your stream).
Comment: This would be my hunch also.
Comment: Agreed. Or at least a newline somewhere.
Comment: @Jimm - It seems as though you don't have any linefeeds in your console output?  If you use std::endl, that induces an implicit flush, while sending '\n' sends a linefeed but does not flush the output.  In your case, I'd only flush at the end of the 4th line, after all of the rest had been buffered.
Comment: Nitpicking:  is `flush` a stream modifier or a method of the class?  I always used `cout.flush();`.
Comment: @ThomasMatthews It's both and they both have exactly the same effect. :)
Comment: @phonetagger - inserting `'\n'` inserts a **newline**; the particular byte or bytes that get sent are system dependent.
Comment: @PeteBecker - Newline, linefeed, same thing.  `std::endl` == `"\n" << flush`.  My point was that I didn't see any newlines in his calls to `std::cout`, so I'm guessing that perhaps the strings returned by `metrics.~~~~~()` may have `"\n"` newlines, which do produce newlines, but don't flush `cout`.  I was only adding that `std::endl`, while also producing a newline, has the added "benefit", if one chooses to see it that way, of also flushing `cout`.
Comment: @phonetagger - no, newline and linefeed are two **different** things. A carriage return moves the output position to the beginning of the current line; a newline moves the output position down to the next line without changing the horizontal position. The two motions together make up a newline.
Comment: @PeteBecker - Your own comment illustrates the muddiness of the issue.  Let's use the terms NL, CR, and LF to represent "newline", "carriage return", and "linefeed".  Your comment says, in effect, "a CR and NL together make up a NL"!  How can CR+NL == NL?  (That was rhetorical; I'm not really asking you.)  I'm sure you meant to say "a CR and LF together make up a NL".  In C and C++, the single character '\n', guaranteed to occupy a single byte, is translated upon text-mode output to the native "newline sequence" of the platform, which ***may*** be multiple bytes.  `std::endl` is the same.
Comment: @phonetagger - sorry, mis-typed. ASCII defined values for **carriage return** and **line feed**. The latter moves the output position down to the next line without changing the horizontal position. In C and C++, the character constant `'\r'` is translated into a carriage return on output; the character constant `'\n'` is translated into whatever the system requires to start a new line.


Creating users in a Windows 2016 VM server which is integrated Azure Active Directory

Question: Scenario/Problem: We need to facilitate access (user access) to an Windows 2016 VM server for couple of our colleagues in our organization.
My understanding is that we do not need to create users locally on the VM. The VM will join organization's active directory domain and users will be authenticated in organization active directory server when they want access to the VM. If it works in this manner, then I am having trouble understanding how active directory server will know these particular users have access to the VM? Or how VM will inform active directory that these users are allowed.
Sorry guys, I am new to Windows world. My basic understanding might be wrong. Please enlighten me!!
Answer: You are correct: when machines are member of an AD domain there is no need to create local accounts. User accounts 'live' in the domain and can be used to access machines that are member of the domain
In what way are your users supposed to use the server VM mentioned? Will they access file shares? Do they need to logon in a RDP session? Depending on what users need to be enabled for certain permissions have to be granted.
If they need access to file shares the accounts need to be granted access to the share and file system. If they have to be able to logon to a RDP session they will need to become member of the local group 'Remote Desktop Users' on the server.


How to control visibility of buttons in ActionColumn of yii2 GridView when using yii2 RBAC with a rule class?

Question: I understand the visibility of ActionColumn buttons can be controlled like this  :
<?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'id',
            'title',
            'body:ntext',

            // ['class' => 'yii\grid\ActionColumn'],
            [
            'class' => 'yii\grid\ActionColumn',
            'visibleButtons' =>
            [
                'update' => Yii::$app->user->can('updatePost'),
                'delete' => Yii::$app->user->can('updatePost')
            ]

          ],
        ],
    ]);
?>

I have created RBAC authorisation, and a AuthorRule Rule class based on yii2 docs
http://www.yiiframework.com/doc-2.0/guide-security-authorization.html
In case of roleParams I have achieved this like below (in view template):
if (\Yii::$app->user->can('updatePost', ['post' =>$model]){
//if the post is created by current user then do this
}

How to figure out the model or atleast id in GridView widget in order for me to do something like  :
    'visibleButtons' =>
    [
        'update' => Yii::$app->user->can('updatePost',['post' => \app\models\Post::findOne($howToGetThisId)]),
        'delete' => Yii::$app->user->can('updatePost',['post' => \app\models\Post::findOne($howToGetThisId)])
    ]

My end goal here is that for a user with author role, update and delete buttons are visible only if the post was created by that user. Any other ideas are also welcome to achieve this.
Thank you !
Answer: You can do the same with visibleButtons :
'visibleButtons' => [
    'update' => function ($model) {
        return \Yii::$app->user->can('updatePost', ['post' => $model]);
    },
    'delete' => function ($model) {
        return \Yii::$app->user->can('updatePost', ['post' => $model]);
    },
]


Array of hashmaps

Question: In python, I'd use a list of dictionaries to collect data (like name, age, height, etc.) of several people that a user enters, but now I want to do the same thing in Java. Is an array of HashMaps the best way to do that?
static List<Map<String, Object>> driverList = new ArrayList<>();

Comment: In Java you would typically define a `Person` class to hold that data.  Using a list of maps is possible, but I'd call it far from the "best" way.
Comment: Please note that array is not the same as List. One dimensional arrays are in form `Type[]` like `int[]` or `String[]` while `List` is interface and `ArrayList` is class *implementing* that interface and *using internally* array to store its elements (but is not array itself). Your question is about List of HashMaps, not Array of HashMaps.
Answer: You could do that, but a more idiomatic approach for Java would be to create a Person class that contains all the data members you want to collect. E.g.:
public class Person {
    private String name;
    private int age;
    // other properties...

    // Constructor using these properties
    // Note: this is a stylistic choice. Some would prefer a default ctor and using setters later
    public Person (String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Getters and setters for all the properties

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int numPeople = 7; // Arbitrary number for the example
        List<Person> people = new ArrayList<>(numPeople);
        for (int i = 0; i < numPeople; ++i) {
            System.out.print("Name: ");
            String name = sc.next();
            System.out.print("Age: ");
            int age = sc.nextInt();
            people.add(new Person(name, age));
        }
    }
}

Comment: Or `Person` [record](https://openjdk.org/jeps/395): `record Person ( String name , int age ) {}`

Array of hashmaps


How do I move a Drupal site from WAMP server to a live server?

Question: I'm a newbie with this so am having quite a bit of trouble. I've created a Drupal site in WAMP Server and am raedy to move the site to my hosting with Heart Internet.
I've copied C:/Wamp/www/mywebsite into a zip folder and uploaded/unzipped into my hosting space so the files are uploaded successfully.
I then went into phpMyAdmin on my computer and exported my database. I then created a blank database on my web hosting on the live server. this database username is c150-drupal and i generated a random password. I then clicked 'restore' on my new blank database and selected the database that I exported from WAMP. however I keep getting the error message below:
ERROR 1044 (420000) at line 22: access denied for user 'c150-drupal'@'%' to 'postcodedatabase'
I'm so confused how I should be exporting mysql databases in order to upload them to my webserver. Also is it acceptable to export a database from WAMP in order to use as a backup incase anything goes wrong so I could import the database back into WAMP?
Thank you,.
Comment: Have you changed your username and password in settings.php
Answer: You should check your user privilege on your production server because you can't do this action.
This thread deals with your problem : https://stackoverflow.com/questions/8838777/error-1044-42000-access-denied-for-user-localhost-to-database-db
Answer: I take it you're using phpMyAdmin on the hosting server as well?
make sure the DB names are the same for the new/empty one and the one you exported from - and if you manually changed the .sql file, make sure you changed the name in all places (CREATE and USE queries);
also check that the user has appropriate permissions for the new/empty DB - the hosting services often have it not in phpMyAdmin, but at the came place where you create DBs and users - look for something like "Add User To Database", and do exactly that - add the user to the DB with enough permissions to create/write
hope this helps


Evaluating a logistic regression model

Question: I've been working on a logistic model and I'm having some difficulties evaluating the results. My model is a binomial logit. My explanatory variables are: a categorical variable with 15 levels, a dichotomous variable, and 2 continuous variables. My N is large >8000.
I am trying to model the decision of firms to invest. The dependent variable is investment (yes/no), the 15 level variables are different obstacles for investments reported by managers. The rest of the variables are controls for sales, credits and used capacity.
Below are my results, using the rms package in R.
  Model Likelihood     Discrimination    Rank Discrim.
                         Ratio Test            Indexes          Indexes
Obs          8035    LR chi2     399.83    R2       0.067    C       0.632
 1           5306    d.f.            17    g        0.544    Dxy     0.264
 2           2729    Pr(> chi2) <0.0001    gr       1.723    gamma   0.266
max |deriv| 6e-09                          gp       0.119    tau-a   0.118
                                           Brier    0.213

          Coef    S.E.   Wald Z Pr(>|Z|)
Intercept -0.9501 0.1141 -8.33  <0.0001
x1=10     -0.4929 0.1000 -4.93  <0.0001
x1=11     -0.5735 0.1057 -5.43  <0.0001
x1=12     -0.0748 0.0806 -0.93  0.3536
x1=13     -0.3894 0.1318 -2.96  0.0031
x1=14     -0.2788 0.0953 -2.92  0.0035
x1=15     -0.7672 0.2302 -3.33  0.0009
x1=2      -0.5360 0.2668 -2.01  0.0446
x1=3      -0.3258 0.1548 -2.10  0.0353
x1=4      -0.4092 0.1319 -3.10  0.0019
x1=5      -0.5152 0.2304 -2.24  0.0254
x1=6      -0.2897 0.1538 -1.88  0.0596
x1=7      -0.6216 0.1768 -3.52  0.0004
x1=8      -0.5861 0.1202 -4.88  <0.0001
x1=9      -0.5522 0.1078 -5.13  <0.0001
d2         0.0000 0.0000 -0.64  0.5206
f1        -0.0088 0.0011 -8.19  <0.0001
k8         0.7348 0.0499 14.74  <0.0001

Basically I want to assess the regression in two ways, a) how well the model fits the data and b) how well the model predicts the outcome.  To assess goodness of fit (a), I think deviance tests based on chi-squared are not appropriate in this case because the number of unique covariates approximates N, so we cannot assume a X2 distribution. Is this interpretation correct?
I can see the covariates using the epiR package.
require(epiR)
logit.cp <- epi.cp(logit.df[-1]))

    id n x1   d2 f1 k8
     1 1 13 2030 56  1
     2 1 14  445 51  0
     3 1 12 1359 51  1
     4 1  1 1163 39  0
     5 1  7  547 62  0
     6 1  5 3721 62  1
    ...
    7446

I have also read that the Hosmer-Lemeshow GoF test is outdated, as it divides the data by 10 in order to run the test, which is rather arbitrary.
Instead I use the le Cessie–van Houwelingen–Copas–Hosmer test, implemented in the rms package. I not sure exactly how this test is performed, I have not read the papers about it yet. In any case, the results are:
Sum of squared errors    Expected value|H0           SD             Z            P
         1711.6449914         1712.2031888    0.5670868    -0.9843245    0.3249560

P is large, so there isn't sufficient evidence to say that my model doesn't fit. Great! However....
When checking the predictive capacity of the model (b), I draw a ROC curve and find that the AUC is 0.6320586.  That doesn't look very good.

So, to sum up my questions:

Are the tests I run appropriate to check my model? What other test could I consider?
Do you find the model useful at all, or would you dismiss it based on the relatively poor ROC analysis results?
Comment: Are you sure that your `x1` should be taken as a single categorical variable? That is, does every case have to have 1, & only 1, 'obstacle' to investing? I would think that some cases could be confronted with 2 or more of the obstacles, & some cases have none.
Answer: There are many thousands of tests one can apply to inspect a logistic regression model, and much of this depends on whether one's goal is prediction, classification, variable selection, inference, causal modeling, etc. The Hosmer-Lemeshow test, for instance, assesses model calibration and whether predicted values tend to match the predicted frequency when split by risk deciles. Although, the choice of 10 is arbitrary, the test has asymptotic results and can be easily modified. The HL test, as well as AUC, have (in my opinion) very uninteresting results when calculated on the same data that was used to estimate the logistic regression model. It's a wonder programs like SAS and SPSS made the frequent reporting of statistics for wildly different analyses the de facto way of presenting logistic regression results. Tests of predictive accuracy (e.g. HL and AUC) are better employed with independent data sets, or (even better) data collected over different periods in time to assess a model's predictive ability.
Another point to make is that prediction and inference are very different things. There is no objective way to evaluate prediction, an AUC of 0.65 is very good for predicting very rare and complex events like 1 year breast cancer risk. Similarly, inference can be accused of being arbitrary because the traditional false positive rate of 0.05 is just commonly thrown around.
If I were you, your problem description seemed to be interested in modeling the effects of the manager reported "obstacles" in investing, so focus on presenting the model adjusted associations. Present the point estimates and 95% confidence intervals for the model odds ratios and be prepared to discuss their meaning, interpretation, and validity with others. A forest plot is an effective graphical tool. You must show the frequency of these obstacles in the data, as well, and present their mediation by other adjustment variables to demonstrate whether the possibility of confounding was small or large in unadjusted results. I would go further still and explore factors like the Cronbach's alpha for consistency among manager reported obstacles to determine if managers tended to report similar problems, or, whether groups of people tended to identify specific problems.
I think you're a bit too focused on the numbers and not the question at hand. 90% of a good statistics presentation takes place before model results are ever presented.
Comment: Thank you Adam for your response! I do base most of my analisis on odds ratios interpretation and predicted probabilities. But since Im not too confortable yet with logistic regression, I fear my analysis could be dismissed because Im missing some general model fit test. But as you said, I also belive I should focus on the more substancial interpretation of the model. I will consider your recomentdations for forest plots and Cronbach´s Alpha as well. Thanks again!
Comment: The only legitimate potential violation of model assumptions would be correlated data, given your problem description. Bearing that in mind, you can do a [test of dispersion with the quasibinomial regression model](http://faculty.washington.edu/heagerty/Courses/b571/handouts/OverdispQL.pdf), or you can attempt to do subgroup analyses by industry types (for the various firms you mentioned), or again try cluster analyses.

Evaluating a logistic regression model


How to derive Camera Jacobian

Question: I'm dealing with a Kalman Filter situation, trying to track points in 3D using cameras, each of which can represent a 3D point as a 2D projection according to:
$$ \begin{bmatrix} u \\ v \end{bmatrix}  = \begin{bmatrix} \alpha_x & \gamma & u_0 \\ 0 & \alpha_y & v_0 \end{bmatrix} \cdot R_{3\times3} \cdot \begin{bmatrix} x \\ y \\ z \end{bmatrix} + \begin{bmatrix} \alpha_x & \gamma & u_0 \\ 0 & \alpha_y & v_0 \end{bmatrix} \cdot \vec{T}_{3\times1} $$
Where $u$ and $v$ are the pixel coordinates of a point in camera frame; $ \begin{bmatrix} \alpha_x & \gamma & u_0 \\ 0 & \alpha_y & v_0 \end{bmatrix} $ is the upper two rows of the camera matrix $K$, $R_{3x3}$ is a rotation matrix describing the rotation of the world coordinate frame relative to the camera; and $\vec{T}_{3x1}$ is a translation that describes the position of the world coordinate frame relative to the camera.
I'd really like this to be in the form
$$ \vec{y} = H \vec{x} $$
I've seen this $H$ called the "observation matrix" and in other cases the "Jacobian". But Jacobian would imply a structure like
$$ \begin{bmatrix} \frac{\partial y_1}{\partial x_1} & \frac{\partial y_1}{\partial x_2} & \frac{\partial y_1}{\partial x_3} \\ \frac{\partial y_2}{\partial x_1} & \frac{\partial y_2}{\partial x_2} & \frac{\partial y_2}{\partial x_3} \end{bmatrix} $$
and it's not clear to me that this would actually give you $\vec{y}$ from $\vec{x}$.
So I guess I have a few questions:

How can I derive a single $H$ to put my transformation in a form a Kalman filter can handle?

Should I use homogeneous coordinates (tack on some 1s) instead? Would the Kalman filter update to the state reliably keep its last entry a 1 then?

I could make my $\vec{y} = \begin{bmatrix} u \\ v \end{bmatrix} - \begin{bmatrix} \alpha_x & \gamma & u_0 \\ 0 & \alpha_y & v_0 \end{bmatrix} \cdot \vec{T}_{3\times1}$, but this really isn't what I want.

Does keeping the additive term on the right make this nonlinear? $\vec{y} = H_{2\times3} \vec{x} + K_{2\times3}\vec{T}_{3\times1} \rightarrow \vec{y} = \tilde{H}(\vec{x}) $? How does this then relate to the Jacobian?
Answer: I've made some progress.
First, my camera equation was definitely wrong: I was missing a division by range to object. This video is what caused me to see the light. Really:
$$ \begin{bmatrix} u \\ v \end{bmatrix} = K_{2\times3} \cdot \begin{bmatrix} x' \\ y' \\ z' \end{bmatrix}/z' $$
where
$$ \begin{bmatrix} x' \\ y' \\ z' \end{bmatrix} = R_{3\times3} \cdot \begin{bmatrix} x \\ y \\ z \end{bmatrix} + \vec{T}_{3 \times 1} \tag{1}$$
The primed ($'$) variables represent coordinates of the thing you're trying to project in to camera in the camera's reference frame, and the unprimed variables represent coordinates in the world frame. I'm trying to find $H$ w.r.t. the world frame.
This makes
$$ u = \frac{\alpha_x x'}{z'} + u_0 $$
$$ v = \frac{\alpha_y y'}{z'} + v_0 $$
If you follow the Jacobian equation that I left above in the question (very carefully, taking derivatives w.r.t. $x$ and friends rather than $x'$ and other friends) through a page and a half of calculus and simplifying linear algebra, you eventually end up with
$$ Jacobian_{2\times3} = \frac{KR}{z'} - \frac{K\vec{x'} \otimes R_3}{z'^2} $$
where $ \vec{x'} = \begin{bmatrix} x' \\ y' \\ z' \end{bmatrix} $, $R_3$ is the third row of the $R$ matrix, and $\otimes$ is an outer product.
Note that you can optionally include translation before rotation in equation (1), and it makes no difference to the derivatives because $x$, $y$, and $z$ don't appear in the translation term.
Second, there is a distinction to be made between system evolution and observation functions and the Jacobians. These tend to blur together because in the linear case multiplying by the Jacobian is the same as evaluating the function. Take the example $y_1 = ax_1 + bx_2$, $y_2 = cx_1 + dx_2$. Then we can write the system as:
$$ \begin{bmatrix} y_1 \\ y_2 \end{bmatrix} = \begin{bmatrix} a & b \\ c & d \end{bmatrix} \begin{bmatrix} x_1 \\ x_2 \end{bmatrix} $$
But also
$$ \begin{bmatrix} \frac{\partial y_1}{\partial x_1} & \frac{\partial y_1}{\partial x_2} \\ \frac{\partial y_2}{\partial x_1} & \frac{\partial y_2}{\partial x_2} \end{bmatrix} = \begin{bmatrix} a & b \\ c & d \end{bmatrix} $$
This is convenient if you need to both find $\vec{y}$ from $\vec{x}$ and do other things like project covariance matrices around, but in a nonlinear system you do these things by separate methods:

Notice the first line uses $h(x)$, but on subsequent lines we use the Jacobian $H$ evaluated at $x$. Likewise at the update step we use $f(x)$ to evolve the system and $F$ evaluated at $x$ to update covariance.
Now to specifically answer my questions:

You don't just get a single $H$; you need both $H(\vec{x})$ and $h(\vec{x})$, evaluated at $\vec{x}$ because the nonlinearity makes the shape vary from place to place.

No, don't use homogeneous coordinates. This is actually so nonlinear (thanks to that division by $z'$) that you're definitely going to need to use the Jacobian anyway. Not sure whether a filter could ever be trusted to keep a state variable stationary. If there were no noise in that variable and the update equations were just so, maybe? Irrelevant here now.

That subtraction isn't..nope.

I think linearity isn't actually violated by that additive term, since that's just an offset. But linearity is violated here after all.
Comment: Regarding the last point: This is in fact not a linear map, as linearity means that $f(\lambda_1 x_1 + \lambda_2 x_2)=\lambda_1 f(x_1)+ \lambda_2 f(x_2)$. What you have here is an _affine_ map.
Comment: Ah, yes, technically you're right.

How to derive Camera Jacobian


Consulta jQuery-Ajax com PHP

Question: Fiz um código com jQuery-Ajax. Afim de consultar o banco sem muita complicação ou objeções, Apenas  SELECT * FROM produto. O resultado foi certo, a partir do momento em que tentei fazer uma consulta com filtro usando a tag <select><option> e mandando por ajax a resposta ir para PHP tentando mudar para  SELECT * FROM produto WHERE Tipo='$_POST[Tipo]' ele não me retorna nada no site. Quando eu faço a inspeção para ver ele tem algum erro no NETWORK ele mostra a pesquisa certinha por categoria mas não exibe ela no site.
$(document).ready(function () {
    $("#Tipo").on('change', function () {
        var Tipo = ($(this).val());
        $.ajax({
            type: 'POST',
            url: '../php/cardapio.php',
            data: {
                Tipo: Tipo,
            },
            success: function () {

            }
        });
        return false;
    });
});

                Categoria:

                <select id="Tipo" name="Tipo" class="select">
                    <option value="todos" selected>Todos</option>
                    <option value="acais">Açais</option>
                    <option value="tapiocas">Tapiocas</option>
                    <option value="marmitas">Marmitas</option>
                    <option value="bebidas">Bebidas</option>
                </select>

    <?php

        $pasta = '../img/img_produto/';
        $imagem = glob("$pasta{*.jpg,png,jpeg}", GLOB_BRACE);
        $Tipo = $_POST['Tipo'];
        $result_produto = "SELECT * FROM produto WHERE Tipo='$Tipo'";
        $resultado_produto = mysqli_query($conn, $result_produto);
        while($row_produto = mysqli_fetch_assoc($resultado_produto)){

     echo"

".$row_produto['Nome_produto']."

".$row_produto['Descricao_produto']."

" .$row_produto['Preco_produto']. "

                    <button class='btn button-cardapio'>Adicionar</button>

        ";
            };
?>

Comment: Você pode fazer um teste para ver se seu arquivo PHP esta funcionando, muda isso `$_POST['Tipo']` para isso `$_GET['Tipo']` e depois tenta acessar a url pelo browser `http://seusite.com/php/cardapio.php?Tipo=Bebidas`, veja sé o resultado é o esperado.
Answer: Verifique no PhpMyAdmin se a sua consulta está de fato retornando algum registro.
Verifique também os valores dos dados que estão sendo passados pelo ajax.
No javascript:
success: function(data) {
  console.log(data); // Acesse o console do navegador para visualizar
}

No php:
echo $_POST['Tipo'];

Dessa forma você provavelmente chegará no resultado que deseja obter. É importante ressaltar, também, que no código informado nada está sendo feito com o retorno de dados do PHP. Isso deve ser feito no success.
Exemplo
success: function(data) {
  $('#cardapio').html(data);
}

Consulta jQuery-Ajax com PHP


Criar um link que ao ser clicado pego o seu texto

Question: Tenho uma tabela que tem o ID do Material e o Nome, o nome é um link, preciso fazer com que quando eu clicar no link ele pegue o ID e o nome o coloque em um campo de texto no fomulário.
A tabela é gerada dinamicamente por um script
$('#tbl').append("
 " + item.ID +
                        "	" + item.Nome + "<\a>
")

Estou tentando pegar o texto do link assim:
function Seleciona(event) {
    var id = event.ID
    var nome = event.Nome

    $('#ID').val(ID);
    $('#nome').val(nome);

    $(this).dialog("close");
}

Comment: Esse código está a precisar de umas correções.. Quando fazes o `append` tens tags mal, não estás a enviar nada para a função `Seleciona`
Comment: o que devo passar para a função Seleciona?
Comment: já fiz uma resposta com as edições necessárias
Answer: Na construção da tua tabela envias o teu item.ID principal que vai definir cada td (também tinhas uns erros nas tags):
$('#tbl').append("
 " + item.ID +
                        "	" + item.Nome + "
")

Na função Seleciona recebes um idlinha que corresponde ao teu item.ID, para poder tratar de ir buscar os dados do id e do nome :
function Seleciona (idlinha) {
    var id = $("#tdID_" + idlinha).html();
    var nome = $("#tdNome_"+idlinha+" a").text();

    $('#inp_ID').val(id);
    $('#inp_Nome').val(nome);

    $(this).dialog("close");
}

Exemplo funcional:

Seleciona = function (idlinha) {
    var id = $("#tdID_" + idlinha).html();
    var nome = $("#tdNome_"+idlinha+" a").text();

    $('#inp_ID').val(id);
    $('#inp_Nome').val(nome);

    $(this).dialog("close");
}

        12

            Fernando Trambolho

<input type="text" id="inp_ID"/>
<input type="text" id="inp_Nome"/>
Answer: Minha sugestão é você já pré carregar o seu link passando os valores para o método Seleciona.
Veja Funcionando:

   $(function () {
            $('#tbl').append("
 " + 1 +
            "	" + "Teste" + "<\a>
")

        });
        function Seleciona(id, nome) {
            $('#ID').val(id);
            $('#nome').val(nome);
        }

    <input type="text" id="ID" />
    <input type="text" id="nome" />
Comment: e de forma simples. +1
Comment: @CesarMiguel a sua está bem prática tbm. Obrigado.
Comment: Em tabelas mais complexas é capaz de ser melhor, mas para o que o Alan quer não justifica :P


Global using do C# está atrapalhando, como desligar isso?

Question: Fui tentar usar o mecanismo relatado em Não precisa mais em C# usar método, classe, namespace e using? e não ficou legal.
Importou namespace que eu não queria e causou conflito com o que eu usava.
Pode usar o recurso, mas controlando o que é importado? Ou pelo menos posso não usar, já que agora cria um projeto e ele está lá sempre.
Answer: Por padrão agora novos projetos começam com um arquivo chamado GlobalUsings.g.cs onde existem os global usings que ele usará. Você pode mudar o que está lá no arquivo (ainda que o mais recomendado seja não mexer diretamente neles.
Pode até mesmo mudar o template que é usado para gerá-lo, mas não recomendo fazer, se for o caso crie um template novo e passe usar no lugar.
Se quiser que não crie isso pode usar --use-program-main no dotnet CLI. Ou fazer pelo Visual Studio:

Além disso é possível configurar no projeto que algum deles não devem ser usados implicitamente:
<ItemGroup>
  <Using Remove="System.Net.Http" />
</ItemGroup>

Ou pode desabilitar completamente o uso implícito:
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    ...
    <ImplicitUsings>disable</ImplicitUsings>
  </PropertyGroup>

</Project>

Você pode adicionar também:
<ItemGroup>
    <Using Include="SuperheroApp.Models"/>
    <Using Include="System.Console" Static="True" />
    <Using Include="System.DateTime" Alias="DT" />
</ItemGroup>

Via código, pontual e diretamente na hora do uso, não é possível fazê-lo, ainda, pra mim é uma falha.
Algumas pessoas estão adotando este mecanismo só quando vão fazer scripts e não para aplicações, outras vão mais fundo.
Conteúdo do arquivo gerado para um projeto Console:
// <auto-generated/>
global using global::System;
global using global::System.Collections.Generic;
global using global::System.IO;
global using global::System.Linq;
global using global::System.Net.Http;
global using global::System.Threading;
global using global::System.Threading.Tasks;

Coloquei no GitHub para referência futura.


Implementing binary logistic regression from scratch

Question: Background knowledge:
To train a logistic regression model for a classification problem with two classes (called class $0$ and class $1$), we are given a training dataset consisting of feature vectors $x_1, x_2, \ldots, x_N \in \mathbb R^d$ and corresponding target values $y_1, y_2, \ldots, y_N \in \{0,1\}$. Our goal is to find numbers $\beta_0, \beta_1, \ldots, \beta_d \in \mathbb R$ such that
$$
\tag{1} y_i \approx \sigma(\beta_0 + \beta_1 x_{i1} + \cdots + \beta_d x_{id}) \quad \text{for } i = 1, \ldots, N.
$$
Here $x_{i1}, \ldots, x_{id}$ are the components of the feature vector $x_i$, and $\sigma:\mathbb R \to \mathbb R$ is the sigmoid function (also called "logistic function") defined by
$$
\sigma(u) = \frac{e^u}{1 + e^u} \quad \text{for all } u \in \mathbb R.
$$
The sigmoid function is useful in machine learning because it converts a real number into a probability (that is, a number between $0$ and $1$).
Equation (1) can be expressed more concisely using vector notation: we hope that
$$
y_i \approx \sigma(\hat x_i^T \beta) \quad \text{for } i = 1, \ldots N
$$
where
$$
\hat x_i = \begin{bmatrix} 1 \\ x_{i1} \\ \vdots \\ x_{id} \end{bmatrix} \quad \text{and} \quad \beta = \begin{bmatrix} \beta_0 \\ \beta_1 \\ \vdots \\ \beta_d \end{bmatrix}.
$$
(The vector $\hat x_i$ is called an "augmented" feature vector. It's the vector you get by prepending a $1$ to $x_i$.)
I think of $\sigma(\hat x_i^T \beta)$ as being a "predicted probability" which tells you how strongly our model believes that example $i$ belongs to class $1$. And $y_i$ is
a "ground truth" probability which reflects certainty about whether or not example $i$ belongs to class $1$.
We will use the binary cross-entropy loss function
$$
\ell(p,q) = -p \log(q) - (1 - p) \log(1 - q)
$$
to measure how well a predicted probability $q \in (0,1)$ agrees with a ground truth probability $p \in [0,1]$. Here $\log$ denotes the natural logarithm. The vector $\beta$ will be chosen to minimize the average cross-entropy
$$
\tag{2} L(\beta) = \frac{1}{N} \sum_{i=1}^N \ell(y_i, \sigma(\hat x_i^T \beta)).
$$
We can minimize $L(\beta)$ using an optimization algorithm such as gradient descent, stochastic gradient descent, or Newton's method. In order to use such methods, we need to know how to compute the gradient of $L$. For Newton's method, we also need to know how to compute the Hessian of $L$.
Question:
How can we compute the gradient and the Hessian of the average cross-entropy function $L(\beta)$ defined in equation (2)?
The goal is to compute the gradient and the Hessian of $L$ with finesse, making good use of vector notation.
(I'll post an answer below.)
Comment: The folks (including myself) over at http://stats.stackexchange.com/ would have appreciated this Q&A too :)
Answer: Notice that
$$
L(\beta) = \frac{1}{N} \sum_{i=1}^N h_i(\hat x_i^T \beta)
$$
where $h_i: \mathbb R \to \mathbb R$ is the function defined by
$$
h_i(u) = \ell(y_i, \sigma(u)).
$$
The sigmoid function and the cross-entropy loss function are natural companions, and they are happy to be combined together into the function $h_i$. By the chain rule,
$$
L'(\beta) = \frac{1}{N} \sum_{i=1}^N h_i'(\hat x_i^T \beta) \hat x_i^T.
$$
So, to compute $L'(\beta)$, we only need to figure out how to evaluate $h_i'(u)$. But this must be easy because $h_i$ is a function of a single variable. Evaluating $h_i'(u)$ is a routine exercise in single-variable calculus.
Before we take the derivative of $h_i$, let's first simplify $h_i(u)$ as much as possible:
\begin{align}
h_i(u) &= -y_i \log(\sigma(u)) - (1 - y_i) \log(1 - \sigma(u)) \\
&= -y_i \log(\frac{e^u}{1+e^u}) - (1 - y_i) \log(\frac{1}{1 + e^u}) \\
&= -y_i (u - \log(1 + e^u)) + (1 - y_i) \log(1 + e^u) \\
&= - y_i u + \log(1 + e^u).
\end{align}
Look how much $h_i(u)$ simplified! The sigmoid function and the cross-entropy loss function are meant to be together. This is why PyTorch offers the "binary cross-entropy with logits" loss function.
Now we are ready to take the derivative:
$$
h_i'(u) = -y_i +\frac{e^u}{1 + e^u} = \sigma(u) - y_i.
$$
This is a beautiful and delightfully simple formula. Interpretation: If the predicted probability $\sigma(u)$ agrees perfectly with the ground truth probability $y_i$, then $h_i'(u)$ is zero, suggesting that no change to the value of $u$ is necessary.
Putting the above pieces together, we see that
$$
L'(\beta) = \frac{1}{N} \sum_{i=1}^N (\sigma(\hat x_i^T \beta) - y_i) \hat x_i^T.
$$
If we use the convention that the gradient is a column vector, then
$$
\nabla L(\beta) =  L'(\beta)^T = \frac{1}{N} \sum_{i=1}^N (\sigma(\hat x_i^T \beta) - y_i) \hat x_i.
$$

Next let's compute the Hessian of $L$. The Hessian matrix $H L(\beta)$ is the derivative of the function
$$g(\beta) = \nabla L(\beta)= \frac{1}{N} \sum_{i=1}^N  \hat x_i (\sigma(\hat x_i^T \beta) - y_i).
$$
To compute the derivative of $g$, it is helpful to know that
$$
\sigma'(u) = \sigma(u) - \sigma(u)^2,
$$
which is a beautiful result that you can easily check.
Again using the chain rule, we find that the derivative of $g$ is
\begin{align}
g'(\beta) &= \frac{1}{N} \sum_{i=1}^N \hat x_i \sigma'(\hat x_i^T \beta) \hat x_i^T \\
&= \frac{1}{N} \sum_{i=1}^N (\sigma(u_i) - \sigma^2(u_i)) \hat x_i \hat x_i^T
\end{align}
where $u_i = \hat x_i^T \beta$.
So we have found our Hessian matrix $HL(\beta) = g'(\beta)$. Having computed the gradient and Hessian of $L$, it is now straightforward to train a logistic regression model from scratch using gradient descent or Newton's method in a language such as Python.


Diferenca entre tabelas, criterios

Question: Tenho duas tabelas como a seguir:Quero obter os dados que estão na Tabela da esquerda e que não estão na da direita. Como as duas tabelas possuem um campo em comum, CPF, eu quero gerar uma outra tabela apenas com os CPFs que estão na tabela da esquerda, mas que não constam na da direita.
 trtreterter
Comment: Talvez fosse mais facil de entender se colocasses um exemplo da tabela que queres obter como resultado baseado nessas imagens, porque tal como está descrito é confuso. Vale a pena ver isto: https://pt.stackoverflow.com/tour
Comment: Não entendo o que a pergunta tem haver com [tag:pandas] (biblioteca python), poderia explicar a ligação da pergunta com isto? Quer, usando pandas, obter esses dados?
Comment: Como não entende? Sei q o pandas faz isso e muito bem, extraindo a diferenca entre as tabelas; já vi isso em video do youtube e nao to achando
Comment: Bem, eu fiz assim: nomeei o dataframe da esquerda como "novoPas" e o da direita como "novaFolha", e criei a variavel novoResultado, com o resultado da diferença dos dois. Ficou assim: novoResultado = novoPas - novaFolha. Ao rodar esse comando, tive o seguinte resultado:
Answer: Bem, eu fiz assim: nomeei o dataframe da esquerda como "novoPas" e o da direita como "novaFolha", e criei a variavel novoResultado, com o resultado da diferença dos dois. Ficou assim: novoResultado = novoPas - novaFolha. Ao rodar esse comando, tive o seguinte resultado. Aparentemente, o que não esta como NAN é justamente o valor da diferença(o que não esta em uma planilha, mas está na outra). Eu fui conferindo, so pra ter certeza e o que aparece embaixo que nao seja NAN realmente não consta em uma das tabelas. É isso mesmo q eu quero, mas alguem pode me explicar por que?
<code>0   NaN NaN NaN NaN NaN NaN
1   NaN NaN NaN NaN NaN NaN
2   3.145070e+10    NaN NaN NaN NaN NaN
3   NaN NaN NaN NaN NaN NaN
4   NaN NaN NaN NaN NaN NaN
5   NaN NaN NaN NaN NaN NaN
6   6.819145e+10    NaN NaN NaN NaN NaN
7   NaN NaN NaN NaN NaN NaN
...
</code>
Comment: Minha necessidade eh exatamente a desse cara; vou tentar fazer o q ele fez e retorno se deu certo: https://pt.stackoverflow.com/questions/130338/comparar-campos-em-dois-conjuntos-de-dados?rq=1
Answer: Consegui o q o queria com essa solução q citei no link. Como eu queria q me retornasse a tabela da esquerda q não esta na direita, usei atual.where(~atual['CPF Favorecido'].isin(seguinte['CPF Favorecido'])).count()
Grato.

Diferenca entre tabelas, criterios


Number of positive integers in [1,1e18] that cannot be divided by any integers in [2,10]

Question: I am having difficulty trying to solve the following problem:

For Q queries, Q <= 1e6, where each query is a positive integer N, N <= 1e18, find the number of integers in [1,N] that cannot be
  divided by integers in [2,10] for each query.

I thought of using using a sieve method to filter out numbers in [1,1e18] for each query (similar to sieve of eratosthenes). However, the value of N  could be very large. Hence, there is no way I could use this method. The most useful observation that I could make is that numbers ending with 0,2,4,5,6,8 are invalid. But that does not help me with this problem.
I saw a solution for a similar problem that uses a smaller number of queries (Q <= 200). But it doesn't work for this problem (and I don't understand that solution).
Could someone please advise me on how to solve this problem?
Comment: belongs on math.stackexchange.com
Answer: The only matter numbers in [2,10] are those primes which are 2, 3, 5, 7
So, Let say, the number cannot be divided by integers in [2,10] is the number cannot be divided by {2,3,5,7}
Which is also equalled to the total number between [1,n] minus all number that is divided by any combination of {2,3,5,7}.
So, this is the fun part: from [1,n] how many numbers that is divided by 2?
The answer is n/2 (why? simple, because every 2 number, there is one number divided by 2)
Similarly, how many numbers that is divided by 5? The answer is n/5
...
So, do we have our answer yet? No, as we found out that we have doubled count those numbers that divided by both {2, 5} or {2, 7} ..., so now, we need to minus them.
But wait, seems like we are double minus those that divided by {2,5,7} ... so we need to add it back
...
Keep doing this until all combinations are taken care of,
so there should be 2^4 combination, which is 16 in total, pretty small to deal with.
Take a look at Inclusion-Exclusion principle for some good understanding.
Good luck!
Comment: +1 Thanks for explaining! I understand the code now.  The TLE was because the code that I linked in my post was flushing the output on each query.
Answer: Here is an approach on how to handle this.
The place to start is to think about how you can split this into pieces.  With such a problem, a place to start is the least common denominator (LCD) -- in this case 2,520 (the smallest number divisible by all the numbers less than 10).
The idea is that if x is not divisible by any number from 2-10, then x + 2,520 is also not divisible.
Hence, you can divide the problem into two pieces:

How many numbers between 1 and 2,520 are "relatively prime" to the numbers from 2-10?
How many times does 2,520 go into your target number?  You need to take the remainder into account as well.
Comment: @user3386109 . . . I actually realize the optimizations that can be made on the problem.  The idea was to give the OP an approach for solving it.


Is it OK to replace a harp string with an adjacent string?

Question: I'm trying to fix up my girlfriend's Salvi concert harp, but just as I finally got the whole thing stringed and tuned, another string broke, and sadly, we did not have this specific string in stock.
However, I figure that it can't hurt all that much to use a different string. She uses Bow Brand natural gut strings; we need a 3rd octave D, and I'm contemplating to use a 3rd octave E string.
Is this OK with a harp, or is this considered bad practice?
Answer: It's obviously better to replace the string with its actual string, but as I'm sure you're aware the adjacent strings are a similar gauge and should not pose any issues, if you don't make a habit out of it. I'd suggest stringing it up with the 3rd octave E String and ordering a replacement string as soon as possible.
It would be more harmful to leave that string unstrung. I string my harp with gut strings from octaves 6-3 and octaves 2-1 with nylon strings. I also keep a full set of nylon strings as my backup in case a string breaks and I do not have that gut string anymore. The price for nylon strings is a lot cheaper. I would highly suggest keeping a spare set of nylon strings or two for events like this. Then swap out the nylon string when you get your gut strings in. The only downside to this is that the tonality of the harp will change a bit due to the differences of strings in the same octave.
Comment: You're welcome. You'll be fine leaving it unstrung for another day, in order for there to be any noticeable detrimental effects to the harp, you would have to leave it unstrung for several months, or have it missing several strings for prolonged periods. A week or two without a string should not harm your harp.
Comment: Thanks for the info; how bad is it to leave it unstrung for just another day? Then I'll have a new string. She does actually keep a full set of spare strings, but of course the one that breaks is accidentally not stocked. (I'll accept your answer tomorrow if no other replies are posted)


Fill a form on one website and second website automatically grabs it

Question: I have two websites, which have exactly same forms and fields. When the user fills the form on first website, the content gets published on first website. I manually do it on another website. Is there any simpler way of doing this? Is it possible that it automatically grabs the data from 1st website as user fills the form?
Comment: Can people fill out the form on both sites? If so you could potentially run into problems with submission IDs getting out of sync. You can use things like services and feeds to pass data between sites but I'm not sure how much support those things have for forms. This is not a simple task and it is too hard to properly answer without having complete information about your websites. There are a lot of possible solutions for sharing data, it comes down to the specifics of the site as to which is the best.
Comment: For example we know nothing about your form. Node form, webform, custom form, something else. We don't know your business rules. We don't know how each of the two sites are used. And there are a bunch more things we don't know that would help in determining possible solutions.
Answer: You can do this with a bit of JQuery. Assuming your form action is action1.php which is on site 1 and you have another handler action2.php on site 2:
<code>$('#form_id').submit(function(event){
    event.preventDefault();  // Stop default handling
    var $form = $(this);
    $.ajax({
        type: 'post',
        url: 'action2.php',  // Submit to the second site
        data: $th.serialize(),
        success: function(){
            $th.submit();    // Submit to the first site
        }
    });
});
</code>
And now the form will be submitted to both sites and they will both handle it
Comment: On which site do I have to use this code? and in the url, actually I can't give action2.php as it is not on the same machine.
Comment: you can put it on any of the sites, or on both sites if you need either site's form to submit to itself and to the other. I know you can't give action2.php, you need to give the full submit url: http://www.mysite.com/.....
Comment: This will also not work in the (admittedly uncommon) case that the user has javascript disabled.


Posicionamento com display: flex

Question: Estava fazendo uma página de exercício e tive uma dúvida com display: flex. Veja o exemplo. Tenho uma DIV centralizada e dentro dela outras DIVs menores.

Abaixo o HTML
<!DOCTYPE html>

<link rel="stylesheet" href="teste.css">

No caso acima usei justify-content: space-around e flex-wrap: wrap. Nas linhas onde há 3 itens fica legal, mas na última linha onde tem dois ele centraliza.
Sei que isso é por causa do space-around. Eu gostaria de saber se tem alguma forma dos itens da última linha ficarem alinhados abaixo (primeira e segunda coluna) mas ainda usando display: flex para manter o ajuste do conteúdo conforme a dimensão da janela?
Segue meu CSS
* {
    margin: 0;
    padding: 0;
}

html, body {
    width: 100vw;
    height: 100vh;
    overflow: hidden;
}

.centro {
    width: 80%;
    height: 50%;
    border: 2px solid #808080;
    transform: translate(10%,50%);
    padding: 5px;
    overflow-y: auto;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
}

.conteudo {
    width: 230px;
    height: 230px;
    border: 5px dashed #808080;
}

Answer: O justify-content alinha os itens flex no container de acordo com a direção. A propriedade só funciona se os itens atuais não ocuparem todo o container. Isso significa que ao definir flex: 1; ou algo similar nos itens, a propriedade não terá mais função.
Logo existem as seguintes propriedades para o justify-content, as quais são:
// Alinha os itens ao início do container.
justify-content: flex-start;

// Alinha os itens ao final do container.
justify-content: flex-end;

// Alinha os itens ao centro do container.
justify-content: center;

// Cria um espaçamento igual entre os elementos. Mantendo o primeiro grudado no início e o último no final.
justify-content: space-between;

Figura Ilustrativa

Sabendo como todas as propriedades do justify-content funcionam, você possui diversas opções de fazer do modo que deseja. Abaixo darei um exemplo utilizando o justify-content: flex-start;.
O justify-content: flex-start; irá alinhar os itens ao início do container, logo ficando deste modo:

Tenha em mente que estou utilizando o browser em uma resolução alta, caso eu diminua a resolução irá ficar do seguinte modo (depende da resolução que irá estar):

Sabendo-se disto, você pode observar que os últimos conteúdos ficaram alinhados como desejava, porém todos os conteúdos estão "colados" uns aos outros, para solucionar isto é bastante simples, basta apenas adicionar as seguintes propriedades a sua classe .conteudo:
margin-right: 10px;
margin-bottom: 10px;

Então você deverá alterar o seguinte no seu .css:

Adicionar o justify-content: flex-start; a classe .centro
adicionar margins a classe .conteudo

CSS Modificado:
   .centro {
        width: 80%;
        height: 50%;
        border: 2px solid #808080;
        transform: translate(10%,50%);
        padding: 5px;
        overflow-y: auto;
        display: flex;
        flex-wrap: wrap;
        justify-content: flex-start;
    }

    .conteudo {
        width: 230px;
        height: 230px;
        border: 5px dashed #808080;
        margin-right: 10px;
        margin-bottom: 10px;
    }

Nota

Para saber mais sobre Flexbox, acesse este Guia Completo.

Posicionamento com display: flex


How to restrict access to files to files of a node while keeping the node itself viewable?

Question: I'm writing a module that allows users to configure special access restrictions on nodes to reflect academic publishing agreements (called 'embargoes'), which are stored in a custom config entity that points to a node and describes what types of access restrictions should be applied, and who is exempt (users, roles, IP ranges, etc). One of the requirements for the module is that users should be able to restrict access to the entire node (a "node embargo"), OR just the files on the node (a 'file embargo') so that the node itself is accessible and shows up in searches, but the files associated with it are not accessible.
I have implemented the 'node embargo' portion of the module using hook_node_access and checking a custom service to determine if the user should see the node or not, and returning \Drupal\Core\Access\AccessResult::forbidden() if they shouldn't. This works exactly as desired, and not only blocks access to viewing the node, but also access to the files associated with the node.
function embargoes_node_access(\Drupal\node\NodeInterface $node, $op, \Drupal\Core\Session\AccountInterface $account) {
  $nid = $node->id();
  $ip = \Drupal::request()->getClientIp();
  $embargoes = \Drupal::service('embargoes.embargoes')->getActiveNodeEmbargoesByNode($nid, $ip, $account);
  if (!empty($embargoes)) {
    $access = \Drupal\Core\Access\AccessResult::forbidden();
  }
  else {
    $access = \Drupal\Core\Access\AccessResult::neutral();
  }
  return $access;
}

What I cannot figure out how to do is implement the "file embargoes" in which the node is still viewable but the files are not. Since the private files are no longer accessible when hook_node_access returns \Drupal\Core\Access\AccessResult::forbidden() on the node they belong to, there must be some system in Drupal that is checking to see what node the files belong too. If I could figure out how to access that I might be able to use hook_file_download and check the node the file belongs to and see if the file should be accessible or not; in fact I already have a function in my custom service that does exactly this, but it needs a node ID in order to see what embargoes exist for the node.
Does anyone know how to do this? What is Drupal doing when a private file is accessed to see if the associated node is accessible or not?
Comment: `What is Drupal doing when a private file is accessed to see if the associated node is accessible or not?` check _/core/modules/file/src/FileAccessControlHandler.php_
Comment: @NoSssweat This ended up being very good advice, I found a reference to https://api.drupal.org/api/drupal/core%21modules%21file%21file.module/function/file_get_file_references/8.2.x there and that ended up being the answer to my question. Thanks!
Answer: The answer ended up being the function file_get_file_references(), referenced in /core/modules/file/src/FileAccessControlHandler.php
https://api.drupal.org/api/drupal/core%21modules%21file%21file.module/function/file_get_file_references/8.2.x


Android Development - EditText & ButtonTheme

Question: I have a problem with my edittext and button.  When I put them in my xml and run it, I get this...

Can anyone help me get the second output?
Edit:
The second picture is what I see in Eclipse.  I feel like it has something to do with the Theme. Some say it is Ice Cream Sandwich that is the problem but my app is 2.2 however my phone is running 4.0
Comment: can you show us the coding part
Comment: There is no coding, I just dragged in a EditText and a Button and ran the app.  When I run it, instead of seeing the second output, I see the first one.
Answer: The first one is using the holo theme which was new in android4.0. So i think if you specify the android2.3 theme in AndroidManifest.xml, then the second editbox will be displayed.
Such as:
<application android:theme="@android:style/Theme" ...../>

Answer: you're compiling (and previewing in the xml editor) for Ice Cream Sandwich. The native UI that you have in the second example is (I believe) from Gingerbread. You can either set your version backwards, or apply the relevant theme in the manifest for this activity.
Comment: Can you explain a bit more? How to do this exactly?
Answer: In AndroidManifest.xml, I think you just need to set this property:
<uses-sdk
    android:targetSdkVersion="15" />

To a value greater than or equal to 15.  Do a clean/build and see if that helps.  That will tell the phone to use ICS or JellyBean.
Answer: Try setting a background to your edittext like  android:background="@drawable/rounded_corner_white"
where rounded_corner_white :

<item>
    <shape android:shape="rectangle" >
        <solid android:color="@color/White" />

        <corners android:radius="18dp" />
    </shape>
</item>


Drupal 7 views, filter by owner

Question: I need to show the list of the content created by the currently logged-in user.
How do I do this with the Views module?
Answer:
Create View on Content, and click "save and edit".
Add necessary fields. Title, body, post date, etc.
Expand the "Advanced" pane.
Add new Contextual filter.
Check "Content: Author uid"
When the filter value is NOT in the URL -> Provide default value  ->  User ID from logged in user (if you are putting this View in profile pages, better choose "User ID from URL")
Apply and save.
:)

Update:
Here is a short list for Views 2:

Create a View on node as primary table.
Add necessary fields as you want.
Click Add new argument(Little plus sign under arguments pane).
Check "User: UID" and click add.
When the argument is not given, choose to use a default argument, and set it to logged in user.

Update 2:
If you want to restrict access to own content, see https://drupal.stackexchange.com/a/41899/1899
Comment: updated answer :)
Comment: how do you do that in views 2?
Answer: You can also achieve this by the following in your view:
Add Relationship "Content: Author" and check require relationship, then add a filter for "User: Current" and chose Is the logged in user.
This is probably a better option if you only want to display posts created by logged in user, as it is url independent.

Drupal 7 views, filter by owner


Insert data into specific Sqlite3 database row?

Question: self.cursor.execute('INSERT INTO User where User_name=(?) (user_name,user_password,user_wins,user_loses) VALUES(?,?,?,?)',(a,a,b,c,d))
self.connect.commit()

Logically i would have thought this would work but im not sure why it hasnt?
The first '?' in the sql statement is the same as 'a'.
I get this error:
sqlite3.OperationalError: near "where": syntax error

So im wondering if it is actually possible to write to an already written row in a SQL database?
Comment: `INSERT` means add a completely new row. If you want to alter an existing row, you need `UPDATE`.
Answer: INSERT means add a completely new row. If you want to alter an existing row, you need UPDATE.
For instance
UPDATE User
SET user_password=?,
    user_wins=?,
    user_loses=?
WHERE user_name=?

passing the user name as the last variable.
So something like:
self.cursor.execute(
    'UPDATE User SET user_password=?, user_wins=?, user_loses=? WHERE user_name=?',
    (b,c,d,a)
)


wondering why my list has bigger number than second argument function return False?

Question: def greater(list, num)
    for x in list:
        if x > num:
            return True
        else:
            return False

as you can see in my code, i am trying to write a function that return True if list_number contained number that is bigger than second argument, otherwise return False.
but here is confusing:
when i input:  greater([1, 2, 3], 2), and its return False. I am wondering why is that? the first argument contained 3 and its bigger than 2.
any helps and explanations will be appreciated.
Comment: Try placing `return False` **after** the for loop
Comment: `return any(i > number for i in list_number)`
Comment: Only your first element will be considered since you return on the first iteration.
Comment: @KlausD.cool, can you explain why only first element will be considered? and how does else stopped the loop?
Comment: You hit the first `return` and the function ends. There's no way not to hit a `return` for any element.
Answer: You want to have it return at the end of the function. Right now, you have it return after checking only the first number. Try this:
def has_gt(list_number,number):
    for x in list_number:
        if x > number:
            return True

    return False

A property of if/else is that if one runs, the other doesn't. But in both cases, one runs. In your code, this snippet:
        if x > number:
            return True
        else:
            return False

Means that it will check if the number is bigger than the number in question. If it is, it will return True. If not, it will return False. A return call instantly ends the processing of a function, so it will stop checking after that.
To summarize, your code loops through the target list. It checks the first number, one, and sees if it is bigger than two. It is not, so the code returns False, instantly ending the function. So, your function just ended in a False, which is what it returned.
The change I made was that it returns False at the end of the code. This means that it will check each value for being greater than the target. If it finds any value greater than the target, it will end processing, with a return value of True. If the code hasn't returned by the time it reaches the end of the function, it will return False because of the statement at the end of the function.
Comment: thanks for answer, but can you please explain in detail of why it is only checking the first number? thanks
Answer: Actually what happens is the else part also runs just after comparing the number (here 2) with the first element in the list_number (here 1) thus returns false.
So the solution is you need to let the for loop first run completely which is stopped by the else statement.
 def has_gt(list_number,number):
    for x in list_number:
        if x > number:
            return True

    return False

Comment: thank you, but can you please explain more details of why it only checking first element and stopped?
Comment: As per loop is concerned, a loop runs the code inside it and then moves back to the top. So when it checks for the first condition i.e, 1 and 2 against each other, as 1 is less than 2,so if condition is not satisfied and it moves to else statement which then returns false. And as something is returned, function simply stops.
Comment: BTW can you please explain why you unmarked my answer as accepted??