Cross domain LDAP

Question: For a system we are developing we have 2 domains an internal and an external domain with bi directional trust between them. However the servers are only able to connect to their own DC's.
We have an application server on the internal domain which needs to use an LDAP query to gather a list of users from a group on the external domain. How do i go about writing an LDAP query that asks one DC to go ask another DC for a list of users.
I tried querying the internal DC with the same LDAP query I would use if it could hit the external DC directly but this does not work. When i use Softerra LDAP Administraor I can view the full hierarchy of the interal domain but despite the trust relationship between domains i am unable to see any of the external doamin.
Any suggestions or help would be greatly appreciated
Answer: You need to use LDAP referrals.
https://www.rfc-editor.org/rfc/rfc4511#section-4.1.10
These can be configured within Active Directory using crossRef objects.
See:
http://support.microsoft.com/kb/241737
technet.microsoft.com/en-us/library/cc978014.aspx
Answer: I ran into the same problem and solved it with OpenLDAP and its meta backend:
http://linux.die.net/man/5/slapd-meta
Answer: I'm not sure if this will help or not, as I don't write LDAP queries directly, but I have c# applications that run on an application server on our external domain that must query AD on our internal domain.
In order to get this to work, I explicitly provide the FQDN of an internal DC in my LDAP connection string:
<code>LDAP://cross-domain-dc.mydomain.local/OU=…
</code>

Cross domain LDAP


Jsoup - Working with URLS

Question: I have the code below:
public static void main (String args[]) throws IOException
{
    String absHref = "";
    String urlList = "";
    String relHref = "";

    Document doc = Jsoup.connect("https://www.planittesting.com").get();
    Elements links = doc.select("a[href]");
    for (Element link : links)
    {
        absHref = link.attr("abs:href");
        urlList = absHref.toString();
        System.out.println(urlList);

But the results have gaps in them, am I missing something? I'm turning the relative urls into absolute urls but some of them come back as blanks.
[
Answer: If you use link.attr("href"); you can see that these href attributes are not empty but they contain something else, like:
javascript:__doPostBack('p$lt$ctl00$GeoLocator$rptCultures$ctl01$lbChangeSite','')
javascript:__doPostBack('p$lt$ctl00$GeoLocator$rptCultures$ctl02$lbChangeSite','')
javascript:__doPostBack('p$lt$ctl00$GeoLocator$rptCultures$ctl03$lbChangeSite','')
javascript:__doPostBack('p$lt$ctl00$GeoLocator$rptCultures$ctl04$lbChangeSite','')

If you use link.attr("abs:href"); you see blank values for all the things that are not urls like javascript.
You can fix it adding a simple check:
package com.github.davidepastore.stackoverflow35544869;

import java.io.IOException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * Stackoverflow 35544869 question.
 *
 */
public class App
{
    public static void main( String[] args ) throws IOException
    {
        String absHref = "";
        String urlList = "";
        String relHref = "";

        Document doc = Jsoup.connect("https://www.planittesting.com").get();
        Elements links = doc.select("a[href]");
        for (Element link : links)
        {
            absHref = link.attr("abs:href");
            if(!absHref.isEmpty()){
                urlList = absHref.toString();
                System.out.println(urlList);
            }
        }
    }
}

Output:
https://www.planittesting.com/uk/Home#main
https://www.planittesting.com/uk/Home
https://www.planittesting.com/uk/Home
https://www.linkedin.com/company/planit-software-testing
https://www.planittesting.com/uk/Course-Bookings
https://www.planittesting.com/uk/Contact
https://www.planittesting.com/
https://www.planittesting.com/uk/Services
https://www.planittesting.com/Services/Functional-Testing
https://www.planittesting.com/Services/Test-Automation
https://www.planittesting.com/Services/Performance-Testing
https://www.planittesting.com/Services/Accessibility-Testing
https://www.planittesting.com/Services/Security-Testing
https://www.planittesting.com/Services/Mobile-App-Testing
https://www.planittesting.com/Services/Digital-Testing
https://www.planittesting.com/Services/Agile-Testing
https://www.planittesting.com/Services/Non-Agile-Testing
https://www.planittesting.com/Services/Test-Strategy
https://www.planittesting.com/Services/Test-Management
https://www.planittesting.com/Services/Process-Improvement
https://www.planittesting.com/Services/DevOps-Solutions
https://www.planittesting.com/Services/Service-Virtualisation
https://www.planittesting.com/Services/Application-Monitoring-Solutions
https://www.planittesting.com/Services/Test-Management-as-a-Service
https://www.planittesting.com/Services/Performance-Testing-Solutions
https://www.planittesting.com/Services/Tools-Licensing
https://www.planittesting.com/Services/On-site-Testing
https://www.planittesting.com/Services/Off-site-Testing
https://www.planittesting.com/Services/Off-shore-Testing
https://www.planittesting.com/uk/Training
https://www.planittesting.com/Training/Software-Testing
https://www.planittesting.com/Training/ISTQB-Foundation-Certificate
https://www.planittesting.com/Training/ISTQB-Advanced-Test-Analyst
https://www.planittesting.com/Training/ISTQB-Advanced-Test-Manager
https://www.planittesting.com/Training/Software-Testing
https://www.planittesting.com/Training/Agile
https://www.planittesting.com/Training/ISTQB-Foundation-Agile-Tester-Extension
https://www.planittesting.com/Training/Certified-Agile-Essentials
https://www.planittesting.com/Training/Certified-Agile-Business-Analysis
https://www.planittesting.com/Training/Certified-Agile-Tester
https://www.planittesting.com/Training/Business-Analysis
https://www.planittesting.com/Training/BCS-Business-Analysis-Foundation
https://www.planittesting.com/Training/BCS-Requirements-Engineering-Certificate
https://www.planittesting.com/Training/BCS-Modelling-Business-Processes
https://www.planittesting.com/Training/BCS-Business-Analysis-Practice
https://www.planittesting.com/Training/Classroom
https://www.planittesting.com/Training/Virtual-Learning
https://www.planittesting.com/Training/Schedule
https://www.planittesting.com/uk/Insights
https://www.planittesting.com/uk/About
https://www.planittesting.com/uk/Join-Our-Team
https://www.planittesting.com/uk/Contact
https://www.planittesting.com/Services
https://www.planittesting.com/Services/Mobile-App-Testing
https://www.planittesting.com/Planit-Testing-Index
https://www.planittesting.com/Training/ISTQB-Foundation-Agile-Tester-Extension
https://www.planittesting.com/Services/Service-Virtualisation
https://www.planittesting.com/Services/Functional-Testing
https://www.planittesting.com/Services/Test-Automation
https://www.planittesting.com/Services/Performance-Testing
https://www.planittesting.com/Services/Accessibility-Testing
https://www.planittesting.com/Services/Security-Testing
https://www.planittesting.com/Services/Mobile-App-Testing
https://www.planittesting.com/Services/Digital-Testing
https://www.planittesting.com/Services/Agile-Testing
https://www.planittesting.com/Services/Non-Agile-Testing
https://www.planittesting.com/Services/Test-Strategy
https://www.planittesting.com/Services/Test-Management
https://www.planittesting.com/Services/Process-Improvement
https://www.planittesting.com/Services/DevOps-Solutions
https://www.planittesting.com/Services/Application-Monitoring-Solutions
https://www.planittesting.com/Services/Performance-Testing-Solutions
https://www.planittesting.com/Services/Test-Management-as-a-Service
https://www.planittesting.com/Services/Service-Virtualisation
https://www.planittesting.com/Services/Tools-Licensing
https://www.planittesting.com/Services
https://www.planittesting.com/Training/Software-Testing
https://www.planittesting.com/Training/Agile
https://www.planittesting.com/Training/Business-Analysis
https://www.planittesting.com/Training
https://www.planittesting.com/Insights/Cricket-Australia-Case-Study
https://www.planittesting.com/Insights/Lend-Lease-Case-Study
https://www.planittesting.com/Insights/Panviva-Case-Study
https://www.planittesting.com/Contact
https://www.planittesting.com/
https://www.linkedin.com/company/planit-software-testing
https://www.linkedin.com/grp/home?gid=4561841
mailto:email@example.com
https://www.planittesting.com/uk/Services
https://www.planittesting.com/uk/Services/Functional-Testing
https://www.planittesting.com/uk/Services/Test-Automation
https://www.planittesting.com/uk/Services/Performance-Testing
https://www.planittesting.com/uk/Services/Accessibility-Testing
https://www.planittesting.com/uk/Tools
https://www.planittesting.com/uk/Tools/Service-Virtualisation
https://www.planittesting.com/uk/Tools/Application-Monitoring
https://www.planittesting.com/uk/Tools/Performance-Testing-Solutions
https://www.planittesting.com/uk/Tools/Test-Management-as-a-Service
https://www.planittesting.com/uk/Training
https://www.planittesting.com/uk/Training/Software-Testing
https://www.planittesting.com/uk/Training/Business-Analysis
https://www.planittesting.com/uk/Training/Agile
https://www.planittesting.com/uk/Training/Full-Course-Schedule
https://www.planittesting.com/uk/About
https://www.planittesting.com/uk/About/Planit-Testing-Index
https://www.planittesting.com/uk/About/Jobs-Board
https://www.planittesting.com/uk/About/Careers-at-Planit
https://www.planittesting.com/uk/About/Bootcamp
https://www.planittesting.com/uk/Contact
https://www.planittesting.com/uk/Contact/Office-1
https://www.planittesting.com/uk/Contact/Office-2
https://www.planittesting.com/uk/Contact/Office-3
https://www.planittesting.com/uk/Contact/Office-4
https://www.planittesting.com/uk/Footer-Navigation/Privacy
https://www.planittesting.com/uk/Footer-Navigation/Terms-Conditions

Answer: You can fine tune the original CSS selector:
a[href]:not([href~=(?i)^(javascript|tel|mailto)])

Description
a[href]                               /* Select any anchor with an href attribute ... */
:not(                                 /* not starting... */
 [href~=(?i)^(javascript|tel|mailto)] /* with javascript, tel or mail */
)

Demo

Original selector: a[href]
121 links found
Fine tuned selector: a[href]:not([href~=(?i)^(javascript|tel|mailto)])
115 links found

Jsoup - Working with URLS


configuring a Fibre Channel switch

Question: (I'm asking this for a friend and I'm don't know most of this technical stuff, so I'm sorry in advance if I'm not clear enough to describe the problem)

Where can i find any information about
  how to configure a Fibre Channel
  switch ( QLocic , Mini GBic, QME2572 )
  to make it communicate with a Dell
  R905 and a Dell M905 Blade Server ?

Many thanks in advance
Pierre
Comment: ummm... RTM? ;)
Answer: Plug the server into the switch with the appropriate cable.
For more complicated settings, refer to the switch's manual (which should have come with the switch or be available for download from the manufacturer).
However from the question, I don't think this is what you want.  It sounds like you have two computers and one FC switch.  Unless you also have a storage device, you need to configure one side to pretend to be the storage. Note that in any case you'll need Fiber Channel cards to make this work.

configuring a Fibre Channel switch


Question on homogeneous ideal in a graded ring

Question: In an $\Bbb{N}$-graded ring $R=\bigoplus_nR_n$, an element is called homogenous (of degree $n$) if it is contained in $R_n$. An ideal is called homogenous if it is generated by homogenous elements. Let $I$ be a homogenous ideal generated by homogenous elements $f_1,\dots,f_s$. Now it says, given $f\in I$ homogeneous, we can write $f=\sum_ig_if_i$ with $g_i$ homogeneous of degree $\deg f-\deg f_i$. No proof is given. How can I see this?
Answer: $I$ is generated by homogeneous elements $f_1,…,f_s$. so $f=\sum_ig_if_i$. if $g_t$ were not homogeneous (for some t) use associative property ($f_i$s may be Repeated). $\deg f-\deg f_i$, by definition of graded rings ($R_i R_j \subset R_{i+j}$).
(in fact $\deg g_if_i=\deg g_i+\deg f_i = \deg f$, for all $i$)


Recommend a USB Flash copier (Software or Hardware based) for Keep-it-simple-stupid bitwise copy

Question: Intro
I'm looking around for a no-frills USB flash media copier that is brain-dead simple and copies a source to a destination, bit for bit, when the drives are approximately the same size.
Untrained people will be using it to copy drives that include both windows and linux data and bootable, multiple partitions.
Requirements:

brain dead simple, no training required
mostly bit-for-bit copy of a source USB flash drive to a destination USB flash drive including multiple paritions, hidden files, MBRs/bootable bits
reasonable handling of slight manufacturing variations among manufacturers of the same "size" drive.  That is, a destination that is only 1.999Gb should still succeed if the partitions on the source drive are not full.
USB 2.0, reasonably fast, like 2Gb in 5-10 minutes
no menus or options to copy single files or directories or ability to turn those options off or have them hidden in an advanced tab

Nice to Have:
Ideally two usb slots, a copy button, and (optionally) a progress indicator.
 - Ideally, handheld form factor.  Shuttle-PC sized might be ok.
 - Ideally, under US$300 or so.
Fail:

Software based: Linux dd if=/dev/sdx of=/dev/sdy is simple
but not brain-dead simple because it
involves knowledge and trust to
identify the partition names and requires root
access to a PC.  Windows drag and drop copy does not do bit for bit
Memorex and some no-names had a handheld usb1.1 device but it was too slow, had options for file names and directories that people could screw up.
A number of manufacturers make 1:many devices PC-based USB copiers that cost $500 or more and may or may not do bit-for-bit copy.

Does such a copier exist?
Looked around in google for a while. Maybe I want too much.
Does anyone know of a device that has met these or similar requirements?
Does anyone know of a Linux LiveCD product that can do this or can be nudged into doing this kind of function?
Thanks in advance

Paul
Comment: dd does not technically require root permissions to function.  You can setup your system so that any attached usb device notes are set to be writable by a non-privileged user.
Answer: You've partly answered your own question here.. I'd have to question some of your requirements. Why do you care if they have 'root', if you treat this box as an appliance? Run it as a kiosk, with a simple UI (text-based, even) that says:

"Insert source USB stick"

It then autodetects this stick

"Insert target USB stick(s), and press GO"

Once user presses GO, it copies.
If source stick is removed, goto step 1

Go to step 2

Once you get it going, back it up, and just let it go. Use a cheap miniitx/shuttle/system you have laying around, as long as you have USB 2.0 you're good.
Comment: Thanks for your encouragement for me to create/build my own. Part of the reason for controlling what kind of device, keeping it simple, etc... is to avoid the complaints and complexities that otherwise probably (and needlessly) follow. I agree that if the box is a single-function appliance, access to root doesn't matter.  However, if the box is multipurpose, e.g. a workstation or a server, then it does matter.  The workflow you mention is the obvious one but there are of course devils lurking in the details and I thought it would be good to see if others have battled them already.
Comment: You can always create a default "kiosk mode" user that limits access to the rest of the system. And for $200, you can get an Acer AspireRevo net top to build this with. You can use any scripting technology like Perl/Python/etc. that supports GUI creation & xan call dd in the background.
Answer: And why not use names with dd ? It's easy : dd if=/dev/disk/by-label/USBDISKPRO of=/dev/disk/by-label/BACKUP ?
It works on all modern linux distributions...
Comment: ls /dev/disk/by-label is actually kind of useful for locating the source drive.  I wonder what happens if you have two disks with the same label (e.g. casper-rw).
Comment: Check if you have the UUID and use /dev/disk/by-uuid/ or /dev/disk/by-id/.

You can maybe change the label of your partition to find it easilyer.
Answer: While its not exactly meant for this, specifically, the usb disk imager that ubuntu uses, least on windows, does this - you'll need to pick 'read' as opposed to write to back up, naturally, but its as simple and painless as it gets. Haven't tried the linux equivilent yet, so no idea about that
Comment: I suppose for now this is the answer.  On a related WTF, I forwarded the link to someone here who needed to copy a USB flash drive and they tried to read a 2Gb drive and then write to a 1Gb drive and figured out that doesn't work (really?)....  So I guess I'll be writing my own 'brain dead simple' tool now which will have to do hand holding and obviously won't use bitwise copy unless the drives are the same size ...


numeros primos entre uma sequencia

Question: O problema é o seguinte, tenho que receber um valor inteiro e calcular o fatorial desse numero (até ai tranquilo), e pegar  e printar na tela os numeros primos que existem entre um e o fatorial, porém estou com problemas para fazer isso, alguem pode me falar o que está errado?
<code>/*Mostrar todos os numeros primos*/
# include<stdio.h>
# include<stdlib.h>

int main()
{
  long int numero,fatorial=1;
  int cont,contador=1,teste,truvs,bash=0,primo;

  scanf("%ld",&numero);

  for(cont=1;cont<=numero;cont++)
  {
    fatorial*=cont;
  }

  printf("FATORIAL -> %ld\n",fatorial);//só printei pra testar a fatoração
//---------DELIMITA A OPERAÇAO---------
  for(contador=2;contador<=fatorial;contador++)
  {
    bash=0;

//--------TESTA  PRIMO------------
    for(teste=1;teste<=contador;teste++)
    {
      bash=0;
//---------ISOLAR O TESTE DE DIVISAO-----------
      while(bash<2)
      {

        // truvs=contador%teste;
        if(contador%teste==0)
        {
          bash++;
           printf("%d\n",bash);
        }
        else
        {
          break;
        }

      }

      if(bash==2)
      {
        printf("%d\n",contador);
      }
      // bash=0;

    }
  }

return 0;
} //Fim do programa
</code>
Answer: Seu teste para verificar se é primo está errado. Tente:
<code>for (teste=1;teste<=contador;teste++)
{
  bash=0;
  div = 1;
  while(div <= teste)
  {
    if (teste%div == 0)
    {
       bash++;
    }
    div++;
  }
  if (bash==2)
  {
    printf("%d\n", teste); /* teste é primo */
  }
}
</code>
Obs: pode ser otimizado.

numeros primos entre uma sequencia


DIDEVICEINSTANCE guidInstance and guidProduct change on same device

Question: I am using DirectInput8 in a project at work that monitors various components of the pc.  To monitor joysticks we use DirectInput8.  The data is retrieved by enumerating all joysticks with DI8DEVCLASS_GAMECTRL as the type and DIEDFL_ATTACHEDONLY as a flag.  Recently it was brought to my attention that we were having multiple joysticks showing up.  First I looked at the xml file we store the components in between reboots.  There were two entries for the joysticks, Logitech Extreme 3d pro, and each had a unique product guid.  I backed the file up and removed it, effectively forcing a rescan of the machine next time the app started after I rebooted the machine.  I was able to get the same problem to occur and logged out the guids and they are different for each.  The system only has a single joystick plugged in however it plugs in through a usb hub.  Is the hub affecting the guids I am seeing?  I could also only get this to occur maybe 1 out of 5 attempts.
Example:
Joystick Product GUID: 3C6A972000000000504944564944
Joystick Instance GUID: 3C6A972097C11E3800144455354
Joystick Product GUID: DA83AFB000000000504944564944
Joystick Instance GUID: DA83AFB0D7B211E2800144455354
Comment: I tried changing the code to only create one instance of the DirectInput object by making my LPDIRECTINPUT8 pointer static and only allowing one call to DirectInput8Create and using a different method to enumerate mice and joysticks.  However I still see the issue randomly where I get two different GUIDs in the same application run for only a single joystick.
Answer: Had a similar issue... I just exported the DirectInput registry settings for the VID/PIDs I wanted to replicate GUIDs across machines.
So, in regedit navigate to:
<code>[HKEY_CURRENT_USER\System\CurrentControlSet\Control\MediaProperties\PrivateProperties\DirectInput\VID_[Whatever]&PID_[Whatever]\
</code>
Right click, choose Export to create the .reg file, the move it to the machine you want and double click.
Answer: This was a pain to find but after watching our testers I found they were logging into multiple user accounts and the GUID returned was different per user which is what caused the problem, would be nice if the documentation would be updated to reflect this.
Answer: I'm having the exact same problem as the original poster.  To clarify his answer, its the instance GUID that is different for each user.  And here is the MSDN documentation that incorrectly asserts that the InstanceGUID should stay the same on a given computer.  Without someone from Mircosoft weighing in I don't know that I'll ever know the answer why this is - is it a bug or is the documentation incorrect.
The bottom line is you'll have a heck of a time sharing keybindings for a joystick among multiple users without a solution to this problem, which is my situation.


Apache, how to handle unknown php file like standard URLs?

Question: I am have a Symfony website where I have renamed the main entry point so "index.php" can't accessed nor being indexed by search motors. It works well. But, when I try to access this file I get a 404 file not found, this 404 page is handled by Apache and not by the application, it's the standard 404 page:
Not Found
The requested URL was not found on this server.

I'd like URLs like /index.php (*.php in fact) to be handled by the Symfony application to display the customised error page with the good layout. My vhost look like this, I tried to add a "directory index" directive but without success.
# configuration/vhosts/prod/mywebsite.com-le-ssl.conf
<IfModule mod_ssl.c>
    <VirtualHost *:443>
        ServerName www.mywebsite.com
        DocumentRoot /var/www-protected/mywebsite.com/public

        <Directory /var/www-protected/mywebsite.com/public>
            AllowOverride All
            Require all granted
            FallbackResource /my-secret-entry-point.php
        </Directory>

        RedirectMatch 404 /\.git

        ErrorLog /var/log/apache2/mywebsite.com_error.log
        CustomLog /var/log/apache2/mywebsite.com_access.log combined

        RewriteEngine on
        RewriteCond %{SERVER_NAME} =mywebsite.com
        RewriteRule ^ https://www.%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]

        SSLCertificateFile /etc/letsencrypt/live/www.mywebsite.com/fullchain.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/www.mywebsite.com/privkey.pem
        Include /etc/letsencrypt/options-ssl-apache.conf
    </VirtualHost>
</IfModule>

Answer: This can be done with mod_rewrite, replying with 301:
Options +FollowSymLinks
DirectoryIndex index.php

RewriteEngine On
RewriteBase /

RewriteCond %{THE_REQUEST} ^.*/index\.php
RewriteRule ^(.*)index.php$ /$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

Default error documents can be used to dispatch the error-codes to PHP:
ErrorDocument 404 https://mywebsite.com/error/page/404
ErrorDocument 500 https://mywebsite.com/error/page/500

Then one still can send whatever header() one wants - or just show a page with the same headers.
Comment: Hi, thanks for answer. Sorry for the delay, I will check this quickly. ErrorDocument seems like a good option. :)
Comment: Hello it works well. I had to put this in a `.htaccess` file. Now the redirection is made to my new hidden front controller (I replaced `RewriteRule . /index.php [L]` at the end), and then the application does a manual redirection to the good page.


How to fix this if choice error in my Python text based game?

Question: I need help with this code;
input()
print("Created by Mr.StiK")
input()
print('In a dark and creepy cave... You got your consciousness back...')
input()

print("Then you remember... you've no time to waste...")
input()

unit = input("Type the command 'wake' to start your adventure... ").lower()

while unit.lower() == "wake":

    if unit.lower() == "wake":
        print("And you starts your adventure...")
        break

    if not unit.lower() == "wake":
        print("Sorry, unidentified command. Please type 'wake'")

The error;
When you type the command wrong, it does not say anything, just skips the code.
And when we input nothing, we get nothing.
And then when we say anything, the program crashes, with this;
Traceback (most recent call last):
  File "<pyshell>", line 1, in <module>
NameError: name 'wake' is not defined

Please I need help with this.
PS: IF YOU CAN ALSO NEED TO RE-WRITE THE CODE WITH A BETTER CODE/ENGINE, PLEASE, IT WILL BE ACCEPTED TOO.
Comment: the while loop's test is the problem.
Comment: In your own words, what do you think `while unit.lower() == "wake":` means? If `unit.lower()` is not equal to `"wake"` before the loop is reached for the first time, do you expect the loop to run at all? Why?
Answer: Change your WHILE_LOOP and INPUT to this
while True:
    unit = input("Type the command 'wake' to start your adventure... ").lower()
    if unit == "wake":
        print("And you starts your adventure...")
        break
    else:
        print("Sorry, unidentified command. Please type 'wake'")


Worksheet IF statements with AirTable

Question: Im using Airtable (Online Excel Equivalent with their own similar Formulas)but I can't seem to get this to work properly.
So I have three values (UE, PE, EE) which are being used for the following columns (GradeF, ZipcodeF, SchoolF) The formula will be applied to the column "Eligible". So overall what I'm trying to do is If Grade is "UE", then mark as "UE". If Grade is "PE" then determine If Zipcode is "EE" or "PE", or School is "EE", or "PE" if so then mark as "PE" otherwise "UE". If Grade is "EE" then determine If Zipcode is "EE", or School is "EE" if so then mark as "EE" otherwise "UE".
IF(GradeF = "UE", "UE", IF(GradeF = "PE", IF(OR(ZipcodeF = "EE", ZipcodeF = "PE", SchoolF = "EE", SchoolF = "PE"), "PE","UE", IF(GradeF = "EE", IF(OR(ZipcodeF = "EE", SchoolF = "EE"), "EE", "UE" ,"")))))

Answer: It's easier if you work backward from your most common case ("UE").  I've never used Airtable, but this should be the logic (line breaks for clarity):
IF(AND(GradeF="EE",OR(ZipcodeF="EE",SchoolF="EE")),"EE",
IF(AND(GradeF="PE",OR(ZipcodeF="EE",SchoolF="EE",
ZipcodeF="PE",SchoolF="PE")),"PE","UE"))

Comment: Awesome thanks! Just realized I needed If GradeF="EE" then if ZipcodeF or SchoolF = "PE" but figured it out by copying the first line and replacing "EE" with "PE" and adding another parentheses at the end.

Worksheet IF statements with AirTable


Ler conteudo input

Question: Eu estou tentando ler o texto dentro de um campo input, mas não esta funcionando, o que pode estar errado?
Meu código:

<input type="text" id=-"campo-de-busca" onKeyPress="teclaPressionada()" placeholder="Nome">

function teclaPressionada()
{
    var texto = $("#campo-de-busca").val();
    alert(texto);
}
Comment: E qual é o `input`? Quando a função `teclaPressionada` é executada?
Comment: troque id=-"campo-de-busca" por id="campo-de-busca"
Comment: Gente, desculpe este erro bobo.
Comment: tens certeza que estas a chamar a função `teclaPressionada` ?
Comment: Inseri meu campo input
Comment: @abduzeedo ele esta reconhecendo o "-" como o nome do campo
Answer: Você pode utilizar os eventos nomeados KeyBoard Events que são esses :

KEYDOWN

O keydown event é enviado para um elemento quando o usuário pressiona uma tecla no teclado. Se a tecla for mantida pressionada, o evento é enviado sempre que o sistema operacional repete a chave.

KEYDOWN EVENT JQUERY

KEYPRESS

O keypress event é enviado para um elemento quando o navegador registra a entrada do teclado.

KEYPRESS EVENT JQUERY

KEYUP

O keyup event é enviado para um elemento quando o usuário libera uma tecla no teclado.
  KEYUP EVENT JQUERY

Abaixo você pode ver um exemplo usando jQuery e os eventos acima citados.
Você pode alterar o evento para keypress ou keydown

$(function(){
  $('#teste').on('keyup',function(){
    console.log(this.value);
  });
});

<input type="text" id="teste">
Comment: Motivo do voto negativo ?
Comment: Só coloquei "se esse foi o motivo" porque algumas pessoas na comunidade no lugar de dar um feedback feito o seu apenas colocam o negativo e não sabemos onde erramos para melhorarmos na próxima resposta entende ? como sou novato na comunidade preciso reconhecer meus erros. @LeoCaracciolo
Comment: entendi, sou contra dar votos negativos sem explicação. Isso não ajuda nada e ninguém.
Comment: Exemplo, tem 2 negativos em minha resposta só que estou tentando ajudar e não atrapalhar, porque não informar aqui o motivo... até desanima a pessoa.
Comment: +1 dado por atender os comentarios, além da resposta agora ficar ok :)
Comment: @AndersonCarlosWoss alterei minha resposta, veja se melhorou, qualquer coisa me informa para que eu melhore sempre.
Comment: Obrigado amigo e desculpe o erro bobo, não percebi o (-) antes do sinal de iguaql
Comment: a primeira teclada não retorna nada
Comment: Se esse foi o motivo do voto negativo era só comentar, eu deixei bem especifico que pode alterar o evento para keyup por exemplo, isso faria com que a primeira tecla retornasse algo.
Comment: Outra coisa, se houver vários inputs na pagina, todos vão executar a função.Melhor por por id
Comment: @LeoCaracciolo Isso é uma falha minha, as vezes eu esqueço de deixar bem especifico pois alguém que é 'iniciante' pode cair facilmente nesse erro. Irei editar a resposta.
Comment: é isso ai, só pra mostrar que ao inves de negativar melhor é ajudar alertando nos comentários
Comment: Obrigado pelo feedback @AndersonCarlosWoss irei agora mesmo editar minha resposta para melhorar o entendimento de todos.
Answer: tem um - no seu campo id
<input type="text" id="campo-de-busca" onKeyPress="teclaPressionada()" placeholder="Nome">

mas o que você que não seria onclick ao invés de onkeypress?
Comment: Eu quero pegar os valores dentro do input ao pressionar a tecla
Comment: tá certo!! entendi que seria o valor total do input, daí vc precisaria de uma outra chamada javascript, mas se é a cada letra, então deve usar o onKeyPress mesmo..
Answer: A solução para seus problemas passa por

uma correção no valor do atributo id do seu input do HTML de -"campo-de-busca" para "campo-de-busca". Observe que tem um hifem logo após o sinal de igual.
Mudar o evento onKeyPress para onkeyup para que a função seja disparada assim que a tecla é pressionada.

function teclaPressionada()
{
    var texto = $("#campo-de-busca").val();
    console.log(texto);
}

<input type="text" id="campo-de-busca" onkeyup="teclaPressionada()" placeholder="Nome">

Para maiores detalhes sobre diferenças entre OnKeyUp, OnKeyDown e OnKeyPress veja esse Post

Com jquery

var userTyped = '';
$(document).ready(function(){
$("#campo-de-busca").keypress(function(e){
userTyped += String.fromCharCode(e.which);
console.log(userTyped);
});
$( "#campo-de-busca" ).focus();
})

<input type="text" id="campo-de-busca" placeholder="Nome">

Ler conteudo input


Compare the mean of a dataset with the reference mean in the literature

Question: I have a dataset and I want to compare its mean to a reference mean that I found in the literature. How can I consider this reference mean (found in the literature and i don't have the raw dataset) as a reference and compare the mean of my dataset against it?
what kind of test should I use?
R or SPSS solutions are accepted.
Answer: The Analyze > Compare Means > One Sample T Test allows you to compare a mean against a fixed value, which your reference mean would be.
Answer: The method to do this in SPSS has been described. In R, you would use a one-sample t-test using the command t.test.
Assume that you have five temperature readings around a city: 12.5, 12.3, 12.8, 12.5, and 13.6. You wish to test the hypothesis that the mean temperature for this time and date is not 14.3, as stated in a reference source.
> t.test(c(12.5, 12.3, 12.8, 12.5, 13.6), mu=14.3)

    One Sample t-test

data:  c(12.5, 12.3, 12.8, 12.5, 13.6)
t = -6.8019, df = 4, p-value = 0.002441
alternative hypothesis: true mean is not equal to 14.3
95 percent confidence interval:
 12.10323 13.37677
sample estimates:
mean of x
    12.74

The results show that you can reject the null hypothesis.
Answer: You only need to know the reference mean and the sample size.  Then assuming normality for both your data set and the reference mean you can apply a two-sample t test to the difference of the two means.
Comment: what do you mean by " apply a two-sample t test to the difference of the two means"? can you give an example?
Comment: You will need to know the sampling variance of the reference mean, not just the sample size.


How can I make a mean sequential estimation?

Question: I am an agronomist trying to estimate the average weight of fruit in a orchard. My first option is to grab 1000 fruit and get their weight mean. But as you can see, if i can get this with less fruits, I will save time (and fruits).
Is there any way to get a stopping rule based on the prior update (every time that I record a new single fruit weight)?
Thank you
Comment: When exactly would you like to stop?
Comment: Well, I guess that's the question. I've read some text about the ROPE and HDI relation. Could it be one possible criteria?
Comment: Hi Hugo. Chapter 13 of DBDA2E is all about "Goals, Power, and Sample Size." In particular, it discusses "optional stopping" using different goals.
Comment: Thank you John K. Kruschke. I am reading your book but I am not finding out how to set a rule. I will work harder and get some more samples.
Answer: Short answer: No. A confidence interval, that you would use as a prior, provides no degree of belief.
The problem here is that you don't know which are the factors that makes your fruits have a different weight, thus you can't be sure to pick a significant samples of fruit.
Say for example that you have red and yellow fruits, and that they have a different weight (Red = 1kg, Yellow = 2kg). If you have the same amount of red and yellow fruits in your orchard then the average is 1.5kg. But if you pick only red fruits for your sample, then you will end up with an average of 1kg. Obviously you wouldn't use a sample of red fruits only because you know that the fruits have different colors, but what about their age ? position on the tree ?  size ? size of the stone ? sun exposure ? etc...
Your problem is not to know when to stop adding fruits to your sample, but what fruits should you put in your sample. And this depends on agronomy criteria that you probably know much better than statisticians.
Now, if you come up with a perfectly homogeneous sample of fruits, the more you add, the more precise your mean estimate should be. When to stop depends on the precision you want to achieve (and you may want to have a look at that)


Como alterar posição do Growl na tela?

Question: Estou querendo alterar a posição do Growl porém aplico no CSS e na hora não altera nada na posição quando aparece na tela, quero centralizar por exemplo.
No template:
<h:head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
    <title>Drogaria</title>
    <h:outputStylesheet library="css" name="estilos.css" />
</h:head>
<h:body>

...
</h:body>

No css:
@CHARSET "ISO-8859-1";

.ui-growl{
    left:20px;
}

No xhtml

Answer: Use o absolute, tente assim que funcionou pra mim:
.ui-growl {
    position: absolute;
    top: 20px;
    left: 40%;
}

Como alterar posição do Growl na tela?


.astype("int") or .astype(int)? Any differences between with and without quote/double?

Question: I have a DataFrame and one of its column consist of float type objects. I want to convert to int. As I tried, both .astype("int") and astype(int) methods work. I just wonder whether there is/are any difference(s)?
Answer: AFAIK there is no major difference...
.astype(dtype) should accept everything what is accepted by numpy.dtype().
Internally it does this:
dtype = np.dtype(dtype)


Put three form buttons on a line

Question: I have 3 buttons that display in a vertical line and I want them to display horizontally
            <form method="twitch" action= "https://www.twitch.tv/">
              <button type="submit"></button>
            </form>
             <form method="Instagram" action="https://www.instagram.com/">
              <button type="submit"> </button>
            </form>
            <form method="linkedin" action="https://www.linkedin.com/">
              <button type="submit"></button>
            </form>

Comment: Does this answer your question? [How can i Display div Elements in one row](https://stackoverflow.com/questions/23799877/how-can-i-display-div-elements-in-one-row)
Answer: Wrap them in a parent div and, in your CSS, set that div to display: flex.
Answer: You can put each form and button inside individual
's, wrap those
's in a parent
, and then use flex: https://jsfiddle.net/HappyHands31/hnkqsjba/2/

.container {
  display: flex;
}

.first, .second, .third {
  display: flex;
}

    <form method="twitch" action= "https://www.twitch.tv/">
    <button type="submit">
    </button>
    </form>

    <form method="Instagram" action="https://www.instagram.com/">
    <button type="submit"></button>
    </form>

    <form method="linkedin" action="https://www.linkedin.com/">
    <button type="submit"> </button>
    </form>

Answer: In css add to each one of them float: left;
Comment: That would be a good solution... 10 years ago
Comment: What makes it not good? Is it slow?
Comment: float:left might work just fine but for that case, it's much better practice to use display:flex because it gives the same result and allows you to use a lot of more parent-related properties from CSS Flexbox
Answer: Use display:inline-block;
most people use flex but its not good becasue some of the old browsers can't understand flex.!
but all of the browsers support inline block
Comment: False. https://caniuse.com/#search=display%3Aflex
Comment: Chrome and FireFox and IE old vers can't run it its totally true.!
Comment: Did You make sure that these browsers are even supported ? ;)
Comment: Dude your web should support every single browsers... :)
that means you are a pro ui designer because everyone can use flex but its only you that can do something special :)
Comment: and of course even last version of IE is partial supported.
lots of users still use IE so... ?
Comment: Good luck than  sir !

Put three form buttons on a line


Top margin of first child and bottom margin of last child

Question: HTML

level1

level2

level2

level2

level2

CSS
.lev1{
  background:lightblue;
}
.lev2wrap{
  background:gold;
}
.lev2{
  background:#999999;
  margin:10px 0;
}

Why does the first instance of lev2 not have a top margin of 10px, and why does the last instance of lev2 not have a bottom margin of 10px?
Instead, lev2wrap has a top and bottom margin, but that's not a CSS instruction.
JSFIDDLE
Answer: Because of collapsing margins.

Top and bottom margins of blocks are sometimes combined (collapsed)
  into a single margin whose size is the largest of the margins combined
  into it, a behavior known as margin collapsing.
Margin collapsing occurs in three basic cases:

Adjacent siblings
Parent and first/last child
Empty blocks

To have the margin of lev2wrap show, add overflow: auto to it:
.lev2wrap {
  background: gold;
  overflow: auto;
}

jsFiddle example


How secured is a 24 character password?

Question: I use a 24 character password for my accounts. But how secured are they really? The characters are made of A-Z in Capital letters, a-z in small caps, 0-9, and special characters consisting "!@#$%^&*()"
So how many tries will it take to brute force it? Considering each character can only repeat no more than thrice in any single password so that no password ends up looking like kkkkkkkkkkk1111111112222.
I'd really like to know the answers.
Comment: When you say each character can only repeat thrice, do you mean that there cannot be a substring of identical characters more than three in length, or do you mean a character cannot appear more than thrice in total in the password?
Comment: I mean the character cannot appear more than thrice in total within the password
Comment: Well for a start you can get a lower bound for how many possible passwords there are. We have 26+26+10+10=72 characters and 24 spaces to fill, so if all characters are distinct there are [$72!/(72-24)!\approx 4.93\times 10^{42}$](https://www.wolframalpha.com/input?i=72%21%2F%2872-24%29%21) possible passwords. Allowing for repetition complicates things by allowing for more passwords;  you would have to add in the number of passwords having duplicates or triplicates.
Comment: @SarcasticSaturdayClub does these answers help you , if so ,you can upvote and accept
Answer: This question is very suitable for EXPONENTIAL GENERATING FUNCTIONS to show its power. When i look at your questions ,we see that there is not any restriction about character types , so each character is seem individual and independent. Moreover , it is said that each character can repeat at most thrice. Then , the exponential generating function of each character is equal to $$\bigg(1+ \frac{x}{1!}+\frac{x^2}{2!}+\frac{x^3}{3!}\bigg)$$
Whats more , we have $72$ characters in total. Then , find the coefficient of $\frac{x^{24}}{24!}$ in the expansion of $$\bigg(1+ \frac{x}{1!}+\frac{x^2}{2!}+\frac{x^3}{3!}\bigg)^{72}$$ , or find the coefficent of $x^{24}$ in the expansion ,and multiply it by $24!$ , namely $$24! \times [x^{24}]\bigg(1+ \frac{x}{1!}+\frac{x^2}{2!}+\frac{x^3}{3!}\bigg)^{72}$$
I give you LINK containing the calculation of the expansion.
As you see , the result is $$24! \times \frac{55,367,603,210,998,525,936,076,341}{93,312}= 3.681492296817581e+44$$
Answer: I am going to attempt to answer a more general question. Suppose there are $N$ distinct characters to choose from and we wish to form a password $L$ characters long. Your setup has $$L=24,\\N=26+26+10+10=72.$$
The question is how many possible passwords are there if no character appears more than thrice in total.

First, let's suppose we decide that $m$ different characters will be used once, $n$ different characters will be duplicated, and $p$ different characters will be triplicated. Then the following constraints must be obeyed:
$$m+n+p\leq N \quad (1)\\
m+2n+3p=L.\quad (2)$$
Note that constraint $(1)$ is automatically satisfied by constraint $(2)$ if $L\leq N$ (which happens in your case).
Having decided $m,n,p,$ we must actually choose among the $N$ characters which ones will appear once, which will be duplicated, which will be triplicated, and which will not be used.  There are
$${N \choose m,n,p,N-m-n-p}=\frac{N!}{m!n!p!(N-m-n-p)!}$$
ways to choose these character assignments.
Next, among the $L$ slots in our password to fill, $m$ slots must be chosen for the characters appearing once, $n$ slot pairs must be chosen for all the duplicates, and $p$ slot triples must be chosen for all the triplicates. So there are
$${L\choose \underbrace{1,...,1}_{m},\underbrace{2,...,2}_{n},\underbrace{3,...,3}_{p}}=\frac{L!}{1!^m2!^n3!^p}$$
ways to assign the chosen characters to slots.
Putting this all together, the total number of passwords is given by the following:
$$\sum_{(m,n,p)\in A}\frac{N!}{m!n!p!(N-m-n-p)!}\frac{L!}{1!^m2!^n3!^p},\\
A\equiv \left \{(m,n,p)\in \mathbb{Z}_+^3\bigg| m+n+p\leq N,m+2n+3p=L\right\}.$$

How secured is a 24 character password?


Thinktecture IdentityManager vs IdentityServer

Question: Looking at http://www.codeproject.com/Articles/683732/Thinktecture-Identity-Server-Configuration-Customi and http://brockallen.com/2014/04/09/introducing-thinktecture-identitymanager/ , I am a bit confused about the relation between IdentityServer and IdentityManager.
The way I currently understand it is the following:

IdentityServer can be used as an STS, and to manage users.
IdentityManager can be used to manage users.

Are the above statements correct? Will the users-part be phased out of IdentityServer in the future?
Answer: Dominick Baier (one of the authors of IdentityServer) posted this when announcing version 3:

while designing IdentityServer v3 we realized that we really also need a good solution for managing users, identity, claims etc – and that this should be ideally a separate project – so I'd also like to announce Thinktecture IdentityManager

You can read whole blog post here.
I don't know if users-part will be phased out of IdentityServer. The state now is that version 3 does not have GUI administration yet and all configuration is done in code. I am quite sure that Dominick and Brock Allen will eventually implement some web GUI for administration of idsrv but you should ask them maybe by opening a new issue here.
Answer: I'm pretty sure IdentityManager is intended to be the GUI for IdentityServer v3+. Therefore, there won't be one built in, as in previous versions.
Comment: Exactly, Identity Manager is used to manage the users on the database. You can create/edit users. Then, those users are able to identify using identityserver v3.

Dixit from github:IdMgr is a modern replacement for the ASP.NET WebSite Administration tool that used to be built into Visual Studio. It is meant to be a tool for developers and/or administrators to manage the identity information for users of their applications. This includes creating users, editing user information (passwords, email, claims) and deleting users.

[link](https://github.com/thinktecture/Thinktecture.IdentityManager)
Comment: The answer makes sense, but what confuses me as that there seems to be 2 similar constructs using each:

            appBuilder.UseIdentityServer(options);

and

            appBuilder.UseIdentityManager(new IdentityManagerConfiguration()
            {
                IdentityManagerFactory = factory.Create
            });

My guess is that UseIdentityManager will in fact call UseIdentityServer


Como relacionar dois form fields no django?

Question: Boa tarde!
Sou novo no django e estou criando um sistema que servirá como uma planilha para auxiliar na análise de algumas demandas.
As demandas serão uma Certidão chamadas de CAT solicitadas por arquitetos. Ou seja, uma CAT será vinculada a apenas um arquiteto, mas um arquiteto poderá ter várias cats e eu gostaria de saber como salvar essa relação no banco de dados e como lê-la depois.

O que eu quero fazer é que ao cadastrar a CAT e o profissional, um fique vinculado ao outro e eu possa depois pesquisar todas as CAT-As vinculadas a um profissional e possa verificar qual profissional vinculado a uma CAT. Mas usando apenas o foreignkey os dois não ficam vinculados, e no admin aparece uma lista de todos os profissionais cadastrados para eu vincular à CAT.
Answer: De fato, a forma correta de se implementar é utilizando uma Foreign Key (chave estrangeira) para o Arquiteto a partir da CAT. De acordo com o que você descreveu, os seus modelos estão corretos.
O que aparece pra você no Admin, com a lista do arquitetos para que você vincule à CAT, também está correto. Você deve escolher um dos arquitetos da lista e salvar a CAT, assim esse arquiteto está vinculado à CAT. Logo, você já tem de forma automática qual arquiteto está vinculado à CAT em questão.
Agora, para verificar todas as CATs que são vinculadas a um profissional, é um pouquinho mais complicado. Você precisa adicionar o método abaixo à classe Arquiteto:
def get_cats(self):
        return list(Cat.objects.filter(profissional_id=self.id))

Essa função retorna uma lista de todas as CATs vinculadas a um determinado arquiteto. Para isso, basta conhecer o ID do profissional em questão. Como esse é um método da própria classe Arquiteto, o ID nós já conhecemos: self.id.
O campo profissional_id é um campo criado automaticamente pelo Django na classe Cat devido ao uso da Foreign Key.
Se você lê um pouco de inglês, recomendo bastante a documentação oficial do Django sobre chaves estrangeiras: https://docs.djangoproject.com/pt-br/3.1/ref/models/fields/#django.db.models.ForeignKey
Comment: Sua resposta me esclareceu muito, Wensiso. Obrigado! Esse sistema seria utilizado por analistas e a ideia seria que eles não precisassem utilizar o admin, mas que a vinculação fosse feita automaticamente. Isso seria possível? Se não for possível fazer pelo django, seria possível fazer utilizando outra tecnologia?


General formula for the value of the $n$th derivative at $x=0$

Question: Can anyone show me how to derive this summation for the value of the $n$th derivative at $x=0$ for this function:
$\frac{d}{dx^n}(\exp({\frac{x^2}{2}+x}))$ is this sum:
$\frac{d}{dx^n}(\exp({\frac{x^2}{2}+x})) =$ $\sum\limits_{k=0}^{\lfloor{\frac{n}{2}\rfloor}} \frac{1}{2^kx^{2k}k!(-2k+n)!}$
Screenshot from wolfram alpha for the sum
Answer: One way is to define the sequence of polynomials
$\,P_n(x)\,$ such that
$$ P_n(x)\,e^{x+x^2/2} = \left(\frac{d}{dx}\right)^n e^{x+x^2/2}. $$ The coefficients of the polynomial sequence is the OEIS sequence A111062. Please consult the OEIS entry for more details. Of course, the function $\,e^{x+x^2/2}\,$ itself is the exponential generating function for the OEIS sequence A000085. The OEIS entry gives the summation formula
$$ a_n = \sum_{k=0}^{n/2} \frac{n!}{(n-2k)! 2^k k!}$$ which you already got from Wolfram|Alpha. Probably the easiest method is to find the power series for $\,e^x\,$ and
 $\,e^{x^2/2}\,$ and multiply them which will produce the formula.
More precisely, consider
$$ \sum_{n=0}^\infty a_n\, \frac{x^n}{n!}
 := e^{x+x^2/2} = e^x\,e^{x^2/2}= \\
 \sum_{j=0}^\infty \frac{x^j}{j!}
 \sum_{k=0}^\infty \frac{x^{2k}}{2^k k!}
 = \sum_{n=0}^\infty \frac{x^n}{n!}
\sum_{k=0}^{n/2} \frac{n!}{(n-2k)! 2^k k!}
$$ where $\,j = n-2k.\,$ Since we have
 $\,0\le j,\,0\le k,\,$ and $\,k=(n-j)/2,\,$ then
we must have $\,0\le k\le n/2.$
Comment: Any connection with Hermite polynomials (https://en.wikipedia.org/wiki/Hermite_polynomials) ?
Comment: @JeanMarie Yes, there are definite connections to Hermite Polynomials. In fact, there is a theory of polynomials with definition similar to both of them.
Comment: How did you get the upper limit of the sum as (n/2)
Comment: @ThaqibDamani2.0  Okay, I added last sentence about that. Thanks for asking.
Answer: Define $f(x) = e^{x^2/2}$ and $g(x) = e^x$.  Then $$(fg)^{(n)}(0) = \sum_{k=0}^n \binom{n}{k} f^{(k)}(0) g^{(n-k)}(0)$$ by the extended product rule.  Now $$f(x) = \sum_{k=0}^\infty \frac{(x^2/2)^k}{k!}, \quad g(x) = \sum_{k=0}^\infty \frac{x^k}{k!},$$ and by Taylor's theorem it follows that $$f^{(k)}(0) = \begin{cases}0, & k \text{ odd}, \newline \frac{k!}{2^{k/2} (k/2)!}, & k \text{ even}.\end{cases}$$  We also have of course $g^{(n-k)}(0) = 1$.  Then $$(fg)^{(n)}(0) = \sum_{k=0}^{\lfloor n/2 \rfloor} \binom{n}{2k} \frac{(2k)!}{2^k k!} = \sum_{k=0}^{\lfloor n/2 \rfloor} \frac{n!}{k!(n-2k)!2^k}.$$
Comment: how did u get ⌊n/2⌋ in the upper limit
Comment: Can you explain the Taylor's theorem part about odd and even


Grails command object not validating

Question: I'm sure this is a total noob question and I'm missing a blatant error, but here goes anyway.
I have a command object:
public class LeadCommand {
    Integer OwnerId
    String FirstName
    String LastName
    String Email
    String Phone1
    String Company
    String StreetAddress1
    String City
    String State
    String PostalCode
    String Country
    String Leadsource

    static constraints = {
        OwnerId(blank: false)
        FirstName(blank: false)
        LastName(blank: false)
        Email(blank: false, email: true)
        Phone1(blank: false)
        Company(blank: false)
        StreetAddress1(blank: false)
        City(blank: false)
        State(blank: false)
        PostalCode(blank: false)
        Country(blank: false)
        Leadsource(blank: false)
    }
}

And a controller action:
def process = { LeadCommand cmd ->

    if (cmd.hasErrors()) {
        redirect(action: index)
    } else {
            // do stuff
    }
}

The command object is getting populated, but is not following the validation constraints that I setup. I've read through the docs a couple of times, but I must be missing something...
Thanks in advance
BTW - I'm using Grails 1.3.7
EDIT:
Here is some sample post data: (straight from params map)
[Phone:,
OwnerId:1,
Country:United States,
LastName:,
City:,
PostalCode:,
State:,
Email:,
Leadsource:,
FirstName:,
Submit:Submit,
Company:,
StreetAddress1:,
action:process,
controller:leadEntry]

Comment: Can you post an example of test data you are submitting that should fail?
Comment: @schmolly159 updated question with post data
Answer: Rename your command properties to use the standard Java naming convention of camel case with an initial lower case letter.  Grails uses these conventions heavily and sometimes breaks if you don't follow them.  For example:
public class LeadCommand {
    Integer ownerId
    String firstName
    String lastName
    String email
    String phone1
    String company
    String streetAddress1
    String city
    String state
    String postalCode
    String country
    String leadsource

    static constraints = {
        ownerId(blank: false)
        firstName(blank: false)
        lastName(blank: false)
        email(blank: false, email: true)
        phone1(blank: false)
        company(blank: false)
        streetAddress1(blank: false)
        city(blank: false)
        state(blank: false)
        postalCode(blank: false)
        country(blank: false)
        leadsource(blank: false)
    }
}

Comment: This is what I was thinking as well.  First letter capitalized on an attribute or method = :(
Comment: That did it! Thanks ataylor. I usually follow those conventions but was trying to take a shortcut (the data is getting passed on to another app the requires the caps), but apparently Grails no likey. Thanks again.

Grails command object not validating


Definition and Doubt: Universal $\mathrm{C}^*$-Algebras given by generators and relations

Question: Let $A:=\mathrm{C}^*(G,R)$ be the (defined) universal $\mathrm{C}^*$-algebra generated by generators $G$ and relations $R$. As far as I can discern, there are two ways of defining such objects --- either using category theory or non-commutative polynomials and ideals.
The big ticket is that given any $\mathrm{C}^*$ algebra $A$ with $|G|$ generators that satisfy $R$ there is a unique surjective $*$-homomorphism $\mathrm{C}^*(G,R)\rightarrow A$. This is the universal property.
I have an informal way of thinking about universal $\mathrm{C}^*$-algebras (that will shortly come into conflict with my second question).
My informal intuition for universal $\mathrm{C}^*$-algebras is that we more or less form a large direct sum of all $\mathrm{C}^*$-algebras that have $|G|$ generators which satisfy $R$ and that is where the universal property comes from (or sums of) projections $\bigoplus_\alpha A_\alpha\rightarrow A_\beta$.

Question 1: How bad is this intuition? Is there something big that it misses (forget if it is formally incorrect)?

That is more or less the question on definition. Now for my doubt. We can consider a particular universal $\mathrm{C}^*$-algebra $B$ which is generated by a magic unitary $u=(u_{ij})_{i,j=1}^4$. That $u$ is a magic unitary is to say that each entry is a projection $u_{ij}=u_{ij}^2=u_{ij}^*$ and that each row and column is a partition of unity:
$$\sum_{k=1}^4u_{ik}=1=\sum_{k}u_{kj}.$$
In the compact quantum group community (say p.8) this universal $\mathrm{C}^*$-algebra is the setting for the algebra of continuous functions on the compact quantum group of permutations. The definition (of compact quantum group) requires a $*$-homomorphism $\Delta :B\rightarrow B\underset{\min}{\otimes} B$ and how this is constructed in this example is to define
$$\Delta(u_{ij})=\sum_{k=1}^4u_{ik}\otimes u_{kj},$$
and the way it is shown that this is a $*$-homomorphism is to show that the matrix:
$$\left[\Delta(u_{ij})\right]_{i,j=1}^4\in M_4(B\otimes B)$$
is a magic unitary, and so $\Delta:B\rightarrow B\otimes B$ is a *-homomorphism. Then the confusion comes in because in my informal intuition from a above $B$ is the largest object with magic unitaries... but here we have $B\otimes B$ which in my understanding is LARGER again than $B$ is also a sub-object of it...
Question 2: Is there a way to resolve this confusion with my informal intuition of what a universal $\mathrm{C}^*$-algebra (perhaps by arguing that the $\mathrm{C}^*$-algebra generated by $\left[\Delta(u_{ij})\right]_{i,j=1}^4$ while living in a large space $B\otimes B$, is in fact smaller than $B$... or is my informal intuition messing up my understanding here?
Comment: I believe your definition of universal property is slightly off. All that matters is that $A$ contains (not neccesarily distinct) elements $\{a_g \mid g \in G\}$ which satisfy the relations $R$. Then there is a unique (not necessarily surjective nor injective) $*$-homomorphism from $C^*(G,R)$ to $A$ taking $g \mapsto a_g$. Your map $\Delta$ is not necessarily injective nor surjective, just exists, and so whether not $B$ is "bigger" or "smaller" than $B \otimes B$ doesn't really come into play.
Answer: Question 1:  Your intuition is not only correct, but it also underlies the proof of the existence of the universal algebra.
Question 2: The universal property is only relevant in the domain.  All that is asked about the co-domain is that the relations be satisfied.
Comment: I don't quite understand your answer to Q.2... could you expand a little is it that we are only considering the algebra generated by the $\Delta(u_{ij})$... it feels a little self-referential to me at the moment.
Comment: The universal property says that whenever you have elements in some C*-algebra $A$ satisfying your relations (they need not be generators) you get your map.
Comment: Along the same lines as my comment above, even if the universal property required the co-domain to be generated by the $\Delta(u_{i,j})$, one could easily get around by replacing the codomain with the algebra generated by these elements.


Inserir Parenteses entre uma sigla no campo input

Question: Boa tarde pessoal, Estou com um probleminha em inserir parentêses entre siglas de um campo que eu criei. Segue meu código:
function maiusculo(){
    var quadro = document.getElementById("quadro").value;
    quadro = quadro.toUpperCase();
    quadrocorrige= "("+ quadro +")";
    document.getElementById("quadro").value = quadrocorrige;
}

O usuário, poderá digitar o Parenteses, mas só pode sair apenas um par, ou seja, se o usuário digitar a sigla RJ, o input corrige para (RJ)! Mas se o usuário digita (RJ), o javascript tá colocando ((RJ)).
Eu necessito que as siglas fiquem em maiúsculo e que estejam entre parentêses.
Comment: Não entendi seu problema. Você quer que isso seja como uma máscara, ou melhor, execute a cada vez que o usuário pressionar uma tecla?
Comment: @WeslleyCXSardinha, como uma máscara
Comment: Você está utilizando JQuery?
Comment: Não @WeslleyCXSardinha
Answer: Para que uma função seja executada a cada tecla digitada, usamos o evento oninput:
document.getElementById("quadro").oninput = function(){

    var value = this.value;

    var arr = value.split(' ');

    if(arr[0] && arr.length > 1){
        arr[0] = '(' + arr[0].replace(/\(|\)/g, '').toUpperCase() + ')';
    }

    this.value = arr.join(' ');

}

Answer: Fiz alguns ajustes aqui, e funcionou se caso o usuário inserir os parenteses a função não insere mais. veja se te ajuda qualquer coisa poste um comentário que te ajudo.

function maiusculo(){
    var quadro = document.getElementById("quadro");
    quadro = quadro.value.toUpperCase();

    if(quadro.charAt(0) !== "(" && quadro.charAt(quadro.length -1) !== ")" ){
        quadro = "(" + quadro +")";
    }

    var quadro = document.getElementById("quadro").value = quadro
    document.getElementById("a").innerHTML = quadro;

}

<input id="quadro">
<button onclick="maiusculo()">ver valor</button>

Answer: Só mais uma outra maneira que pode de ser feita:

var quadro = document.getElementById("quadro");

function maiusculo() {
  var valor = quadro.value;
  quadrocorrige = "(" + valor + ")";
  document.getElementById("quadro").value = quadrocorrige.toUpperCase();
}

quadro.onkeyup = function() {
  var valor = quadro.value;
  var rgex = /[(|)]/;  // regex que impede o uso dos () pelo usuário

  if(valor.length == 2) {
    maiusculo();
  } else if(valor.length == 3 ) {
    quadro.value = ''
  } else if(valor.match(rgex)) {
    quadro.value = '';
  }
}
<input id="quadro">
Answer: Tenta colocar um replace para remover os ( )

function maiusculo(){
    var quadro = document.getElementById("quadro").value;
    quadro = quadro.toUpperCase();
    quadrocorrige= "("+ quadro.replace("(", "").replace(")", "") +")";
    document.getElementById("quadro").value = quadrocorrige;
}
<input id="quadro">
<button onclick="maiusculo()">ver valor</button>


How to correctly block access to a port forwarded docker container?

Question: I have a VPS running docker. I have an Apache container running that port forwards some random port to port 80 in the container.
I can hit my VPS IP on the random port and it loads the site as expected.
In addition, I've setup SSL on my Nginx reverse proxy and am wanting SSL termination via Nginx which forwards the request in cleartext to the container. This is also working, but the container port is still exposed to the outside world.
What is the recommended approach to only allow what is defined in my nginx conf to be what is exposed? In other words, how can I secure the container to be only accessible to nginx?
Answer: By default docker binds mapped ports to 0.0.0.0, which exposes it to all interfaces. If you don't want that, you can bind it to the local interface only.
docker run -p 127.0.0.1:8080:80 httpd

Comment: Thanks, that was easy. For some reason I was thinking 0.0.0.0 was already binding to localhost and forgot it was exposing to all and not just local. Thanks for the quick response and explanation.


Qvalue.R results

Question: I have some p-values that I want to convert to q-values.  The issue I am running into is that the qvalues being generated by storey's qvalue package are all in a very tight range (i.e. .25-.35).
I am not sure what this means.  I am working with a ridiculously small dataset, given the number of hypotheses, could that be the problem?  I could understand if I had all high q-values, but that all of them having a ~.25 q-value... I'm just lost.
I would really appreciate it if someone could explain what I am not understanding here about q-values.
Thanks.
Edit:
A histogram of the p-values

Descriptive Statistics

count    249.000000
mean       0.395376
std        0.263631
min        0.006288
25%        0.173421
50%        0.351731
75%        0.588190
max        1.000000

Dispersion

p-val < .2  0.026
p-val > .2  0.092
Comment: First off, do you understand how a q-value is calculated from a p-value? http://en.wikipedia.org/wiki/False_discovery_rate#q-value
Comment: I have read the Storey paper, I even implemented it myself to get a better understanding of what was going on.  My real problem is I have not used it enough to get an intuition for the behaviour of qvalues under different conditions.  I was hoping to get a qualitative description of q-values and their relationship to different p-value distributions.
Answer: As Storey's q-values are estimates of the pFDR, with the Bayesian interpretation of "the probability of the null given the data", my guess is that the estimated  alternative distribution has high variance so that almost all values away from the null have similar pFDR.
Are your pvalues very spread except for a concentration near 0?
Comment: I appreciate your response.  I have added a histogram of the p-values and some descriptive statistics, including the dispersion for p-vals < and > .2.  They are concentrated near zero.  They were generated via permutation testing.  In general, I would expect this to be true. The method I am characterizing basically asks the question, can I differentiate between two subtypes with this network, where there are 249 networks.

Qvalue.R results


Need help with a JavaScript function to determine ascending numbers

Question: I have table rows, which have a start number and an end number (input fields).
Per row, the end must be larger than the start.
From inputs left to right, top to bottom the numbers must be larger than the last.
So there are 2 inputs per row, and 4 (for example) rows. Each number is bigger than the last.
I've been trying to validate this using this function
<code>   var maxDepth = 0,
  didValidate = true;

// I assume this reads from left to right top to bottom as they are that way in the markup
$('.input-start-depth, .input-end-depth').each(function(i) {

  maxDepth = Math.max(maxDepth, parseFloat($(this).val(), 10));

  var isStart = ($(this).hasClass('input-start-depth'));
  var value = $(this).val();

  if (isStart && value > maxDepth) {
    didValidate = false;

    return false;
  };

  lastValue = value;

});
</code>
I've been racking my head to get this to work. The other important thing is the number of rows is dynamic, there could be 1 or 10,000 or any in between.
Basically it is meant to say if the start depth is larger than the max depth so far, it should fail.
But it is validating numbers when they shouldn't be valid.
What am I doing wrong?
Cheers.
Comment: Fixing the indentation might clarify things a little... is that `if(isStart)` supposed to be there on line 11?
Comment: @sje397 Sorry, good catch. I removed some `console.log()`'s in there for the sake of clarity.
Comment: So if you have a 2x2 table (0, 1), (2, 3) (where , denotes a new row), is that valid?
Answer: i don't think you can assume the order in which the elements are read. you should look into reading the table row by row. here's some code to look at to see what i mean:
<code>$('table#mytable tr').each(function() {
  var start = parseInt($(this).find('.input-start-length').val());
  var end   = parseInt($(this).find('.input-end-length').val());
  if(start > maxDepth) {
    didValidate = false;
    return false;
  }
  lastvalue = start;
});
</code>
Comment: I `after()`'d the each iterator and it did go in the order I expected.
Answer: I ended up using, which seems to work
<code>$('table tbody tr').each(function(i) {

                var startDepth = parseFloat($(this).find('.input-start-depth').val(), 10);
                var endDepth = parseFloat($(this).find('.input-end-depth').val(), 10);

                var anyNans = isNaN(startDepth) || isNaN(endDepth);

                if (anyNans || startDepth > endDepth || startDepth < maxDepth) {
                    didValidate = false;
                    return false;
                };
                maxDepth = Math.max(maxDepth, endDepth);

            });
</code>
Comment: Note that parseFloat only takes one parameter, unlike parseInt, where you probably do want to pass 10 as the second parameter.
Comment: Also note that you require endDepth >= startDepth and startDepth >= maxDepth which means that maxDepth is always the previous endDepth.


passar uma struct utilizando extern C em uma .dll c++

Question: Possuo uma função que vem de uma .lib que me retorna um struct
tabela GSTV(vector<double> inpA, vector<double> inpB);

esse struct é definido da seguinte forma:
struct tabela {

    vector<int> Z;
    vector<double> F;
    vector<double> S;
    vector<double> Y;

};

Porém estou transformando esse .lib em uma .dll com extern "C"
Quando tenho para um vetor eu costumo fazer:
vector<int> GSTV(vector<double> inpA, vector<double> inpB);

passar a ser
extern "C" MINHADLL_API void GSTV( vector<double> inpA, vector<double> inpB, vector<int> &GSTV_ans);

E assim pelo argumento eu gero o meu vetor, entretanto para um struct isso não está funcionando.
Answer: Parece que era apenas preciso declarar um extern "C" da struct no cabeçalho da .dll também:
extern "C" struct tabela;

dessa forma pelo que entendi ele converte a struct da .lib original e funciona corretamente o código.


eclipse juno and jsf 2.1

Question: eclipse won't let me create a project with JSF 2.1 because "Required class javax.faces.FactoryFinder does not exist in selected libraries", but the class does exist.
works well with jsf 2.0.9
Comment: I solved it by moving the JSF 2.1 library outside my project
Comment: So you solved it and answer you question yourself or remove your post.
Answer: This is because you may be added your JSF jar file in web-inf/lib folder and after that you add this jar in your jsf configuration.

eclipse juno and jsf 2.1


Is there a required format for table name prefix?

Question: I know that in MySQL installations it must end in an underscore like prefix_ but I want to know if that is also the required format for Postgres and SQLite.
Answer: There is no requirement for the prefix to end in an underscore for any type of database but it can be beneficial for readability.
It is just a string of characters that Drupal prepends to table names in queries so it can contain any characters that are legal to use in table names in your chosen type of database.
Database prefixes are also not necessary at all unless you are using a single database for multiple purposes, for example you have all your drupal tables prefixed with drupal_ and then have other non-drupal tables without a prefix or with a different prefix.
That way you can easily tell which tables are for what.
This is usually only necessary if your hosting provider limits the number of databases you are allowed or sometimes in some more advanced Drupal configurations.
The way Drupal uses it is that if you use one of the db functions like db_select(), db_insert(), db_update(), db_delete() it automatically appends any prefix value you have configured.
When using db_query() it will also do this for any table name wrapped in braces, eg:
db_query("SELECT * FROM {node}");

Comment: Thank you. So this is an internal Drupal feature, separate from the ability of certain DBMSs to handle schemas, as in 'schema_name'.'table_name' ?
Comment: Yes. By default it will be schema_name.table_name. If you use a drupal prefix it will be schema_name.prefixtable_name.


I need help clarifying what (R1,..RN) is in this context

Question: Let R be the space of all the N! permutations of (1,2, ..., N), and let R = (R1,...RN) be uniformly distributed over R.
The thing i don't understand is what "R = (R1,...RN) be uniformly distributed over R." mean
Comment: R is something uniformly distributed over itself? That doesn't make sense.
Comment: @Galen I just re-read the question and let me rephrase it, let **R** be the sapce of all the N! permutations and R = (R1,...,RN) be uniformly distributed over **R**. So its 2 different R, i believe the regular R to be the rank vector but Im not entirely sure.
Answer: Your statement will make a bit more sense if you use more standard notation to differentiate vectors of values from sets.  I would write it as follows:

Let $\mathscr{R}$ be the space of all $N!$ permutation vectors of $(1,2,...,N)$ and let $\mathbf{R} = (R_1, ..., R_N)$ be uniformly distributed over $\mathscr{R}$.

This means that the vector $\mathbf{R}$ is a permutation vector of the set $(1,2,...,N)$ and this vector has $N!$ possible values that are collected together in the set $\mathscr{R}$.  To give a simple example, for $N=3$ you would have $3!=6$ possible values for the permutation vector, given explicitly by the set:
$$\mathscr{R} = \{ (1,2,3), (1,3,2), (2,1,3), (2,3,1), (3,1,2), (3,2,1) \}.$$
The uniformity specification then means that:
$$\mathbb{P}(\mathbf{R} = \mathbf{r}) = \frac{1}{N!}
\quad \quad \quad
\text{for all } \mathbf{r} \in \mathscr{R}.$$


R Decision Tree based on imbalanced data which was up-sampled

Question: This is a rather theoretical question, so I'm sorry if that's not appropriate to the platform. I have trained a decision tree (partykit) on an imbalanced data set, and to force the model to learn both positive and negative examples I have up-sampled the data to be balanced. On a validation/test set performance was more than decent (balanced accuracy > 80%). However, when trying to interpret the tree with business users, they were surprised with inflated prediction probabilities and I think those probabilities are distorted since the data was up-sampled.
Is there anyway to stream the test set (which is not balanced) through the tree and get the prediction probabilities on the test set (both visually and by printing the tree )?
Comment: This is a very interesting question, but would be better suited on crossvalidated.com (voting for a migration).
Comment: Can I migrate this question from within this platform ?
Comment: In my limited experience upsampling/downsampling  with `SMOTE` did not help in improving prediction accuracy also useful [reference](http://bmcbioinformatics.biomedcentral.com/articles/10.1186/1471-2105-14-106)
Comment: In general,  up-sampling the minority class will not improve accuracy, but increased accuracy is not the goal.  Take a look at [This Answer](http://stats.stackexchange.com/a/259971/141956)
Answer: I share the critical view of upsampling raised in some of the previous comments. Especially for conditional inference trees there is the additional issue that the meaning of the $p$-values in the tree is not so clear.
Having said that, it is fairly straightforward to associate a fitted partykit tree with a new data set. The building blocks for this are described in the vignette("partykit", package = "partykit"). As a simple illustration let's upsample the kyphosis data set for approximately balanced response categories:
data("kyphosis", package = "rpart")
table(kyphosis$Kyphosis)
##  absent present
##      64      17
ky2 <- kyphosis[rep(1:nrow(kyphosis), c(1, 4)[kyphosis$Kyphosis]), ]
table(ky2$Kyphosis)
##  absent present
##      64      68

The tree on the upsampled data can be created, printed, and visualized by:
ct2 <- ctree(Kyphosis ~ ., data = ky2)
print(ct2)
## Model formula:
## Kyphosis ~ Age + Number + Start
##
## Fitted party:
## [1] root
## |   [2] Start <= 12
## |   |   [3] Age <= 27: absent (n = 13, err = 30.8%)
## |   |   [4] Age > 27: present (n = 67, err = 16.4%)
## |   [5] Start > 12
## |   |   [6] Start <= 14: absent (n = 23, err = 34.8%)
## |   |   [7] Start > 14: absent (n = 29, err = 0.0%)
##
## Number of inner nodes:    3
## Number of terminal nodes: 4
plot(ct2)

To associate the same tree/node structure with the original kyphosis data without subsampling we just need to: extract the tree ($node), get the fitted nodes and observed response, and add data and terms. This can then also be converted into a constparty (recursive partyitioning with constant fits) and printed/visualized.
ct <- party(ct2$node,
  data = kyphosis,
  fitted = data.frame(
    "(fitted)" = predict(ct2, newdata = kyphosis, type = "node"),
    "(response)" = kyphosis$Kyphosis,
    check.names = FALSE),
  terms = terms(Kyphosis ~ ., data = kyphosis),
)
ct <- as.constparty(ct)
print(ct)
## Model formula:
## Kyphosis ~ Age + Number + Start
##
## Fitted party:
## [2] root
## |   [2] Start <= 12
## |   |   [3] Age <= 27: absent (n = 10, err = 10.0%)
## |   |   [4] Age > 27: present (n = 25, err = 44.0%)
## |   [5] Start > 12
## |   |   [6] Start <= 14: absent (n = 17, err = 11.8%)
## |   |   [7] Start > 14: absent (n = 29, err = 0.0%)
##
## Number of inner nodes:    3
## Number of terminal nodes: 4
plot(ct)

Comment: Thanks for your solution. However, one odd thing is happening when I run this code, it seems that the call to party is actually creating (fitting) a new decision tree with the newdata. The original intention was to fit a tree on a training set, and then feed the tree with a test set and visualize the errors on the leaf nodes
Comment: Actually, my mistake - the tree is actually the same, however, the names of the variables are mixed up, e.g. original tree:  [1] root
|   [2] ProbabilityDown <= 0
|   |   [3] Total_Data_Size.fixed <= 2
|   |   |   [4] Employees.fixed <= 2 and the new tree : [1] root
|   [2] ProbabilityUp <= 0
|   |   [3] NumberofCalls <= 2
|   |   |   [4] Time_Frame.fixed <= 2
|   |   |   |   [5] StagesDuration <= 0
Comment: The order of the variables needs to be the same because the `node` only stores the _number_ of variable not its _name_. Hence ordering matters. You could use `newdata[names(ct$data)]` to set up the same ordering in `newdata` as you had in `ct`.


Distribution of $|X|$

Question: Find the distribution of $|X|$ if $X \sim N(\mu, 1)$
My attempt:
$$P(|X| \leq x) = F_X(x) - F_X(-x)$$
If $F$ denote the cumulative distribution of $X$, then
$$P(|X| = x) = \frac{1}{\sqrt{2\pi}}(\exp(-1/2(x-\mu)^2 + \exp(-1/2(x+\mu)^2).$$
But i am confused if it is correct and about the limits of integration of this variable. Also, can we write it in function of $|X|$?
Thanks!
Comment: $P(|X|=x)=0$. Don't confuse it with the PDF.
Answer: $F_{\left|X\right|}\left(x\right)=P\left\{ -x\leq X\leq x\right\} =P\left\{ X\leq x\right\} -P\left\{ X<-x\right\} =F_{X}\left(x\right)-F_{X}\left(-x\right)$
This for $x\geq0$.
The last equality follows from $P\left\{ X=-x\right\} =0$.
If $x<0$ then $F_{\left|X\right|}\left(x\right)=0$.
Here $X=\mu+U$ where $U$ has standard normal distribution.
So $F_{X}\left(x\right)=P\left\{ U\leq x-\mu\right\} =\Phi\left(x-\mu\right)$
where $\Phi$ denotes the CDF of the standard normal distribution.
We end up with:
$F_{\left|X\right|}\left(x\right)=\Phi\left(x-\mu\right)-\Phi\left(-x-\mu\right)$
if $x\geq0$ and $F_{\left|X\right|}\left(x\right)=0$ otherwise.
Here $$\Phi\left(u\right):=\int_{-\infty}^{u}\phi\left(y\right)dy=\left(2\pi\right)^{-\frac{1}{2}}\int_{-\infty}^{u}e^{-\frac{1}{2}y^{2}}dy$$
and: $$\Phi'\left(u\right)=\phi\left(u\right)$$
This enables us to find the PDF of $\left|X\right|$. Denoting it
by $f_{\left|X\right|}$ we can take $f_{\left|X\right|}\left(x\right)=0$
on interval $\left(-\infty,0\right]$. On interval $\left(0,+\infty\right)$
we find $f_{\left|X\right|}$ as derivative of $F_{|X|}$ :
$$f_{\left|X\right|}\left(x\right)=\phi\left(x-\mu\right)+\phi\left(-x-\mu\right)=\left(2\pi\right)^{-\frac{1}{2}}\left[e^{-\frac{1}{2}\left(x-\mu\right)^{2}}+e^{-\frac{1}{2}\left(x+\mu\right)^{2}}\right]$$
Comment: Ineed to find the pdf of |X|, and I just derivated on x to obtain what I got
Comment: That will be $\phi\left(x-\mu\right)+\phi\left(-x-\mu\right)$ as derivative of
$\Phi\left(x-\mu\right)-\Phi\left(-x-\mu\right)$

Distribution of $|X|$


How to switch from one view to another in iPhone?

Question: I am a beginner in objective-c. Can anyone please tell me how can I switch from one view to another in an iPhone application.
Comment: You should be more specific about exactly what you are trying to do.  Are you using a navigation controller or a tab bar controller?  Have you looked at any of Apple's sample code?  Have you read any documentation?
Comment: Possible duplicate of http://stackoverflow.com/questions/4845188/how-to-switch-from-one-view-to-another
Answer: View Programming Guide for iOS
iPhone View Switching Tuturial
How To Switch Views using Multiple Viewcontrollers (Method 1)
Switching Views with Animation
How to animate View swap on simple View iPhone App?
switch between uiviews with buttons and not uinavigation controllers
Switch between UIViewControllers using UISegmentedControl
Answer: There are 3 main controllers that can switch views for you:

UINavigationController

Here you push and pop views in a chain.
There will be a navigation bar on top which lets you navigate back to where you came from.

UITabbarController

Here all the views will be represented by tabs at the bottom of the screen.
You can switch back and forward between them by clicking them in the tabbar.

UIViewController

There is a method in UIViewController wich lets you "present" other viewcontrollers. It's called presentModalViewController:animated:
You will have to do your own navigation back to the parent by using dismissViewControllerAnimated:

You can also do your own switching with variations of addSubView: or view.hidden or similar, but I would recommend those 3 to begin with.


$F(x)$ versus $F[x]$ where $F$ is a field

Question: What is the difference, if there is any, between $F(x)$ and $F[x]$, where $F$ is a field and $x$ is an element of a field extension $E/F$ that is not in $F$? I have some guesses, but I was never sure about this. For example, for one specific usage in a textbook, I see $\mathbb{Q}[i]$ and $\mathbb{Q}(\pi)$. And maybe a more general question: what happens when $F$ is just a ring? For example, for the ring of Gaussian integers, the notation I usually see is $\mathbb{Z}[i]$, with brackets instead of open parentheses. I guess I never properly learned the notation.
Answer: Short answer: given a ring $A$ and an element $x$, the notation $A[x]$ denotes the smallest ring that contains both $A$ and $x$. If $A$ happens to be a field, then $A(x)$ denotes the smallest field that contains both $A$ and $x$. That's all.
Longer answer: given a ring $A$, we denote by $A[x]$ the ring of polynomials in the variable $x$ with coefficients in $A$. Starting from the description in the above paragraph, if a ring contains $x$, it must also contain $x^2,x^3$, and so on. And sums of these. And the results of multiplying these with one another and with the elements of $A$. Without any more context, these are just polynomials the way you're used to them.
If $A\subseteq B$ and $x\in B$, then $x$ inherits any relations it may satisfy in $B$ when used in this polynomial ring. One example is the ring of Gaussian integers $\Bbb Z[i]$, where $i^2=-1$. If $x$ satisfies no relations that can be described using only elements of $A$, then it acts like in the previous paragraph, and you get regular polynomials with no special rules. Your $\Bbb Q[\pi]$ is an example.
If $F$ is a field, then $F(x)$ is the smallest field that contains both $F$ and $x$. Starting from the description in the first paragraph, this field must for the same reason contain all polynomials in the variable $x$ with coefficients in $F$. But it must also contain the reciprocal of any non-zero polynomial. Same things as in the above paragraph apply: If $x$ satisfies some algebraic relation that can be phrased using only coefficients from $F$ (we call this "$x$ is algebraic over $F$"), then that's baked into $F(x)$. Your $\Bbb Q(i)$ is an example of that, where $i^2=-1$ is the algebraic relation in question.
When $x$ is not algebraic over $F$, then $F(x)$ becomes the field of rational functions in the variable $x$ with coefficients in $F$. Which is to say, the elements of $F(x)$ are fractions where the numerators and the denominators are polynomials in $F[x]$. One concrete example is $\Bbb Q(\pi)$. But the fact that $\pi$ lies inside a well-known extension of $\Bbb Q$ is unnecessary. $\Bbb Q(x)$ works just as well, where $x$ is just an abstract variable.
If $x$ is algebraic over $F$, then $F[x]$ and $F(x)$ turn out to be isomorphic: fractions in $F(x)$ can always be expanded so that the denominators have no $x$ in them. Thus you will see either one used, which can be a point of confusion. For instance, $\Bbb Q(i)$ and $\Bbb Q[i]$ are, for all practical intents and purposes, the same thing.
Comment: You said that if $x$ is algebraic over $F$, then $F[x]$ and $F(x)$ turn out to be isomorphic. I just want to say that they are not only isomorphic, but they are equal!
Comment: @ArielFishbein Not in my book, because $F(x)$ has elements that look like $\frac 1x$, and $F[x]$ doesn't have those.
Comment: remember you said that $x$ is algebraic. E.g $F=\mathbb{Q}$ and $K=\mathbb{R}$.
Now, $\frac 14\in F(4)$ but $1/4=\frac{1}{16}\cdot 4 \in F[x]$.
Comment: If you want, I can prove to you that if $\alpha$ is algebraic over $F$ with a minimal polynomial $p(x)$, then $F(\alpha)=F[\alpha]\cong F[x]/(p(x))$.
Just tell me if you want to see this prove, and I'll be happy too
Comment: The element $\frac{1}{\sqrt2}$ is not in $\Bbb Q[\sqrt2]$. The element $\frac{\sqrt2}{2}$ does exist there. The two rings / fields are isomorphic, but one of them has names for elements that the other one doesn't.
Comment: I don't know what to tell you other than that $\frac{\sqrt{2}}{2}=\frac{1}{\sqrt{2}}$
Comment: @ArielFishbein In $\Bbb Q(\sqrt2)$, yes.. In $\Bbb Q[\sqrt2]$, we only have polynomials, so elements have the names $a+b\sqrt2$ for $a,b\in\Bbb Q$, and no others. Of course, this is being pedantic, but I will stand by my statement that $\Bbb Q[\sqrt 2]$ and $\Bbb Q(\sqrt2)$ are two different rings, because their underlying sets of formal algebraic expressions are different. They are very obviously isomorphic with a very obvious isomorphism, but they are not the same.
Comment: (I say no others, but of course we have higher degree expressions, any finite variation of $a+b\sqrt2+c\sqrt2^2+\cdots$. What you DON'T have in $\Bbb Q[\sqrt2]$ are fractions with $\sqrt2$ in the denominator.)
Comment: If $\alpha$ is algebraic, then $F[\alpha]$ becomes a field that contains both $\alpha, F$. But by definition, $F(\alpha)$ is the smallest field that contains $\alpha, F$ so we get that $F(\alpha)\subseteq F[\alpha]$. But it is also obvious that $F[\alpha]\subseteq F(\alpha)$. So we can conclude by saying that $F[\alpha]=F(\alpha) \square$
Comment: @ArielFishbein We can conclude they are isomorphic. There is no "the" smallest field. There are infinitely many of them, and they are all isomorphic. You can't use universal properties like that to prove that things are actually equal. You can't prove $\subseteq$, you can only prove there exists injective homomorphisms. It is NOT obvious that $F[\alpha]\subseteq F(\alpha)$, because their elements have different names.
Comment: $F[\alpha]=\{\sum\limits_{i=0}^n a_i \alpha^i: a_i\in R \}$ and $F(\alpha)=\{\frac{p(\alpha)}{q(\alpha)}\bigg| p,q\in F[\alpha]\}$
Comment: Can you please tell me then what is the isomorphism between $F[\alpha]$ and $F(\alpha)$?
Comment: The isomorphism $F[\alpha]\to F(\alpha)$ is given by $f\mapsto \frac f1$. Note that I didn't say $f\mapsto f$, because by your own definition, the elements of the two fields are written differently. It is even clearer that it isn't an equality if you try to write the inverse isomorphism. If you have a rational expression in $\alpha$, you need to massage it pretty heavily to make it into a polynomial. Rational expressions aren't the same as polynomials, even with an algebraic variable, and therefore a ring of rational expressions is not a ring of polynomials, even if it's isomorphic to one.
Comment: Ill think about it. Anyways it was an interesting convo. Cya!
Answer: $F[x]$ is the ring of all polynomials in $x$ with coefficients from $F$. In contrast, $F(x)$ is the smallest field which extends $F$ and contains $x$: in other words, it contains all rational functions (i.e. quotients of polynomials) in $x$ with coefficients from $F$, rather than just all polynomials. Note that sometimes these can be the same, e.g. $\mathbb{Q}\left[\sqrt{2}\right]$ is the same as $\mathbb{Q}\left(\sqrt{2}\right)$, since any polynomial in $\sqrt{2}$ can be written in the form $a+b\sqrt{2}$, and if $a,b,c,d \in \mathbb{Q}$ then $$\frac{a+b\sqrt{2}}{c+d\sqrt{2}} = \frac{ac-2bd}{c^2-2d^2} + \frac{bc-ad}{c^2-2d^2}$$ where the coefficients are still in $\mathbb{Q}$.
Answer: Well, $F[x]$ means ring adjunction of $x$, while $F(x)$ means field adjunction of $x$.
More concretely,
$F(x) = \left\{\frac{f(x)}{g(x)}\mid f(x),g(x)\in F[x], g(x)\ne 0\right\}$
is the field of quotients of $F[x]$.
$\Bbb Q(i) = \{a+ib\mid a,b\in\Bbb Q\}$ with $i^2=-1$ is the field adjunction of $i$ to $\Bbb Q$. It's a field and the same as the ring adjunction $\Bbb Q[i]$ (as its also a field).
$\Bbb Z[i] = \{a+ib\mid a,b\in\Bbb Z\}$ with $i^2=-1$ is the ring adjungation of $i$ to $\Bbb Q$. Its's a ring.
Beware of $\Bbb Q(\pi)$. As $\pi$ is tranzendential over $\Bbb Q$, this field extension of $\Bbb Q$ is infinite.
You need to learn about ring and field adjunction.
Comment: I think in English the word that goes with "adjoin" is more commonly "adjunction" and I have never seen "adjungation". But in mathematics it might also be more common to speak of things like "a ring extension obtained by extending the ring by adjoining an element" than ring or field "adjunctions". And the spelling is usually "transcendental" rather than "tranzendential".


Open a Make Meeting field inside colorbox

Question: I am using the Make Meeting Scheduler for my site, which is a Doodle-like scheduler module. This module makes it possible to insert a field (only field, not available as block) into a node. However, I need to open this field inside Colorbox.
I know a possible workaround would be to create separate nodes with only the Make Meeting field and then connect them to the original nodes where I need them, but this is definitely not an elegant solution.
I'm really not good with Drupal templates and that is why I haven't come up with a better solution. I suppose I should edit the template, print a link with the class "colorbox-load" and have that link point to the Make Meeting div. Problem is, I am currently clueless as to how to do that.
Answer: The easiest way to do this is through views. You can configure a view with an "Contextual Filter" of the node id to show and then configure it to show your makemeeting field here. Here's a screenshot of a view that worked for me (note the important parts are marked with arrows.

Then when I go to /meeting-popup/6 (where 6 is the id of a node with a meeting field) i see the following.

Then you can add a link to /meeting-popup/ on the nodes page using the lightbox-load class so it will showup in a popup.
Lastly you can theme the meeting-popup pages so that they only show the content and don't show any regions/sidebars, etc.
Alternatively you can have views make it into a "block" if you know of a good way to do it that way.
Comment: Okay, I managed to make everything work except the contextual filter. It's my lack of knowledge, I'm sure you explained it quite well. Could you please clarify that? I added a link to my nodes that goes like this Make an appointment, but I still get all of my fields in the colorbox. Could you please help me with the contextual filters bit? How do I get only the fields for the specfic node?
Comment: The link needs to be /make-meeting/10, if 10 is the node id of the current node the user is looking at. So you will need to do some PHP ($node->nid) or use tokens  [node:nid] depending on how you are inserting the link.


Find index of javascript "array of objects" based on object field value

Question: I have a Javascript array of objects and I would like to find index of the array element (object) where particular object's field is matching my search criteria.
That is, array looks like
  [{id:1, saved:0, name: "name1"}, {id:26, saved:0, name: "name2"},
    {id:3, saved:0, name: "name3"}, {id:15, saved:0, name: "name4"}]

and I would like to locate index of the element where element's id field is equal to, say, 15.
I am using angular and jquery.
Answer: You'd have to iterate, here's a very simple example
var index = null;

for (var i=0; i<array.length; i++) {
    if ( array[i].id == 15 ) {
        index = i;
        break;
    }
}

That gets you the index, if you just want to return the object you can do
var obj = array.filter(function(obj) {
    return obj.id == 15;
}).shift();

Answer: With ES6, you could use Array#findIndex

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.

var array = [{ id: 1, saved: 0, name: "name1" }, { id: 26, saved: 0, name: "name2" }, { id: 3, saved: 0, name: "name3" }, { id: 15, saved: 0, name: "name4" }],
    index = array.findIndex(({ id }) => id === 15);

console.log(index);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Answer: array.filter is JavaScript's more elegant method for achieving this:
var arrr = [{id:1, saved:0, name: "name1"}, {id:26, saved:0, name: "name2"},
{id:3, saved:0, name: "name3"}, {id:15, saved:0, name: "name4"}];

return arrr.filter( function( value ){ return value.id == 15; })[0];

Comment: You can get the item this way, but how can I get the index of that item in the array?
Answer: There are multiple ways to do this.
You could iterate through the array and do a search.
var search = 15;
for(var index=0; index<input.length; index++) {
   if(input[index].id == search) {
       //Do whatever you want to do with this index.
   }
}

Or you could create a lookup first
var lookup = {};
for(var index=0; index<input.length; index++) {
   var element = input[index];
   lookup[element.id] = element;
   lookup[element.id].index = index;
}

Now, in every subsequent look-ups of a search term, you could do the following
var search = 15;
if(lookup[search]) {
   var index = lookup[search].index;
}

Answer: Try this:
$.each(json.yourrootjson, function(i, v) {
    if (v.id == "15") {
        alert(v.id);
        alert(v.name);
        alert(v.saved);
        return;
    }
});

Answer: Here is a very basic way to do it. Of course, you won't want to use the variables key and match statically like I did, but I will have to know more about your code to help you with that as well.
var array = [{id:1, saved:0, name: "name1"}, {id:26, saved:0, name: "name2"},
             {id:3, saved:0, name: "name3"}, {id:15, saved:0, name: "name4"}]

var key = 'id';
var match = 15;

array.forEach(function(elem, i) {
    if (elem[key] === match) {
        alert(i);
    }
});

Answer: There are a lot of sources out there but a while loop appears to be the fastest way to iterate an array. Alternatively, Array.map() is in my opinion the cleanest way but actually turns out to be fairly slow.
Benchmarks
Article on loops
var array = []; // your array
var len = array.length;

while (len-- ) {
  if ( array[i].id == 15 ) {
    console.log(array[i])
  }
}


Why angular packages are separated and why we need them

Question: I have started building a new angular 2 app. I have gone through the articles and downloaded some free apps from github, all of them have angular/comman package along with some other packages. I installed angular package and it added "angular": "^1.6.5" in package.json file. I am not sure if we can have full package then why we install comman package separately ?
When I checked other app then they mostly have following
"@angular/common": "2.0.1",
"@angular/compiler": "2.0.1",
"@angular/core": "2.0.1",
"@angular/forms": "2.0.1",
"@angular/http": "2.0.1",
"@angular/platform-browser": "2.0.1",
"@angular/platform-browser-dynamic": "2.0.1",
"@angular/router": "3.0.1",

are they all part of angular core ? I can not see angular package here.
Is there any article or guidelines for angular 2 packages ?
Answer: Here is the brief description of each package:
Required

@angular/core - contains core functionality like decorators, component views, change detection etc.
@angular/compiler - contains Angular compiler.

Required depending on the environment and setup

@angular/platform-browser - contains browser specific code required to bootstrap the application and work with the DOM. May not be required if you use Angular on the platform other than browser.
@angular/platform-browser-dynamic - contains implementations for the dynamic bootstrap of the application. Not required if you use AOT.

Usually required

@angular/common - contains common directives and pipes
@angular/forms - contains forms implementation
@angular/http - contains http client implementation
@angular/router - contains router implementation

The reason for not packaging it all into one huge @angular package is because you may not need everything in your runtime. You application may not use forms, or built-in directives like ngFor, or may not use routing. Why load it all into the browser?
Also, the second group of packages is sometimes required and sometimes not depending on the setup. The only thing that is always required in runtime is @angular/core.
See also the official docs.
Comment: Also the doc link: https://angular.io/guide/npm-packages#feature-packages
Comment: @Maximus Thanks Dude, that's great info for a beginner, I was struggling to decide the packages for long time.
Comment: @echonax, thanks, I'll add the link. Didn't know it existed)
Comment: @Maximus Thanks ! I wonder if you can share your thoughts on https://stackoverflow.com/questions/45185310/angular-2-app-loads-too-slow-and-bundle-file-size-is-huge  and what should I use for my live project angular CLI or webpack ?