Enquete com PHP

Question: 10 usuários responderão uma enquete com 19 opções iguais para todos, cada resposta é salva no banco numa tabela chamada 'votos' com a seguinte estrutura:
id: 1 - user_id: 1 - resposta: {resposta do usuário}
Quero contabilizar todas as 10 respostas e mostrar a mais votada, por exemplo.
3 pessoas votaram na opção 'CASA'.
5 pessoas votaram na opção 'TRABALHO'
e 2 pessoas votaram na opção 'LAZER'.
Como posso mostrar que a mais votada foi TRABALHO e que 5 pessoas votaram nela?
Comment: se o campo resposta for do tipo varchar pode ser que vc tenha problemas, mas acredito que tudo que você precisar fazer é um count no campo resposta e agrupar por usuário.
Answer: Se entendi direito sua pergunta ...
e se a tabela é assim .....

então o select é esse
<code>Select resposta, count(resposta)
from votos
group by resposta
having count(resposta)=(Select max(A.CNT)
from (Select count(resposta) as CNT
from votos
group by (resposta)) as A)
</code>
e o resultado é esse
Comment: Funciona. Mas não entendi nada kkkkkk.
Comment: @VitorLeite, pois é, tem que dar uma pesquisada/estudada em cada clausula da query pra vc entender, count, group, having. Agora se a resposta serviu marque-a como aceita.

Enquete com PHP


Save activity data when switching to different activity in android like Whatsapp

Question: I am basically developing a chat app just like whatsapp, so I am also using Room database for persisting the chats for offline use. I store message delivered, seen, sent status with each message in database. So, if a user try to upload any media like then I want to show progressbar for file upload just like whatsapp, but where does whatsapp stores that download progress of each media message, because it seems they don't save it to Database because it's kind of temporary data and it changes very fast. Even when I switch from a person's chat to Chatlist in whatsapp aand go back to the person's chat I can see the upload bar there, so how does it maintain the state during activity switches.
I heard of using sharedpreferences and saveinstance() , but they are delivering some other functionality I think.
Answer: Have look into:
ViewModel  &  LiveData
The ViewModel keeps track of the state independent of what View is shown. And via LiveData you can update the current View. Since LiveData knows about the respective LifeCycle, it only updates the person's chat when it is currently active.


sort a list of maps according to a list elixir

Question: I have this sorted list
@days ["mon", "tue", "wen", "thu", "fri", "sat", "sun"]

and I have a list of maps such as
[%{day: "sat"}, %{day: "tue"}, %{day: "fri"}]

I am trying to sort the list of maps according to days, I have tried Enum.sort_by/2 but I am unable to put the right condition. any help would be thankful.
Answer: What you want, is to produce a sorter with O(1) access in the first place
iex||1 ▸ days = ["mon", "tue", "wen", "thu", "fri", "sat", "sun"]
["mon", "tue", "wen", "thu", "fri", "sat", "sun"]
iex||2 ▸ days_idx = days |> Enum.zip(1..7) |> Map.new()

Now sorting the original list would be as easy as
iex||3 ▸ Enum.sort_by(
...||3 ▸   [%{day: "sat"}, %{day: "tue"}, %{day: "fri"}],
...||3 ▸   &days_idx[&1[:day]])

#⇒ [%{day: "tue"}, %{day: "fri"}, %{day: "sat"}]

Comment: Happy new year Aleksei! and thank you.
Comment: You spilled some stuff on your prompt
Comment: btw what if the unsorted list does not implement the Access behaviour for the map?
Comment: I produde the map myself, see the 1st iteration.


Why these two cases gives the same results?

Question: I was following the tutorial here:
http://cslibrary.stanford.edu/110/BinaryTrees.html
The very first problem is to construct the following binary tree:
 2
 |  \
 1   3

My question is, why the following two main functions gives the same result. From what I understand, in the second case after the second call to the insert function, root will point to the child i.e. the node containing 1 and therefore it should create a tree which looks like
2
|
1
|
3

int main(void){
  struct node* root = NULL;
  struct node* n1;
  struct node* n2;
  root = insert(root, 2);
  n1 = insert(root, 1);
  n2 = insert(root, 3);
  print(root);
  return SUCCESS;
}

int main(void){
  struct node* root = NULL;
  struct node* n1;
  struct node* n2;
  root = insert(root, 2);
  root = insert(root, 1);
  root = insert(root, 3);
  print(root);
  return SUCCESS;
}

struct node* insert(struct node* node, int data){
  if(node == NULL){return newnode(data);}
  else{
    if(data < node->data){node->left = insert(node->left, data);}
    else{node->right = insert(node->right, data);}
    return node;
  }
}

Comment: This comment made me think, I was assuming that the insert function always returns the new node but I was wrong. It returns the new node only when the root node is Null otherwise it returns the new node. Haven't dealt with recursion in a while. Thanks guys.
Comment: Have you tried to [debug your small program](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/)?
Comment: Hi, My question was more of a conceptual one. `struct node* build123c() {
  struct node* root = NULL;
  root = insert(root, 2);
  root = insert(root, 1);
  root = insert(root, 3);
  return(root);
}` This is a code from stanford's website(link provided in the question). I don't completely understand why this is correct.
Comment: My comment was trying to guide you down the path of, if you want to know why two bits of code are different, break into the debugger at the start of each, step through each line, and see where / why they diverge or do not diverge.
Comment: Conceptually, what is your `insert` function supposed to return? The new node inserted? Or the current root node?
Answer: For these statements
root = insert(root, 2);
root = insert(root, 1);
root = insert(root, 3);

root continues to point to the same node after the first non-null node pointer is returned from insert.
For your expectation to be true, insert would have to be defined as something like
struct node* insert(struct node* node, int data){
    if (node == NULL) {
        return newnode(data);

    } else {
        if (data < node->data) {
            return ( node->left = insert(node->left, data) );
        } else {
            return ( node->right = insert(node->right, data) );
        }
    }
}

But it is not defined that way. (And the tree wouldn't work correctly if it was.) I think the function is simpler than you are making it in your head.
Each node pointer is only returned a single level. When you call insert(root, ...), the return value is either the return value of newnode or root.
Answer: If you want to get the left of the node, then return the left of the node, not the node itself.
If you want to get the right of the node, then return the right of the node, not the node itself.


Save XML adding space in blank fields

Question: So I'm trying to learn how to modify XML files with PowerShell but am encountering a weird issue, where PowerShell adds blank space to my XML files after saving them.
Say I have an xml file called test.xml that looks like:
<employee>
    <person>
        <name>John Doe</name>
        <id></id>
    </person>
</employee>

I wrote this PowerShell script to change the name:
$file1 = ".\test.xml"
$file2 = ".\test_new.xml"
$xml = New-Object XML
$xml.Load($file1)
$xml.employee.person.name = "John Smith"
$xml.Save($file2)

So far, so good. However, the output file is formatted like this:
<employee>
    <person>
        <name>John Smith</name>
        <id>
       </id>
    </person>
</employee>

This is a problem, because I am trying to use similar code to update an XML file with a schema that restricts including spaces in blank fields. This makes it unreadable after modification.
Anyone know what I'm doing wrong here?
Answer: This appears to work for me:
$file1 = ".\test.xml"
$file2 = ".\test_new.xml"

# Remove old variable to ensure new instance
Remove-Variable xml -ea SilentlyContinue

# Create new empty xmldoc
$xml = New-Object XML

# Set preserve whitespace before load
$xml.PreserveWhiteSpace = $true
$xml.Load($file1)

$xml.employee.person.name = "John Smith"

#Set it again before save
$xml.PreserveWhiteSpace = $true
$xml.Save($file2)

Comment: I get this error: `Out-File : A parameter cannot be found that matches parameter name 'Path'.` If I remove the -Path parameter it works, but the output file is not XML and just shows the employee object.
Comment: The joy of powershell argument inconsistencies.
Comment: Completely rewrote it after reading the craziness that is `PreserveWhiteSpace`
Comment: preservewhitespace was the answer!
Answer: Another option is to use a command from the PowerShell Community Extensions called Format-Xml e.g.:
...
$xml.employee.person.name = "John Smith"
$xml | Format-Xml > $file2

Save XML adding space in blank fields


How to create a BigQuery View using REST request

Question: I've tried building and sending the REST request using the Google Tables: insert page with the following (sanitised) values:
Request parameters
projectId:prj-name
datasetId:dataset_name

Request body
{
  "view": {
    "useLegacySql": false,
    "query": "SELECT * FROM `prj-name.dataset_name.hello_world`"
  },
  "type": "VIEW",
  "tableReference": {
    "projectId": "prj-name",
    "datasetId": "dataset_name",
    "tableId": "v_hello_world"
  }
}

This post suggests these parameters should work, but Google returns the following response:
{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "invalid",
    "message": "Output field used as input"
   }
  ],
  "code": 400,
  "message": "Output field used as input"
 }
}

I've experimented with the REST properties and I think the 400 issue is caused by the inclusion of the tableReference property.  But if I exclude it I get the following alternative error:
{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Required parameter is missing"
   }
  ],
  "code": 400,
  "message": "Required parameter is missing"
 }
}

It's a shame that the "Required parameter" is not named in this error message!
I can use this code method to create the view but that code method throws an exception when patching views.
Help is appreciated.  I'd rather not have to maintain two different ways of managing views in my code.
Thanks.
Answer: Remove "type": "VIEW", from your request.
That's not an input parameter. It's an output field from the response.
https://cloud.google.com/bigquery/docs/reference/rest/v2/tables#resource
Comment: Thanks!  I should have spotted that one.


A user-friendly, fast way to delete the same field from several content types at once?

Question: I have a Drupal 7.39 site with about 10 content types. All of these content types contains 2 fields which I want to delete (It's a long story why).
Is there a way to delete both of these fields from all content types at once, instead of manually deleting each one of them from each content-type? Thanks,
Comment: To be honest, I don't quite believe that deleting fields (and thus losing data) should be either friendly or fast to do, especially in bulk.
Answer: You can execute this code manually
<code>field_delete_field('your_field_machine_name');
</code>
Comment: @Umair, you can use function field_delete_instance, but I don't think that title field can be deleted. Actually, it's not classic field. It's system field.
Comment: I'm a humble JS student and I've yet to acquire enough knowledge to know how to implement this. Where do I execute this code and how? (Maybe via Drush?), Can you please elaborate more via updating your answer?, Thanks,
Comment: The simpliest way to do it, is install module devel, open page devel/php and execute this code there.
Comment: DOMAIN/devel/php is url of page. On this page you can execute your PHP code. This page available only if you have enabled module devel.
Comment: @Eugene What if I want to delete a field of a certain content type? For example title field
Answer: Field tools

A collection of useful UI tools for working with fields:

Overview of fields with links to edit single instances, and all    instances at once
Visual overview of relationships between entity types defined by    entityreference fields, taxonomy reference fields, and schema
  properties, using GraphAPI
Clone any field instance to multiple entities and bundles
Clone all field instance of a bundle to multiple entities and bundles
Import and export fields
Delete multiple instances of a field
Apply a vocabulary to multiple entities and bundles at once (the same    way vocabularies were applied to content types on Drupal 6)
... your idea here. Patches welcome!
Comment: I've installed the module - Can you please add a small update on where to go to delete the fields just to "Save time for all users to come"? Not critical but will be nice I guess.
Comment: T could see an option to clone or to delete the field from a single content type but not a "delete from all" button. Can you please elaborate on how to do the deletion of a field from all content types? Thanks,


Comparing Strings in Pandas dataframe in elif fashion

Question: I am trying to compare strings in a dataframe with the specific caveat that if one of the strings already equals "Missing" that value will be carried over.
For instance if my df looks like
df =pd.DataFrame({'Col1':['Dog','Cat','Missing'],
      'Col2':['Dog', 'Monkey', 'Rat']})

and I asked if Col1 is in Col2 the results would be
True, False, Missing

The following code allows the comparison of values per row (providing me with "true" and "false" values), but I have been struggling with how to incorporate the check for "Missing"
df['result'] = df.apply(lambda row: row[Col1] in row[Col2], axis=1)

Perhaps I should abandon the notion of using a lambda function in this case and switch over to a if/elif/ statement such as in this pseudocode:
if df[df[Col1]] == "Missing":
     df['result'] = 'Missing'
elif df[df[Col1]] in df[df[Col2]]:
    df['result'] = 'True'
else:
    df['result'] = 'False'

I appreciate any help you can provide.
Answer: I think you can use double numpy.where:
mask1 = df['Col1'] == 'Missing'
mask2 = df.apply(lambda row: row['Col1'] in row['Col2'], axis=1)

df['result'] = np.where(mask1, 'Missing',
               np.where(mask2, 'True', 'False'))

print (df)
      Col1    Col2   result
0      Dog     Dog     True
1      Cat  Monkey    False
2  Missing     Rat  Missing


Copy only the input folder files whose names match value from JSON or CSV file

Question: Input:

a folder containing LOTS of files (with a complex file hierarchy)
a JSON/CSV file containing filenames

Output:

a new folder containing files copied from input folder and matching filenames in CSV/JSON file

I kind of have a limited knowledge of batch/sed/awk, so any idea/suggestion is welcome.
Thank you!
Comment: Suggestions or should we write your code for you? http://whathaveyoutried.com
Comment: Can you show an example of the JSON file's contents please?
Comment: bash/sed/awk is probably the wrong choice for JSON parsing
Answer: As mentioned in the comments above, bash/sed/awk is the not ideal for parsing JSON. Since you've hinted that CSV is an option, I'd say that's your best bet.
Since I don't know if this is an assignment and you've yet to mention what you've attempted, I'll refrain from writing a full script for you. Instead, here's a quick run-through of the core bits which will hopefully help you forward.
And since you've did not provide an example input file, I'm going to make one up. Say you have an input CSV file as such:
$ cat in.csv
john,hello/world/domination.txt,10
ruth,some_file.txt,20
sarah,jessica/parker.jpg,80

Looping through contents of the CSV file
The simplest way would be to use a while loop and read:
$ while IFS=',' read -r NAME FILENAME AGE; do echo "$FILENAME"; done < in.csv
hello/world/domination.txt
some_file.txt
jessica/parker.jpg
in/my documents/empty.file

Note that we've temporarily changed IFS (internal file separator) to a comma to split the input CSV lines into fields.
The copy command
Assuming that in your script you have a base path (your "... folder containing LOTS of files (with a complex file hierarchy)") and a destination directory as such:
BASE_PATH="/some/source/"
DEST_PATH="/the/destination/"

and for each filename from the CSV file -- say hello/world/domination.txt -- you want to end up copying from /some/source/hello/world/domination.txt to /the/destination/hello/world/domination.txt, then there are 3 steps involved:

Create the FROM and TO paths by appending the strings:
FROM="${BASE_PATH}/${FILENAME}"
TO="${DEST_PATH}/${FILENAME}"

Make sure that the destination directory exist. We use dirname to extract the name of the directory, and mkdir -p to recursively create directories if they do not yet exist:
mkdir -p "$(dirname $TO)"

Perform the actual copy
cp "$FROM" "$TO"

The quotes around the arguments for mkdir and cp ensure that paths with spaces are not treated as separate arguments.
Note that for brevity, I've left out error checking. In a production script you'd generally want to include checks to ensure that the source files exist and is readable, and the destination path is writeable.
putting it all together
Assuming you have already assigned BASE_PATH and DEST_PATH:
while IFS=',' read -r NAME FILENAME AGE
do
    FROM="${BASE_PATH}/${FILENAME}"
    TO="${DEST_PATH}/${FILENAME}"
    mkdir "$(dirname $TO)"
    cp "$FROM" "$TO"
done < in.csv

Comment: cut is not needed. `while IFS=',' read -r val1 val2 val3; do ...; done < in.csv`
Comment: Thanks jordanm. That's absolutely right. However, the OP has stated that he/she is new to scripting and this is my attempt at a step-by-step approach with the hope that each piece is potentially transferrable to future tasks. In this instance, it shows how the output of arbitrary commands can be iterated.
Comment: @jordanm after some thought, I've come to agree with you that the 'proper' way is likely to be more readable. Answer updated. Thanks for pointing it out.
Answer: You didn't give a whole lot for us to go on, so I will assume that

you use a CSV file
located in the root of the source directory
is formatted as file1,file2,...
that file1 is just a filename, not the full path to that file.

In that case (which is the simplest case), you can try something like
#!/bin/bash

# some renaming for easier read
srccsv="$(basename "$1")"
srcdir="$(dirname "$1")"
trgtdir="$2"

# perform the copy
set +o posix
cp <(IFS=,; \
    while read filename; do \
        find "$srcdir" -type f -name "$filename" -print0; \
    done < "$srccsv") "$trgtdir"

Then run it via
./cp_csv.sh path/to/your/csv path/to/your/targetdir

Supposing you've named this script cp_csv.sh.
Note: It's bash-specific (because of process substitution), and I didn't test this (it's very late over here..), but I don't see why this would fail.
If you're using a JSON input file, that'll be much more of a pain to parse in bash. As indicated by @jordanm, bash/sed/awk isn't the right tool for that.


Linearity Of Expectations in Bernoulli's trials

Question: I am having hard time understanding Linearity of Expectations. Here is my understanding.
$X$ is a random variable defined on Sample Space $S$ as $Pr\{X=x\}= \sum_{s \in S:X(s)=x}Pr\{s\}$
Expectation of Random variable is weighted average defined as $E[X]= \sum_{x}x.Pr\{X=x\}$.
Also, the Linearity of Expectation says, if $X$ is a random variable which is sum of other random variables such as $X_1,X_2,X_3,...X_n$ i.e.,
$X=X_1+X_2+X_3+.....+X_n$, then $$E[X]=E[X_1]+E[X_2]+E[X_3+....+E[X_n]=\sum_{i=1}^nE[X_i]$$.
Let's image we are doing a $n$-Bernoulli trial in which success probability is $p$ and failure probability is $q$ and we defined a random variable $X=$ Number of Successes where $X$ could take values $\{0,1,2,3....,n\}$.This gives $$E[X]=0.Pr\{X=0\}+1.Pr\{X=1\}+2.Pr\{X=2\}+3.Pr\{X=3\}+....+n.Pr\{X=n\}$$ I could see that $E[X]=np$ by the definition of binomial distribution formed by Bernoulli trials and applying some manipulations on it.
In the book I am reading, it is said that, instead of doing complex algebra to find the expectation, we can express X as sum of smaller random variables and apply Linearity of Expectation.Let $X_i$ is the random variable which describes number of successes in $i^{th}$ trial. It is said that $X=X_1+X_2+X_3+....+X_n$ (I don't understand why this is true).
Also, in order to find the $E[X_i]$ we are using Indicator Random Variables in which $Pr\{X=x_i\}=1.p+0.q=p$, that means $X$ can take values $0,1$.

I don't understand why a random variable which describes number of successes in all the trials is sum of successes in each trial.

Also, when we are computing original Expectation which is $E[X]$ we are working on sample space which has $2^n$ (domain of $X$) sample points, cause each trial has two possible outcomes and we have $n$ trials.

To calculate Expectation of individual random variables why did we shrink our sample space to two? I know it is due to the fact that, we are working on per trail basis but my expectation is, all the individual random variables also should be defined on original number of trails, not per trail.

If I do the math, I could get the correct value but what I lack here is intuition
Comment: The random variables $X,X_1,\dots,X_n$ are all defined on the same [probability space](https://en.wikipedia.org/wiki/Probability_space) (so there is no shrinking of our sample space, as you suggest). If that would not be the case then the expression $X=X_1+\cdots+X_n$ would have no sense at all.
Answer: For simplicity let $n=2$ and throw a coin twice.
We speak of a success if head turns up and $X$ is by definition the number of successes, so takes values in $\{0,1,2\}$.
Further define $X_1$ by stating that $X_1$ takes value $1$ if the first throw gives heads, and takes value $0$ otherwise.
Likewise define $X_2$ by stating that $X_2$ takes value $1$ if the second throw gives heads, and takes value $0$ otherwise.
Can you grasp that $X=X_1+X_2$?
If not directly then look at all $4$ different outcomes we can get:
$$\begin{array}{ccccc}
 & HH & HT & TH & TT\\
X & 2 & 1 & 1 & 0\\
X_{1} & 1 & 1 & 0 & 0\\
X_{2} & 1 & 0 & 1 & 0\\
X_{1}+X_{2} & 2 & 1 & 1 & 0
\end{array}$$

For finding e.g. the expectation of a Bernoulli random variable $B$ we only have to know the value of $P(B=1)$. The looks of the underlying sample space are irrelevant.

edit

To calculate Expectation of individual random variables why did we shrink our sample space to two?

We do not!
Let us build a model for the situation that you describe. As sample space we can use the set $\Omega:=\{0,1\}^n$. Every subset of $\Omega$ is an event and must be equipped in a suitable way with a probability. If the probability on success is $p$ then tuple $\omega=(\omega_1,\dots,\omega_n)\in\{0,1\}^n$ induces an event $\{\omega\}\subseteq\Omega$ and it is equipped with probability $p^{\sum_{i=1}^n\omega_i}(1-p)^{n-\sum_{i=1}^n\omega_i}$ to occur. So for a  subset $B\subseteq\{0,1\}^n$ we have $$P(B)=\sum_{\omega\in B}p^{\sum_{i=1}^n\omega_i}(1-p)^{n-\sum_{i=1}^n\omega_i}$$
Any function $Y:\Omega\to\mathbb R$ is a random variable.
Examples are:

function $X$ prescribed by $\omega\mapsto\sum_{i=1}^n\omega_i$
for $i=1,\dots, n$ function $X_i$ prescribed by $\omega\mapsto\omega_i$

Now observe that for every $\omega\in\Omega$ we have:$$X(\omega)=X_1(\omega)+\cdots+X_n(\omega)$$ leading to:$$\mathbb EX=\int X(\omega)P(d\omega)=\int X_1(\omega)+\cdots+X_n(\omega)P(d\omega)=\sum_{i=1}^n\int X_i(\omega)P(d\omega)=\sum_{i=1}^n\mathbb EX_i$$
Function $X$ has binomial distribution with parameters $n$ and $p$.
The functions $X_i$ are iid and have Bernoulli distribution with parameter $p$.
Comment: I can see it with examples. But, what I lack here is intuition. I tried it with3-Bernoulli trials. What I could not understand is **how is it working when we represent one random variable on n-trials as sum of Indicator Random Variables on individual trial**
Comment: I have edited my answer.
Comment: I got till summation part. Could you please explain the integration part differently? I am not well versed with integration stuff.
Comment: Integration comes in to define $\mathbb EX$. Familiar with that? Integration is linear: $\int f+gd\mu=\int fd\mu+\int gd\mu$. Familiar with that? That is all you need to know here. If not familiar then you should look it up in the math script/book that you have at your disposal.
Comment: I think I get it now. With the Random Variables you declared above, it is clear that summation of individual random variables $X_i$ equals to $X$. So, it is wrong that sample space is shrinked to 2 (S,F), we are still calculating the Expectation of individual random variables with sample space $2^n$. So, $E(X_i)=1 \times (1.1.1.......1.p) + 0 \times (1.1.1.......1.q) = p$ where $p$ and $q$ in the multiplication signifies the success and failure of trial $i$. Did I get that correct?
Comment: $X_i:\Omega\to\mathbb R$ is a function that only takes values in $\{0,1\}$. Then by definition the integral $\int X_i(\omega)P(d\omega)$ takes the value $1\times P(\{\omega\in\Omega\mid X_i(\omega)=1\})+0\times P(\{\omega\in\Omega\mid X_i(\omega)=1\})$. It can be calculated that $P(\{\omega\in\Omega\mid X_i(\omega)=1\})=p$ so we get $\mathbb EX_i=p$. This way of calculating expectation makes use of the underlying probability space. There is another way that makes use of the so-called distribution of $X_i$ wich is a propability measure on $(\mathbb R,\mathcal B)$.
Comment: According to the second way $\mathbb EX_i=\sum_{x\in S}xf(x)$ where $S$ denotes a countable support of $X_i$ and $f(x)$ denotes the probability mass function. In this case $f(1)=p$ and $f(x)=0$ for any $x\neq1$ and we also get $\mathbb EX_i=p$.


Microsoft Access 2013 Record Source Columns

Question: I recently got tasked with customizing a report in an access database, I havent touched access in years so its a little rusty for me. I have successfully added the Fields to the table, added them to the form and added them to the report. If i run the report they query correctly. But all the other fields on the report are setup with an expression such as:
=IIF([Mold Temp High]=0,"----",[Mold Temp High])
Now the expression makes 100% to me but when it auto populates the field, such as Mold Temp High, for all the previous fields i can see they show up as Record Source Column fields, but for any new field i have added shows up as a Text Box.
If i create an expression with the new fields i get a Circular Reference and it shows #type on the report instead of the value.
Just curious to why the new fields show up as TextBoxs and not Record Sources.
Answer: What if you change your logic around a bit..
We remember, IIF is constructed as:
<code>=IIF((Some_Table_Field or value),True-condition,False-condtion)
</code>
You maybe looking at:
<code>=IIF([Mold Temp High]=NULL,"----",[Mold Temp High])
</code>
Or, maybe (use ISNULL or ISBLANK it has been a while for Access with me as well):
<code>=IIF(isnull([Mold Temp High]),"----",[Mold Temp High])
</code>
Or, rather:
<code>=IIF([Mold Temp High]<1,"----",[Mold Temp High])
</code>
Hope this makes sense.
Comment: Thanks for the update, this is not really more about my expression as i know that it is correct, but more about why it pulls a text box field instead of a record source column. But i do appreciate your information.
Answer: I'm guessing that you are dragging the new fields from the field list.  When you do this, it creates the text box with the exact same name as the data field.  So when you use this name in an expression, it thinks you are referencing the text box object.  To prevent this problem, make sure that every time you create a new textbox (or any control) from a data field that you name it something different by setting the Name property of the text box.  Generally I just add "txt" to the front of the field name.  This will ensure that you are always explicitly referring to either the textbox name or the data field name.
Comment: I believe I have tried both Dragging onto the report and also creating a text box but I could be wrong. I will check this out.
Comment: I think it was a combination of me expecting the Record Source to be one way (using a query named Process Sheet Report Query) but instead having a custom SQL select statement, that wasnt pulling any changes I was making and what you proposed. Thank you! it was driving me crazy.


Como faço para Gerar Hash MD5

Question: Estamos precisando gerar um hash MD5, para passar uma senha encriptada. Alguém poderia nos dar um exemplo?
Comment: Eu não entendo de Java então não tenho como responder. Mas preciso deixar isso aqui: **MD5 não é uma forma de encriptação**. Se você quer "passar" uma senha e precisa do MD5 para que ela não seja vista, você tem duas falhas de segurança graves na mão.
Answer: tenta rodar essa classe de exemplo:
<code> public class DigestTest extends MainWindow
{
   private Edit edtInput;
   private ComboBox cboDigests;
   private Button btnGo;
   private ListBox lboResults;
   private Object[] comboItems;

   public DigestTest()
   {
      super("Digest Test", TAB_ONLY_BORDER);

      try
      {
         comboItems = new Object[] {new MD5Digest(), new SHA1Digest(), new SHA256Digest()};
      }
      catch (NoSuchAlgorithmException e)
      {
         e.printStackTrace();
      }
   }

   public void initUI()
   {
      edtInput = new Edit();
      edtInput.setText("0123456789ABCDEF");
      cboDigests = new ComboBox(comboItems);
      cboDigests.setSelectedIndex(0);
      btnGo = new Button("Go!");
      lboResults = new ListBox();
      lboResults.enableHorizontalScroll();

      add(edtInput, LEFT + 2, TOP + 2, FILL - (btnGo.getPreferredWidth() + cboDigests.getPreferredWidth() + 6), PREFERRED);
      add(cboDigests, AFTER + 2, SAME, PREFERRED, PREFERRED);
      add(btnGo, AFTER + 2, SAME, PREFERRED, PREFERRED);
      add(lboResults, LEFT + 2, AFTER + 2, FILL - 2, FILL - 2);
   }

   public void onEvent(Event e)
   {
      switch (e.type)
      {
         case ControlEvent.PRESSED:
            if (e.target == btnGo)
            {
               Digest alg = (Digest)cboDigests.getSelectedItem();
               String message = edtInput.getText();

               alg.reset();
               alg.update(message.getBytes());
               byte[] digest = alg.getDigest();

               lboResults.add("Message: " + message);
               lboResults.add("Digest: " + Convert.bytesToHexString(digest) + " (" + digest.length + " bytes)");
               lboResults.add("=========================");
               lboResults.repaintNow();
            }
            break;
      }
   }
}
</code>
Comment: Obrigado Bruno, funcionou perfeitamente...
Answer: De uma olhada no código abaixo:
<code>public static String toMD5(byte[] bytes){

    MessageDigest md = null;

    try {
        md = MessageDigest.getInstance("MD5");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    md.update(bytes);

    BigInteger hash = new BigInteger(1, md.digest());

    return hash.toString(16);
}
</code>
Até mais.

Como faço para Gerar Hash MD5


Center All Elements to a Certain Width

Question: I'm trying to get everything to center and to about 80% of the page. Everything seems fine, except for my two main divs extend over my banner and nav bar by about 1px, even though they are set to 80%.
Here is the CSS: https://pastebin.com/HM7PLqX0

body {
  background: url('bg.png');
  background-size: cover;
  background-repeat: none;
}

.banner {
  font-family: 'Raleway', sans-serif;
  color: #f2f2f2;
  margin-top: 20px;
  text-align: center;
  background: url('bg.jpg') no-repeat;
  background-size: cover;
  background-position: center;
  line-height: 120px;
  font-size: 40px;
  text-shadow: 2px 2px 2px black;
  width: 80%;
  height: 120px;
  margin: 0 auto;
}

.about {
  background-color: #333;
  opacity: 0.8;
  display: inline-block;
  vertical-align: top;
  text-align: center;
  width: 60%;
  height: 300px;
  font-family: 'Raleway', sans-serif;
  color: white;
}

.stats {
  background-color: #333;
  opacity: 0.8;
  display: inline-block;
  vertical-align: top;
  text-align: center;
  width: 20%;
  height: 300px;
  font-family: 'Raleway', sans-serif;
  color: white;
}

.logo {
  margin-top: 50px;
  font-family: myFirstFont;
  color: white;
  text-align: center;
  font-size: 50px;
}

.topnav {
  background-color: #333;
  overflow: hidden;
  width: 80%;
  margin: 0 auto;
}

  The Realm MC

     Home

     Play

     Forums

     Donate

  There are 7 out of 10 players online!

    Lorem ipsum
 dolor sit amet

    Lorem ipsum
 dolor sit amet

Answer: You haven't mention any with for wrapper div, therefore it is assigned 100% of the width available and div inside it will take width accordingly.
Try reducing the width of about div to 59% as shown below, this will make both divs lie inside 80% of width scope :
.about {
  background-color: #333;
  opacity: 0.8;
  display: inline-block;
  vertical-align: top;
  text-align: center;
  width: 59%;
  height: 300px;
  font-family: 'Raleway', sans-serif;
  color: white;
}

Here is the fiddle for that : https://jsfiddle.net/rp1shr4t/
or you can set width of wrapper div as you have done topnav div and then set width of inner divs accordingly.
Answer: This seems working fine.

body{
  background: url('bg.png');
  background-size: cover;
  background-repeat: none;
}

.banner {
  font-family: 'Raleway', sans-serif;
  color: #f2f2f2;
  margin-top: 20px;
  text-align: center;
  background: url('bg.jpg') no-repeat;
  background-size: cover;
  background-position: center;
  line-height: 120px;
  font-size: 40px;
  text-shadow: 2px 2px 2px black;
  width: 80%;
  height:120px;
  margin: 0 auto;
}

.about {
  background-color: #333;
  opacity: 0.8;
  display: inline-block;
  vertical-align: top;
  text-align: center;
  width: 60%;
  height: 300px;
  font-family: 'Raleway', sans-serif;
  color: white;
}
.stats {
  background-color: #333;
  opacity: 0.8;
  display: inline-block;
  vertical-align: top;
  text-align: center;
  width: 20%;
  height: 300px;
  font-family: 'Raleway', sans-serif;
  color: white;
}

.logo {
  margin-top: 50px;
  font-family: myFirstFont;
  color: white;
  text-align: center;
  font-size: 50px;

}

.topnav {
  background-color: #333;
  overflow: hidden;
  width: 80%;
  margin: 0 auto;
}

The Realm MC

  Home
  Play
  Forums
  Donate

    There are <?php echo $ServerStatus['numplayers'] . " out of " . $ServerStatus['maxplayers'] . " players online!"; ?>

    Lorem ipsum

    dolor sit amet

    Lorem ipsum

    dolor sit amet

Answer:
You must assign a width:80% for wrapper.
use of float property instead of display:inline-block.

So,Change Like this :
#wrapper {
    width: 80%;/*/<-------------------/*/
    margin: 0 auto;/*/<-------------------/*/
    box-sizing: border-box;/*/<-------------------/*/
}

.about {
  background-color: #333;
  opacity: 0.8;
  vertical-align: top;
  text-align: center;
  width: 70%;/*/<-------------------/*/
  height: 300px;
  font-family: 'Raleway', sans-serif;
  color: white;
  float: left;/*/<-------------------/*/
  /*/-------Remove display:inline-block-----------/*/
}

.stats {
  background-color: #333;
  opacity: 0.8;
  vertical-align: top;
  text-align: center;
  width: 29%;/*/<---------1% for margin-left ----------/*/
  height: 300px;
  font-family: 'Raleway', sans-serif;
  color: white;
  float: right;/*/<-------------------/*/
   /*/-------Remove display:inline-block-----------/*/
}

This is Demo

Center All Elements to a Certain Width


Find all records with same join column data

Question: I have these tables:
Project

id
name
version

1
Swam
0.0.1

2
Dinali
0.0.1

3
Dinali
0.0.2

4
BigR
0.0.3

5
Kale
0.0.1

6
Kale
0.0.2

Person

id
name

1
Jake

2
Skye

3
Kieth

4
Jim

5
Eliz

6
Haun

Person_Project

id
person_id
project_id

1
1
1

2
2
1

3
2
2

4
3
1

5
3
2

6
4
1

7
4
4

8
5
1

9
6
1

10
6
2

11
6
3

I want to find all the persons who are working on same projects exact match. From the above data, result should be persons 1 and 5 because they both working on project 1, persons 2 and 3 because they are working on same projects 1 and 2.
Should not return 4 and 6 as there are no other persons working exact projects they are working on.
Answer: This can be optimized.
2x subquery, 1x window function
SELECT person_id
FROM  (
   SELECT person_id, count(*) OVER (PARTITION BY projects) AS match_ct
   FROM  (
      SELECT person_id, array_agg(project_id) AS projects
      FROM   person_project
      GROUP  BY 1
      ) sub1
   ) sub2
WHERE  match_ct > 1;

1x CTE, 1x EXISTS
WITH cte AS (
   SELECT person_id, array_agg(project_id) AS projects
   FROM   person_project
   GROUP  BY 1
   )
SELECT person_id
FROM   cte c1
WHERE  EXISTS (
   SELECT FROM cte c2
   WHERE  c2.projects = c1.projects
   AND    c2.person_id <> c1.person_id
   );

In addition, array_agg() should be faster that string_agg() (also avoiding the cast).
For large numbers of persons and/or projects, it should pay to create a temporary table instead of the CTE, add an index on (hash_array(projects), person_id), and compare the hash values.
For very large sets, use hash_array_extended(projects, 0) to practically rule out hash collisions.
Related:

Why doesn't my UNIQUE constraint trigger?
Answer: Query:

 with projects as
  (
   select person_id, STRING_AGG (project_id::varchar,' , ' order by project_id ) project_ids from Person_Project
   group by Person_id
  )
  ,cte as
   (select project_ids from projects group by project_ids having count(*)>1)
  select person_id from projects where project_ids in (select project_ids from cte)

OUtput:

person_id

1

2

3

5

fiddle
Comment: thank you. Sorry I was not clear, i do not want to which person match to which person. Just list of person ids which have exact match projects to some other persons. OutPut will persion_id/1 2 3 5
Comment: @user09 Please check my modified answer.
Comment: thank you. this is exactly what I was looking for. other solution helps to figure out what matches to what
Comment: You are most welcome. Best wishes.


iphone snow falling effect

Question: i have been following
apps
snowfall tutorial, but i am getting some issue in iOS 5, something like this

(source: appsamuck.com)
-
 (void)onAnimationComplete:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {

    UIImageView *flakeView = context;

****this is where the issue is: implicit conversion of a non objective c pointer type 'void *' to 'UIimageview' is disallowed when using ARC
Please suggest, how can I solve this problem.
Regards
Comment: I'd highly recommend replacing the above code with UIView's blocks-based implementation of animations, because that eliminates the need to pass in a bridged value for the context. As I comment below, the straight bridging opens you up to potential crashes if the context object is deallocated before the callback is triggered.
Comment: use `UIImageView *flakeView = (__bridge UIImageView *)context;`. Not an answer because I can't explain why ^^
Comment: Hello Shishir, did you intend to attach an additional image to your posting?  The "[enter image description here]" bit gives it away.  :-)
Comment: sry for the formating. i was trying to attach my screenshot of my code.let me try again
Comment: @flunchtpunkt that worked. cool. i have one more place, where i am getting the same thing."//UIImageView* flakeView = [[UIImageView alloc] initWithImage:flakeImage];" how should i convert this?[UIView beginAnimations:nil context:flakeView];
Answer: Expanding on @fluchtpunkt 's comment which should really have been an answer ;)
ARC works by determining, at compile time, if the objects are needed or not - it then works out your retain/release for you.
If you pass an object as (void *) the compiler cannot work out that it has to retain this object so it might get released before you use it.
The __bridge explicitly tells the compiler that you are passing a 'real' object but using a void * to do it.
However, there might be a risk of a memory leak if you don't tell the compiler somewhere else that you are done with the object :)
Take a look at http://developer.apple.com/library/ios/#releasenotes/ObjectiveC/RN-TransitioningToARC/index.html and search for '_bridge' to see more details.
Comment: In this case, I don't know if it's a leak I'd be worried about, but a crash if the bridged object went away before it was used by the callback. The straight bridge won't cause it to be retained by the callback, so it could be deallocated at some point in the meantime.
Comment: THen use `__bridge_retain` instead - that article is dull but useful ;)

iphone snow falling effect


Is $p\in B(\mathbb{C}^4)$ a s.o.t-limit of a sequence $(a_n\otimes b_n)_{n\in\mathbb{N}}\subseteq B(\mathbb{C}^2)\otimes B(\mathbb{C}^2)$?

Question: Let $L(H)$ the bounded linear operators on a hilbert space $H$. I proved that the inclusion $$i:B(\mathbb{C}^2)\otimes B(\mathbb{C}^2)\hookrightarrow B(\mathbb{C}^4)$$ is not surjective: take $p=\begin{pmatrix} 1 & 0 & 0 &0 \\ 0 & 1 & 0 &0 \\ 0 & 0 & 1 &0 \\ 0 & 0 & 0 &0 \end{pmatrix}\in M_4(\mathbb{C})\cong B(\mathbb{C}^4)$, then it is'nt possible to write $p=a\otimes b$ with $a,b\in B(\mathbb{C}^2)$. My question is now: Is $p$ a strong operator topology limit of a sequence $(a_n\otimes b_n)_{n\in\mathbb{N}}\subseteq B(\mathbb{C}^2)\otimes B(\mathbb{C}^2)$? I.e. is there a sequence  $(a_n\otimes b_n)_{n\in\mathbb{N}}\subseteq B(\mathbb{C}^2)\otimes B(\mathbb{C}^2)$ such that $\|(a_n\otimes b_n -p)x\|_{\mathbb{C}^4}\to  0,\; n\to\infty$ for all $x\in \mathbb{C}^4$?
I think the answer is yes. I tired to find matrices $a$ and $b$ such that $\begin{bmatrix}
    a_{1,1} & a_{1,2} \\
    a_{2,1} & a_{2,2} \\
  \end{bmatrix}
\otimes
  \begin{bmatrix}
    b_{1,1} & b_{1,2} \\
    b_{2,1} & b_{2,2} \\
  \end{bmatrix}
=
  \begin{bmatrix}
    a_{1,1} b_{1,1} & a_{1,1} b_{1,2} & a_{1,2} b_{1,1} & a_{1,2} b_{1,2} \\
    a_{1,1} b_{2,1} & a_{1,1} b_{2,2} & a_{1,2} b_{2,1} & a_{1,2} b_{2,2} \\
    a_{2,1} b_{1,1} & a_{2,1} b_{1,2} & a_{2,2} b_{1,1} & a_{2,2} b_{1,2} \\
    a_{2,1} b_{2,1} & a_{2,1} b_{2,2} & a_{2,2} b_{2,1} & a_{2,2} b_{2,2} \\
  \end{bmatrix}$ converges to $p$ in the strong operator topology. I don't have found suitable matrices not yet. Do you have an idea?
Answer: The inclusion $i$ is surjective, because both $B(\mathbb C^2)\otimes B(\mathbb C^2)$ and $B(\mathbb C^4)$ have the same dimension (concretely, 16).
The issue, and what you showed, is that if you restrict $i$ to the subset of elementary tensors, then $i$ is not surjective.
Your element $p$ is not a sot limit of elementary tensors. For starters, because we are in a finite-dimensional setting, the sot topology agrees with the norm topology. And since a norm-limit of elementary tensors is again an elementary tensor, elements that are not elementary tensors cannot be realized as limits of elementary tensors.


Chain rule and x =cos(θ) substitution on the Legendre ODE

Question: I am having difficulties with a question where I am required to use the chain rule, and then use the substitution x = cos(θ), on the Legendre differential equation, which is
$$(1-x^2)y'' - 2xy' + l(l+1)y = 0.$$
The resultant expression should be
$$\frac1{\sin\theta} \frac{\mathrm d}{\mathrm d\theta} \left(\sin\theta \frac{\mathrm d}{\mathrm d\theta} P_n(\cos\theta)\right) + l(l+1) P_n(\cos\theta) = 0.$$
However, I am unsure of how to get from the first equation to the second, even with the instructions given.
I have attempted to solve the problem, with steps such as the substitution of cosθ, but I am having trouble going from there. The substitution (as I see it) yields:
$$sin^2θy'' - 2cosθy' + l(l+1)y = 0.$$
although I am not even sure if this step happens before or after any use of the chain rule.
Many thanks.
EDIT: I have come across the follwing information from another website, but I do not understand how they have moved between their two uses of the chain rule. They have:
"$$(1−x^2)P′′_n(x)−2xP′_n(x)+n(n+1)P_n(x)=0.     (11)$$
The linear second-order differential equation (11) is called Legendre's differential equation and as seen Pn(x) satisfies (11). This is why Pn(x) is called a Legendre polynomial.
In physics (11) is often expressed in terms of differentiation with respect to θ. Let x=cosθ. Then by the chain rule,
$${dP_n(cosθ) \over dθ}=−sinθ*{dP_n(x) \over dx}      ,    (12)$$
$${d^2P_n(cosθ) \over dθ^2}=−x{dP_n(x) \over dx}+(1−x^2){d^2P_n(x) \over dx^2}, (13)$$.
Using (12) and (13), Legendre's differential equation (11) can be written as
$${1 \over sinθ}{d \over dθ}\left(sinθ{dP_n(cosθ) \over dθ}\right)+n(n+1)P_n(cosθ)=0$$.              "
How did they do this?
Comment: Any help at all would be great, thanks
Answer: $$\begin{align}
y'&=\frac{dy}{dx}=\frac{dy}{d\theta}\frac{d\theta}{dx}=\frac{dy}{d\theta}\frac{1}{dx/d\theta}=-\frac{1}{\sin\theta}\frac{dy}{d\theta},\\
y''&=\frac{1}{\sin\theta}\frac{d}{d\theta}\Bigl(\frac{1}{\sin\theta}\frac{dy}{d\theta}\Bigr).
\end{align}
$$
Comment: This is a great help, thanks. Could you possibly elaborate a little further with regards to the resultant expression that I should get? i.e. How it links the expressions together?
Comment: When I put these back into the equation, what happens when I have -2cos(theta)*((1/sin(theta))*(dy/d(theta)))? Also, how do I convert the 1/sin(theta) within the differential to sin(theta) as it is in the required expression? Thanks


sum certain columns of 2 tables matching criteria sql

Question: Table1 data:
ACType Dualhr P1hr Total
A320     2     2    4
B787     1     2    3
B777     3     1    4

Table2 data:
ACType P1hr Total

A320    5     5

on comparing the 2 tables,what sql query will give me result:
ACType Dualhr P1hr Total
A320     2     7     9
B787     1     2     3
B777     3     1     4

which should also factor case when Table1 is empty,so to give result:
ACType Dualhr P1hr Total
A320     0      5    5

Comment: Start with UNION, and see how you get on
Comment: Why do b787 and b777 drop out of your second result example?
Comment: @p.salmon because table1 is empty
Answer: Use union and subquery:
select ACType, sum(Dualhr) as Dualhr, sum(P1hr) as P1hr,sum(Total) as Total
from
(
select ACType, Dualhr, P1hr, Total from table1
union all
select ACType, 0, P1hr, Total from table2)a
group by ACType

Comment: which case those are, explain and if this answer helps you then please accept this
Comment: Thanks. In some cases,  Table2 may not have few columns that are present in Table1. For eg here, P1hr is present..in other case, only Dualhr is present.  columns are lesser in number in Table2 than Table1...in actual ptogram, I have 14 columns in Table1 and 7 in Table2...So at one time all 7 columns will not be filled in Table2
Comment: what if the query has " select ACType, Dualhr, P1hr, Total from table2" ?
Comment: your table2 does not have Dualhr column
Comment: so columns not being used in table2 will be referred by 0 in the query?
Comment: yes that is the way to show columns which are not present in table


Implement select for update for hypertable query language

Question: I am asked to implement select for update in HQL in python. I haven't tried anything because I don't have a good idea how I am going to go about it.
As select for update fetches rows after we disable autocommit and there by achieve locking on particular rows in the table until we commit and enable autocommit , it seems to me a bit doubtful to achieve in hypertable.
How could I lock a few rows in Hypertable?
For now I have a table like
CREATE TABLE foo (
  c1,
  c2,
  ACCESS GROUP default (c1, c2)
);

select * from foo;
001 c1  a
001 c2  b

I am still beginning to learn hypertable .
Some help will be appreciated.
Answer: Hypertable does not support transactions and does not have any locking or read-modify-write operations.  However, if you're just trying to implement a simple update, you can just set the MAX_VERSIONS 1 option on the columns as follows:

CREATE TABLE foo (
  c1 MAX_VERSIONS 1,
  c2 MAX_VERSIONS 1,
  ACCESS GROUP default (c1, c2)
);

Then each time you insert, it will either 1) replace the old value, or 2) insert the new value if it doesn't already exist.
Comment: I was asked to handle and store parsed data in a table . So before inserting or updating I need to check whether its a duplicate and other things. So if rows are read simultaneously then there would be a problem as one of them would update them to parsed while the other would also fetch the same rows and update them again to parsed with different data.


Removing rows until a metric point is reached and extracting the minimum value

Question: I'am classifying some text using a Machine learning model. Essentially I am fitting 80% of the data to the model and predicting the remaining 20%. On top of this, for each classification, I am outputting a confidence level as given by the ML model and and a check variable, which is set to TRUE if the prediction is correct and FALSE otherwise.
The data frame output I get from the process above looks like this:
+----------------------+
|  confidence   Check  |
+----------------------+
|  1            TRUE   |
|  0.72         TRUE   |
|  0.68         TRUE   |
|  1            TRUE   |
|  0.150287157  FALSE  |
|  1            TRUE   |
|  0.7          TRUE   |
|  0.68         TRUE   |
|  1            TRUE   |
|  0.903333333  FALSE  |
+----------------------+

I would like to know what the minimum confidence level is that approximates 95% accuracy the closest in the data set. E.g, If I remove enough rows with FALSE Values, starting with the rows which have the lowest confidence levels and are FALSE, what is the minimum confidence level in the data set which is reached?
I compute accuracy as the number of rows which are TRUE divided by the the total number of rows in the data frame.
How can I do this?
Comment: How do you calculate the minimum level of confidence?
Comment: I don't calculate it. I just retrieve it from the resulting data frame. So its, essentially, the minimum value of the dataframe that produces 95% accurancy. I currently have a visual build in PowerBI to do this, but I need it in Python as its part of a bigger process I am automating.
Comment: @smici, Perhaps I did not explained it correctly, but the answer is not to just reorder the dataframe, its not that simple. I will try to rephrase my question better and the output I want to get. I any case, thanks for your help!
Comment: @Pythonista: I provided the solution first. See my third and final hint. After you find the number of the row n, then you can pick your cutoff confidence threshold as any number between `df.iloc[n-1].confidence` ... `df.iloc[n].confidence`
Comment: @smci, thank you very much. But you are computing the mean value of the confidence? I am looking for the minimum confidence which approximates 95% accuracy by removing FALSES from the dataset. accuracy is computes as total rows TRUE divided by total amount of rows
Comment: No, I've been telling you I'm computing exactly what you're asking for: the confidence as total rows TRUE divided by total amount of rows (i.e. first filter/remove rows with `iloc[n:]`, then `df.iloc[n:].Check.mean()`. The code works and was working 5 hours ago. Run it first before you tell me it's wrong.
Comment: @smci thanks for your answer! I've ran your code multiple times and it does what I want indeed. I just got confused with the .mean(), but I now noticed its the same as counting true and dividing my the total amount of rows. I will mark your answer as accepted.
Answer: Here is the solution:

read your dataframe in (code below), treating Check column as int (rather than boolean), and sort in order of increasing confidence.
now look at the values as you sweep your confidence threshold over rows:
[ round(df.iloc[n:].Check.mean(), 3) for n in range(len(df.index))] which gives [0.8, 0.889, 0.875, 0.857, 0.833, 0.8, 1.0, 1.0, 1.0, 1.0]
after you find the number of the cutoff row n, then df.iloc[n].confidence gives you a cutoff confidence value which gives >= 0.95 accuracy. Hence you can pick your cutoff confidence threshold as any number between df.iloc[n-1].confidence  ... df.iloc[n].confidence

Code:
import pandas as pd

dat = """confidence   Check
1            TRUE
0.72         TRUE
0.68         TRUE
1            TRUE
0.150287157  FALSE
1            TRUE
0.7          TRUE
0.68         TRUE
1            TRUE
0.903333333  FALSE"""

df = pd.read_csv(pd.compat.StringIO(dat), header=0, delim_whitespace=True, dtype={'confidence':'float', 'Check':'int'})
df.sort_values(by='confidence', inplace=True)

df

   confidence  Check
4    0.150287      0
2    0.680000      1
7    0.680000      1
6    0.700000      1
1    0.720000      1
9    0.903333      0
0    1.000000      1
3    1.000000      1
5    1.000000      1
8    1.000000      1

# Sweep over the df, finding the cutoff row which gives us 0.95 confidence...
for n in range(len(df.index)):
    if df.iloc[n:].Check.mean() >= 0.95:
        break

# ...then find the range for the cutoff confidence level
print("Cutoff confidence level is between:", df.iloc[n-1].confidence, df.iloc[n].confidence)

# Cutoff confidence level is between: 0.903333333 1.0

Comment: smci, thanks for your answer! However, this is exactly where I am stuck at the moment. So I've sorted the values, but now I want to remove "0" (as in your example) until I reach a 95% accuracy level ( e.g. 1/(1+0) ) and check what the minimum confidence level is. BTW, It was not me who down voted your answer.
Comment: Second hint:  look at `[ round(df.iloc[n:].Check.mean(), 3) for n in range(len(df.index))]` as you sweep `n`, which gives `[0.8, 0.889, 0.875, 0.857, 0.833, 0.8, 1.0, 1.0, 1.0, 1.0]`
Comment: Third hint: after you find the number of the row n, then `df.iloc[n].confidence` gives you a cutoff confidence value which gives >= 0.95 accuracy. Hence you can pick your cutoff confidence threshold as any number between `df.iloc[n-1].confidence`  ... `df.iloc[n].confidence`
Comment: Fourth hint: if you want to exclude rows with df.Check==False then increasing values of confidence, then change it to `df.sort_values(by=['Check','confidence'], ...)`
Answer: Use:
import math
accuracy=0.95
#df=df.replace('TRUE',True).replace('FALSE',False)

#contains the number of True an the number of False
total_True=df['Check'][df['Check']].sum()
total_false=len(df)-total_True
#Calculate the num of false max to this precision and total_true
n_false_max=math.floor(total_True/(accuracy)-total_True)

#Order the DataFrame to drop the number of False excluding
df_sorted=df.sort_values(['Check','confidence']).reset_index(drop=True)
print(df_sorted)
#Select the min level of confident
if n_false_max==0:
        print('95% accuracy is not possible')
        accuracy_remove1=total_True/(total_True+1)
        print('Accuracy with remove all False except one: ',accuracy_remove1*100)

        if (1-precision)<(precision-accuracy_remove1):
            nearest_accuracy=100
            print('nearest Accuracy 100%')
        else:
            nearest_accuracy=accuracy_remove1*100
            print('Nearest Acuracy: ',nearest_accuracy )
            min_level_of_confident=df_sorted.iloc[(total_false-1):].iloc[0].confidence
            print('Min Confident level associated:',min_level_of_confident)

elif total_false==0:
    print('for every level of trust is over 95%')
else:
    min_level_of_confident=df_sorted.iloc[(total_false-n_false_max):].iloc[0].confidence
    print(min_level_of_confident)

Output
   confidence  Check
0    0.150287  False
1    0.903333  False
2    0.680000   True
3    0.680000   True
4    0.700000   True
5    0.720000   True
6    1.000000   True
7    1.000000   True
8    1.000000   True
9    1.000000   True
95% accuracy is not possible
Accuracy with remove all False except one:  88.88888888888889
nearest Accuracy 100%

Comment: I don't understand what you mean exactly
Comment: this is awesome! the only thing is that its a hard coded 95% accuracy, would it be possible to get an approximation? If I would get 0.9545 or 0.9432 is also fine, I just need the minimum confidence level that gets me the closest to 95% accuracy.
Comment: My apologies for not specifying it clearly, but I need to know what the minimum confidence level is that approximates 0.95 accuracy level by removing FALSES which have lowest confidence until that minimum confidence level is reached. So having "95% accuracy is not possible" is not a possibility.
Comment: in the case of the example, it is only possible to reach such a level of precision if all False ones are eliminated. That's why resilvi with a print. Now I have added the precision obtained by eliminating all false ones except one and the level of confidence associated
Comment: @ansev, Its almost there, however, I need the confidence level which approximates 0.95 accuracy the most, even if its at at 0.85 accuracy. So the accuracy level is actually variable approximating 0.95 accuracy the most
Comment: You cannot get accuracy levels between 88% and 95% (removing False) in this example... the only way is to increase the number of True
Comment: Do you want I add True values?
Comment: that is to say if it eliminates all the FALSE the result is 100% accuracy. If the eliminated all but 1 the accuracy is 88%. Therefore the only way to get closer to 95% is to add True. I think he answered more than clearly his question
Comment: @ansev, then in this example, the closest answer approximating 95% is 100% as its closer to 95% than 88%, but the important thing is that is should be the closest approximation derived from the analysis


Drupal 6 administration menu like the one on Drupal 7

Question: I build a lot of sites, mostly on Drupal 7, so when I have to use Drupal 6 I am totally lost on the admin options, (even using the administrative menu bar).
Since I can't find any module for this issue, I am wondering if I should give it a try to build a module myself to rename and rearrange the admin menu items, but I am not sure, if this is even possible or if that will cause any path issues in modules later.
Comment: If you should give a try building a module depends from your skills on building a module. Creating a module is always extra work, and you [commented](http://drupal.stackexchange.com/questions/27621/d6-admin-menu-like-d7#comment26783_27628) saying you want to avoid that. This probably rules out creating a module. For the first point, this question is subjective: The answer is "it depends from your skills on writing a module," and nobody but you knows your skills in writing a module.
Answer: Why not building your own menu with the most used functions and show it only for you? I do this all the time for D6 and D7.
Comment: Well as I mentioned I build a lot of sites, that means I am user 1 for all of them, and also I want to save time, not creating extra work... I also want the clients to have some of the admin links, but like D7


PowerMockito mockStatic gives MissingMethodInvocationException

Question: I am trying to mockStatic method using PowerMockito , where I tried some options to mockStatic for a class, resulting in different exceptions.
@RunWith(PowerMockRunner.class)
@PrepareForTest({Base64.class})
public class BqClientFactoryTest {
    @Test
    public void testGetBigQueryClient() throws Exception {
        mockStatic(Base64.class);
        Base64.Decoder mockDecoder = mock(Base64.Decoder.class);
        when(Base64.getDecoder()).thenReturn(mockDecoder);

This resulted in org.mockito.exceptions.misusing.MissingMethodInvocationException:
I used another example like this
@RunWith(PowerMockRunner.class)
@PrepareForTest({Base64.class})
public class BqClientFactoryTest {
    @Test
    public void testGetBigQueryClient() throws Exception {
        mockStatic(Base64.class);
        Base64.Decoder mockDecoder = mock(Base64.Decoder.class);
        doReturn(mockDecoder).when(Base64.class, "getDecoder");

which gives me
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:

If I use
BDDMockito.given(Base64.getDecoder()).willReturn(mockDecoder);

from Mocking static methods with Mockito , it still returns org.mockito.exceptions.misusing.MissingMethodInvocationException
I tried to check similar questions on SO, they haven't seemed to help.
Any help resolving this is appreciated.
Answer: I solved it following this, all other solutions didn't work for me. It is difficult to search for this solution, since there are too many on SO on the same.
PowerMockito mock single static method and return object inside another static method , PowerMock, mock a static method, THEN call real methods on all other statics
@RunWith(PowerMockRunner.class)
@PrepareForTest({Base64.class})
public class BqClientFactoryTest {
    @Test
    public void testGetBigQueryClient() throws Exception {
        Base64.Decoder mockDecoder = mock(Base64.Decoder.class);
        stub(method(Base64.class, "getDecoder")).toReturn(mockDecoder);

Comment: Since I have found this solution now, not sure what is the right thing to do, since it seems a duplicate. But difficult to find in so many questions and answers on SO on the same topic. This one adding to it.


How can I prove why I chose the point to lie on a parabola?

Question: I have a problem: Let $A$ and $B$ be two points that lie on the parabola $y=x^2 + 3x - 4$, where $x \in [-3,3]$. Find the greatest value of the segment $AB$.
Here is what I tried: Suppose $B=(3,14)$ and $A=(a, a^2 +3a - 4)$. We have
$$AB^2 = a^4+6 a^3+46 a^2+102 a+333.$$
From here, I have maximum of $AB^2$ is appr. 1296.
How can I prove why I chose the point $B$ to lie on the parabola like that?
Comment: Wouldn't the end point of the parabola in the given interval give the maximum length of chord ?
Comment: Not  true. For example, the parabola of $x^2$ on interval $[-3,3]$ then $(-3,9)$ and $(3,9)$ are distance $6$ apart, but $(0,0)$ is distance at least $9$ from $(-3,9)$. @Shashaank
Comment: @ThomasAndrews Yes I realize ! I did not just think at all.
Comment: BTW, I get $a^4+6a^3-26a^2-114a+333$.
Comment: And this distance between $AB$ can't be close to $36$ because the minimum value for $a^2+3a-4$  is $-25/4$ and thus the maximum distance squared can't be more than the distance squared to $(-3,-25/4)$, which is: $(3-(-3))^2+(14+25/4)^2\approx 21.12^2$.
Answer: Write it as $y=f(x)=\left(x+3/2\right)^2 - \frac{25}{4}$.
This means that $f(x)=f(-3-x)$. We have to take care with this symmetry, because $x$ and $-3-x$ are both in $[-3,3]$ if any only if $x\in[-3,0]$.
Assume $-3\leq a\leq b\leq 3$.
Now, if $b\leq\frac{-3}{2}$, then the distance between $(a,f(a))$ and $(b,f(b))$ is the same as the distance between $(a',f(a'))$ and $(b',f(b'))$, with $a'=-3 -b, b'=-3-a$, and we still have $a',b'\in[-3,3]$ and $a'<b'$, but with $b'\geq \frac{-3}{2}$.
So we can assume that $b\geq\frac{-3}{2}$.
If $f(a)> f(b)$, then show that you can start with $b'=-3-a, a'=-3-b$. This is the tricky one. if $f(a)>f(b)$ and $a<b$ and $b\geq -3/2$, then $a$ must be further from $-3/2$ than $b$ is. But $a$ must be at most $3/2$ less than $-3/2$, so $-3-a$ is still in $[-3,3]$, and the same is true for $-3-b$.
This means we can assume $f(a)\leq f(b)$. But then, since $b\geq-3/2$, increasing $b$ increases both $|f(b)-f(a)|$ and $|b-a|$, and hence the distance, so you can assume $b=3$.

This might seem complicated, but "visually" it is fairly simple.
If you draw the graph of the function, then it is symmetric in the interval $[-3,0]$ with center $-3/2$.
So you can assume both points are not in the $[-3,3/2]$ range. Likewise, if both points are in the $[-3,0]$ range, with $a\leq -3/2 \leq b\leq 0$, you can apply the symmetry to assume that $f(a)\leq f(b)$.
Also, if $b>0$ and$-3\leq a\leq b$ then $f(a)\leq f(b)$, because $b$ is further from $-3/2$ than $a$ is.
But if $f(a)\leq f(b)$ and $a<b$ and $b\geq -3/2$, then increasing $b$ increases the distance, so the maximum distance must occur when $b=3$.

By the way, the same argument also means that $a\leq -3/2$ - because the distance is clearly increasing as $a$ moves from $3$ to $-3/2$.


Como alterar o código de contribuição para registros duplicados

Question: Tenho uma consulta que me retorna 04 linhas duplicadas; preciso alterar os códigos da contribuição para que não ocorra erro de Pk.
<code>nm_Matricula    Mes_Ano_Referencia  Mes_Ano_Competencia Cod_Contribuicao    DT_pagamento
    32665107            102001             102001               11          2001-10-18
    32665107            102001             102001               11          2001-10-19
    32665107            102001             102001               11          2001-10-22
    32665107            102001             102001               11          2001-10-23

 nm_Matricula   Mes_Ano_Referencia  Mes_Ano_Competencia Cod_Contribuicao    DT_pagamento
    32665107            102001             102001               257         2001-10-18
    32665107            102001             102001               258         2001-10-19
    32665107            102001             102001               259         2001-10-22
    32665107            102001             102001               260         2001-10-23
</code>
Comment: Poderia postar sua query e formatar melhor a resposta? Para retornar dados não duplicado user o DISTINCT.
Comment: @CidineiaOkamoto: Qual é o gerenciador de banco de dados? // Observe que as linhas não estão duplicadas, pois diferem na coluna DT_pagamento. // Qual é a regra para alterar valores na coluna Cod_Contribuicao? Isto é, como 11 virou 257,.., 260.
Comment: Estou uitlizando sqlserver 2014, a coluna dt_pagamento eu só inclui para fazer a ordenação.. os campos que preciso fazer o Insert são apenas os nm_Matricula    Mes_Ano_Referencia  Mes_Ano_Competencia Cod_Contribuicao,
Comment: @CidineiaOkamoto: Qual é a regra para alterar valores na coluna Cod_Contribuicao? Isto é, como Cod_Contribuicao=11 virou 257, 258, 259 e 260? // Na tabela de destino, quais colunas fazem parte da chave primária?
Comment: Primeira contribuição 257, segunda 258 e assim sucessivamente..A chave da tabela q recebera esses registros é: nm_Matricula   Mes_Ano_Referencia  Mes_Ano_Competencia Cod_Contribuicao
Answer: Considerando-se que o valor da coluna Cod_Contribuicao deve ser renumerado para cada matrícula, ordenado pela data de pagamento, eis esboço do código.
<code>-- código #1 v3
with cteRecod as (
SELECT nm_Matricula, Mes_Ano_Referencia, Mes_Ano_Competencia,
       reCod_Contribuicao= 256 + row_number() over (partition by nm_Matricula order by DT_pagamento asc)
  from tbOrigem
  -- where ...
)
INSERT into tbDestino (colunas)
  SELECT nm_Matricula, Mes_Ano_Referencia, Mes_Ano_Competencia, reCod_Contribuicao
    from cteRecod;
</code>
Substitua tbOrigem e tbDestino pelos nomes das tabelas.
No comando com a instrução INSERT, substitua colunas pelos nomes das colunas na tabela de destino, na mesma sequência do SELECT.
Se for necessário restringir a leitura da tabela de origem, utilize a cláusula WHERE em cteRecod.
Comment: Jose.. Perfeito.. muito obrigada


Why multiple testing matters?

Question: I am learning multiple testing and I am curious about why it matters?
I understand the mathematics behind the multiple testing problems, for example, I understand things like $\text{FWER} \le m \alpha$, where $\text{FWER}$ refers to family-wise error rates, $m$ refers to hypotheses numbers, and $\alpha$ refers to significance level. However, I don't understand the statistical ideas behind the multiple testing problems and I don't know why it matters.
Let me elaborate on that. A common example about the consequence of multiple testing is that consider a study where we have $10,000$ hypotheses, we test each of them separately on a $0.05$ significance level and reject all of the null hypotheses which we reject in its own test. Even all of the $10,000$ null hypotheses are correct, we will reject $500$ hypotheses and make $500$ Type-$1$ errors in expectation ($0.05 \times 10,000$). The literature (e.g. Chapter 13, Introduction to Statistical Learning with R, Tibshirani et al.) uses this example to argue the multiple testing matters. I think the literature implicitly assumes that making $500$ Type-$1$ errors are bad to make this argument valid.
Let us consider another example. Consider $10,000$ independent researchers testing their own hypothesis and publishing the positive results. Formally, each of the researchers is totally independent from others, i.e. they work on different projects, have different hypotheses, do different experiments. Assume all researchers are honest, they propose their null hypothesis before the experiment, test their hypothesis with $0.05$ significance level, and publish their result if and only if the test rejects the null hypothesis. If all of the null hypotheses are correct, then there will be $500$ false rejections ($0.05 \times 10,000$), i.e. $500$ Type-$1$ errors, in expectation. Then we will see $500$ false positive papers.
It seems like there is no difference between the first example and the second example. They have the same assumptions (all $10,000$ null hypotheses are correct) and they have the same results (there will be $500$ Type-$1$ errors). However, I think the second example is exactly how the science community works: independent researchers do their own research and publish the positive result. It seems like nothing goes wrong in the second example. Then why the first example is bad while the second example is not bad? What is the difference between the two examples?
Comment: @ChristianHennig The problem of 500 published studies describing a positive effect which is either not there or is substantially overstated, when the other 19500 studies are never published, is a major contributor to "reproducibility crisis" even when there is no bad practice by the researchers involved.  It is "selective reporting" by the system even when it is not by the individual
Comment: The second example is still bad, see the current "reproducibility crisis" in psychology and other fields. The difference is in the fact that the badness in the first example can be addressed much more easily, because the one researcher with 10,000 hypotheses can address the multiple testing problem far more easily than 10,000 researchers can coordinate *their* multiple testing problem.
Comment: @StephanKolassa I don't think that the second example properly describes what leads to the "reproducibility crisis". For sure "hunting for significance", i.e., selective reporting and hidden multiple testing, issues with data quality and model assumptions, and even fraud play a role there.
Comment: @ChristianHennig: I would not presume to explain the reproducibility crisis in a single comment, and I am sure that the points you raise are very impotant (cf. Gelman's "garden of forking paths"). Nevertheless, I would say that the huge number of possible hypotheses also has an impact (again Gelman, this time "researcher degrees of freedom"). It's hard to disentangle where one problem ends and the next one starts - especially since the null hypothesis is *never* true. Sometimes statistics frustrates me.
Comment: Can you please write out abbreviations and define notation? Terminology is not always used in a unified matter, people don't know all the same books, and you can't assume that people know what ISLR is.
Comment: @ChristianHennig Thanks for the suggestion, I edit the question to explain the abbreviations and notations. Your suggestion is really helpful.
Answer: This is an interesting question, and I've thought about this as well. My current thinking is this: Hypothesis testing has to be seen within a wider research context. Generally testing a hypothesis cannot ultimately settle a scientific problem of interest. For sure 5% type I error probability is worryingly high if decisions are made and scientific statements are taken for granted based on significances alone that can have serious consequences for society or be it individual patients. There are also many other issues with significance tests (such as that tests with sufficiently large samples easily turn out significant, and this is theoretically even "correct", if the null hypothesis is not precisely true but effects are so small that they don't matter, or are at least over-interpreted based on a small p-value).
Given all this, the difference between the two situations in my view is this. One should hope (and check!) that the "independent researchers" test hypotheses that are of real substantial interest, backed op by background information and thorough subject matter considerations. A hypothesis test should never be the only "information" based on which something is claimed; even using the very same data, effect sizes and potential violations of model assumptions, problems with data quality etc. should be addressed, and even then it should be clear that, say, $p=0.035$ isn't that strong an indication that anything meaningful is going on. Ultimately one can say that these specific data don't provide evidence against the null hypothesis, or they do, weaker or stronger (indeed keeping in mind that there are thousands of scientific papers with tests published every month if not week, and that a certain number of "false significances" is to be expected), with additional careful interpretation of all further results of data analysis.
In a single study in which 10,000 hypotheses are tested, chances are that other than running the tests there isn't much further background and detailed analysis for every single test. Also chances are that significant or "most significant" results will be selectively reported, which means that the probability that something is reported as meaningful that in fact isn't is far higher than the significance level. So I indeed believe that multiple testing adjustments are more appropriate in this situation than in a situation where more thorough analysis is done and more information is taken into account. Apart from this, one can of course generally discuss the pros and cons of significance testing in all of these situations.

Why multiple testing matters?


Prove that if $X$ is Hausdorff, $\Delta$ is closed in $X\times X$

Question: Prove that if $X$ is Hausdorff, $\Delta=\{(x, x)\mid x\in X\}$ is closed in $X\times X$ (with the product topology).
My attempt:
Let $x_1, x_2\in X$ s.t. $x_1\ne x_2$.
There exist neighborhoods $U_1$ and $U_2$ of $x_1$ and $x_2$ that are disjoint.
$U_1\times U_2$ is a basis element in the product topology on $X\times X$. So, $U_1\times U_2$ is open in $X\times X$.
Let $x\in X$.
$(x, x)\in U_1\times U_2\implies x\in U_1$ and $x\in U_2\implies x\in U_1\cap U_2$, which contradicts the fact that $U_1$ and $U_2$ are disjoint.
So, $(x, x)\notin U_1\times U_2$.
I feel that I'm on the right track but don't know how to proceed. Could someone please help me out?
Comment: That's fine: each point of the complement of $\Delta$ is contained in an open set within that complement, so the complement is open....
Answer: You're basically there, you just need to interpret your result. You found that for any point $(x_1,x_2)\in X\times X-\Delta$, there exists a neighborhood of $(x_1,x_2)$ contained in $X\times X-\Delta$. That is, $X\times X-\Delta$ is open. Therefore $\Delta$ is...
Answer: Your work shows that
$$
\Delta^c=\bigcup_{\substack{(x_1,x_2)\in X\times X\\x_1\neq x_2}} U_1(x_1)\times U_2(x_2),
$$
where $U_1(x_1)$ and $U_2(x_2)$ are separating sets for $x_1,x_2$. This shows the complement of $\Delta$ is a union of open sets, so the complement of $\Delta$ is open, so $\Delta$ is closed.
Answer: Let $(x, y)\in X\times X-\Delta$
$\implies(x, y)\in X\times X$ and $(x, y)\notin\Delta$
$\implies x, y\in X\text{ and }x\ne y$
There exist neighborhoods $U_x$ and $U_y$ of $x$ and $y$ respectively that are disjoint.
$U_x\times U_y$ is a basis element in the product topology on $X\times X$.
$(x, y)\in U_x\times U_y$ --------------------------------------------- (1)
Let $(u, v)\in U_x\times U_y$. --------------------------------------------- (2)
$\implies u\in U_x$ and $v\in U_y$
Since $U_x\subset X$ and $U_y\subset X$,
$u, v\in X$
$\implies(u, v)\in X\times X$ --------------------------------------------- (3)
$u=v\implies u=v\in U_x\cap U_y$, a contradiction as $U_x$ and $U_y$ are disjoint.
So, $u\ne v$.
$\implies(u, v)\notin\Delta$ --------------------------------------------- (4)
From (3) and (4),
$(u, v)\in X\times X-\Delta$ --------------------------------------------- (5)
From (2) and (5),
$U_x\times U_y\subset X\times X-\Delta$ --------------------------------------------- (6)
Combining (1) and (6),
$(x, y)\in U_x\times U_y\subset X\times X-\Delta$
So, $X\times X-\Delta$ is open in $X\times X$.
So, $\Delta$ is closed in $X\times X$.
QED


In how many ways can $12$ people be seated at a square table if $90^\circ$ rotations are considered to be equivalent?

Question: Say for instance we are give a table as follows, with the condition that if you were to rotate the table 90 degrees it would still be considered the same.
\begin{bmatrix}&A&B&C&\\L&&&&D\\K&&&&E\\J&&&&F\\&I&H&G\end{bmatrix}
Q1) How  many ways can 12 be seated, under this specified condition?
My answer) 3 cases to consider. Someone sits next to the Right of A. Someone sits to the Left of A. A sits between 2 people. Therefore $3*11!$
Q2) How many different seating are possible with A and B must be sitting next to each other?
My answer) A and B must be sitting with each other, however due to 90/180/270 degree turns that eliminates three options. 3*11! - 27*10!
Q3) How many different seating are possible with A and B must NOT be sitting next to each other.
My answer) 3 cases to consider. Someone sits next to the Right of A. Someone sits to the Left of A. A sits between 3 people. We have 9 positions where people can be seated with 3 cases to follow, therefore $9*10! + 9*10! + 9*10! = 27*10!$
Q4) What is the probability that a seating arrangement chosen at random will have A and B not sitting next to each other?
My answer) We know # of people who cannot sit together and total seating arrangements, therefore 27*10! / 3*11!
Ultimately, I'd like to know if logic in Q1 and Q3 is sound, as it would let me answer Q2/Q4 very easily.
Answer:
How many ways can $12$ people be seated at a square table if $90^\circ$ rotations are considered to be equivalent?

Your answer is correct.
Method 1:  When viewed from the opposite side of the table, person A is either in the left, middle, or right seat.  There are $11!$ to seat the other eleven people as we proceed clockwise around the table relative to $A$, which yields
$3 \cdot 11!$ possible seating arrangements.
Method 2:  There are $12!$ ways of seating $12$ people in order.  Since $90^\circ$ rotations of seating arrangements are considered to be equivalent, we must divide by $4$, which yields
$$\frac{12!}{4} = \frac{12 \cdot 11!}{4} = 3 \cdot 11!$$

How many ways can the $12$ people be seated at a square table if A and B sit in adjacent seats if $90^\circ$ rotations are considered to be equivalent?

We first seat person A.  When viewed from the opposite side of the table, person A is either in the left, middle, or right seat.  Person B can be seated to the immediate left or immediate right of A.  The remaining $10$ people can be seated in $10!$ ways as we move clockwise around the table relative to the block of two seats now occupied by persons A and B.  Hence, there are $3 \cdot 2 \cdot 10!$ seating arrangements in which A and B sit in adjacent seats.

How many ways can the $12$ people be seated at a square table if $A$ and $B$ do not sit in adjacent seats if $90^\circ$ rotations are considered to be equivalent?

Subtract the number of ways they can sit in adjacent seats from the total number of seating arrangements.

What is the probability that a seating arrangement chosen at random will have A and B not sitting next to each other if $90^\circ$ rotations are considered to be equivalent?

Divide the preceding result by the total number of seating arrangements, which is equivalent to $1$ minus the probability that they are sitting next to each other.


Acesso à biblioteca DLL feita em Delphi a partir do Java

Question: Estou desenvolvendo uma ferramenta para reconhecimento biométrico usando o SDK fornecido em formato DLL, desenvolvido em Delphi. Para o acesso à DLL a partir do Java, estou usando JNA.
O template da digital (a parte mais importante) é um objeto que se refere a este trecho (em Delphi):
type
  CIS_Digital = packed record
    intSize: integer;
    pDigital: Pointer
  end;

pCIS_Digital = ^CIS_Digital;

Como desenvolver algo equivalente em Java?

Basicamente, preciso chamar as seguintes funções da DLL:
SDK_CIS_Iniciar(int cnpj, int detectaFake);
SDK_CIS_LerDigital(pCIS_Digital digital);
SDK_CIS_CompararDigital(pCIS_Digital amostra1, pCIS_Digital amostra2);
SDK_CIS_Finalizar();

Olhando o exemplo fornecido, desenvolvido em Delphi, vi que o objeto pCIS_Digital, que é passado nas funções SDK_CIS_LerDigital() e SDK_CIS_CompararDigital(), é do tipo (type) declarado no trecho de código mais acima.
No mesmo exemplo, antes de chamar o método SDK_CIS_LerDigital(), o objeto pCIS_Digital é instanciado e vai vazio onde então é "preenchido" através da função.
O leitor é o Techmag BioFlex, que é baseado nos leitores Futronic (FS-80).
Pesquisando, vi que o objeto pCIS_Digital (do trecho de código), faz acesso à memória para ler as informações que o leitor grava nela escreve.
Depois de muitas pesquisa, acho que devo desenvolver algum objeto equivalente em Java, estendendo das classes Structure ou Memory, do JNA.

Atualização: Informações sobre meu código
Leio e armazeno duas vezes a minha digital utilizando o método SDK_CIS_LerDigital, depois comparo as duas utilizando o método SDK_CIS_CompararDigital, que sempre retorna 0 (comando não executado).
"Printei" os objetos intSize e pDigital após ler a digital, intSize retorna 0 e pDigital retorna null.
Interface com os métodos da DLL:
public interface SDK_CIS extends StdCallLibrary {

static SDK_CIS INSTANCE = (SDK_CIS) Native.loadLibrary("SDK_CIS", SDK_CIS.class);

    public String SDK_CIS_Versao();

    public String SDK_CIS_Retorno(int resposta);

    public int SDK_CIS_Iniciar(long cnpj, int fake);

    public int SDK_CIS_Finalizar();

    public int SDK_CIS_LerDigital(CIS_Digital.ByReference digital);

    public int SDK_CIS_CancelarLeitura();

    public int SDK_CIS_CompararDigital(CIS_Digital.ByReference pAmostra1, CIS_Digital.ByReference pAmostra2);
}

Classe que estende Structure, referente ao objeto CIS_Digital:
public class CIS_Digital extends Structure {

    public static class ByReference extends CIS_Digital implements Structure.ByReference {}

    public int intSize;
    public Pointer pDigital;

    @Override
    protected List<String> getFieldOrder() {
        return Arrays.asList("intSize", "pDigital");
    }
}

Método responsável por ler duas vezes qualquer digital e compará-las:
public void leEcomparaDigitais() {

        SDK_CIS leitor = SDK_CIS.INSTANCE;

        try {
            // TROQUEI MEU CNPJ POR ZEROS, PARA NÃO EXPOR MINHA LICENÇA
            leitor.SDK_CIS_Iniciar(Long.parseLong("00000000000000"), 0);

            CIS_Digital.ByReference amostra1 = new CIS_Digital.ByReference();

            leitor.SDK_CIS_LerDigital(amostra1);

            try {
                // AGUARDA 1 SEGUNDO PARA LER PELA SEGUNDA VEZ
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            CIS_Digital.ByReference amostra2 = new CIS_Digital.ByReference();

            leitor.SDK_CIS_LerDigital(amostra2);

            int resp = leitor.SDK_CIS_CompararDigital(amostra1, amostra2);

            // EXIBE RESPOSTA
            // 0 -> COMANDO NAO EXECUTADO
            // 1 -> COMANDO EXECUTADO COM SUCESSO
            System.out.println(resp);

        } finally {
            leitor.SDK_CIS_Finalizar();
        }
    }

Comment: Favor, verifique o resultado da função `leitor.SDK_CIS_LerDigital(amostra1);`. O problema pode estar na leitura e você não está verificando o retorno
Comment: Uma sugestão um pouco diferente, você poderia fazer uma interface c/c++ com a dll e implementar os métodos em Java usando JNI. Java+Delphi usando JNI: http://www.linhadecodigo.com.br/artigo/747/jni-interacao-java-e-outras-linguagens.aspx; Delphi DLL e c++: https://sergworks.wordpress.com/2013/12/13/consuming-delphi-interfaces-in-dephi-and-c/; JNI: https://www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html.
Comment: Olá! Chamei o método SDK_CIS_Versao e o mesmo imprime a versão do SDK (2014.001.02.1404).
Comment: Esta é a primeira vez que trabalho com acesso à DLLs. Não faço ideia sobre qual é a calling convention da dll SDK_CIS. Irei pesquisar a respeito. Obrigado mais uma vez.
Comment: Numa rápida pesquisa, localizei a seguinte informação:

Based on the Pascal programming language's calling convention, the parameters are pushed on the stack in left-to-right order (opposite of cdecl), and the callee is responsible for balancing the stack before return.

This calling convention was common in the following 16-bit APIs: OS/2 1.x, Microsoft Windows 3.x, and Borland Delphi version 1.x. Modern versions of the Windows API use stdcall, which still has the callee restoring the stack as in the Pascal convention, but the parameters are now pushed right to left.
Comment: LerDigital retona 1. (1 = comando executado com sucesso).
Comment: `amostra1.intSize` retorna sempre 0?
Comment: Sim, @EProgrammerNotFound. intSize sempre 0 e pDigital sempre null. =(
Comment: Você possui uma versão em Delphi desse sistema que está funcionando?
Comment: Possuo sim, @EProgrammerNotFound. Com o fonte e tudo mais.
Comment: tenta correr isso em jar no delphi( programas o pretendido em java e no delphi chamas um jar.
Comment: Eu vi esse post aqui no SOF em inglês, mas o código da resposta tá em português. Talvez você possa chegar à pessoa que respondeu por meio do chat: http://stackoverflow.com/questions/30945826/function-mapping-delphi-dll-with-java-jna
Comment: A DLL é 32 ou 64 bits? Qual a versão do java que você pretende utilizar (exemplo: 1.7 32bits, 1.8 64bits) ? Se precisar recompilar a DLL (em Delphi), você pode alterar o código-fonte dela?
Comment: pelo que sei deves chamar o jar no delphi, esse jar deve gerar-te um output depois é so partir a string
Answer: Isso pode se tratar de um erro devido a calling convention das funções na DLL.
Assumindo que você tenha o código fonte original da DLL em Delphi, você pode alterar a calling convention das funções incluindo a cláusula stdcall no final da definição, por exemplo:
function foobar( x: Integer ): Integer; stdcall;

Espero que seja útil!


If numbers $1$, $2$, $\ldots$, $20$ are arranged in a circle in any order, there must be three close numbers whose sum is at least $32$.

Question: We are required to use contradiction to prove that:

If the numbers $1, 2, ..., 20$ are arranged in a circle regardless of order, that there must be $3$ close numbers whose sum is at least $32$.

If we list the numbers, say in a clockwise direction starting at any arbitrary number say, $k_1$ upto $k_{20}$ we look at the total sum as being
\begin{equation*}
\begin{aligned}
  (k_1 + k_2 + k_3) + (k_2 + k_3 + k_4) + (k_3 + k_4 + k_5) + ... + (k_{19} + k_{20} + k_1) + (k_{20} + k_1 + k_2)
\end{aligned}
\end{equation*}
Here, we realise that every number from 1 to 20 appears atleast 3 times in the above big sum. So the big sum is literally $3(1 + 2 + 3 + ... + 20)$
We know however that the total sum of values from $1$ to $20$ can be achieved by using the formula
\begin{equation*}
\begin{aligned}
  \sum_{k=1}^{n} k &= \frac{n(n + 1)}{2} \\
         &= \frac{20(20 + 1)}{2} \\
         &= 210
\end{aligned}
\end{equation*}
Right now am stuck at this point. How to prove that there will be $3$ numbers that have a sum lesser than $32$.
My thinking is that if i join up the three biggest numbers, namely $18 + 19 + 20$, I will end up with $57$. But then how do I prove it with contradiction in this induction question?
Comment: So, the sum of $1$ to $20$ is $\sum\limits_{k=1}^n k = 210$, so the total sum of the above $(k_1+k_2+k_3)+(k_2+k_3+k_4)+\dots+(k_{20}+k_1+k_2)$ is $630$.  The average value of each parenthetical expression is then $\frac{630}{20}$, or $31.5$.  Can you continue from there?
Comment: As an aside, induction does not appear to be useful in any proof for this result.  This is a straightforward proof by contradiction and/or pigeonholing
Comment: "at least 3 times" means the sum is,**at minimum** 3(1+\dots+20)$. But it is "exactly three times," so you can say it is equal to.
Comment: Also, "How to prove that there will be 3 numbers that have a sum lesser than 32?" is the wrong question. You want to show that there are 3 numbers that have a sum $\geq 32.$
Comment: Am having problem trying to understand the problem to solve it in a proof by induction manner, coz i realized where am heading is trying to make the problem harder than it seems
Comment: Induction is for establishing theorems of the form $\forall k \in \mathbb N \dots$.  This problem isn't like that, in fact, it is finite.  There are only $20!$ cases to check.  So the best thing for this type of problem is to try to build a counter example and see why that doesn't work.
Answer: I am assuming that by 'three close numbers' you mean a triplet of adjacent numbers in some permutation (following from what you gave in the details of your question).
I am not very sure about where you can use induction effectively here. But if you do look at the problem from a pigeonhole principle point of view, the answer is fairly straightforward and you're actually almost there, you're just looking at the wrong question. What you should try to prove is that there will always be a triplet where the sum is at least 32; of course there have to triplets where the sum is less than 32 as well.
Just notice that the sum you calculated, which equals $210$, appears exactly thrice when you take the sum across all triplets of interest; and there are exactly 20 of these in any rearrangement in a circle as you've already figured out. Then it follows immediately that
$$\frac{3}{20}\sum_{i=1}^{20}i=31.5, $$ which implies that if the sums for all triplets of interest were less than 32, they would be at most 31, which gives a contradiction because the sums cannot match; it is strictly less in case this were true.
Answer: Induction is not useful in such kind of problem, as noticed by J. Moravitz to prove that let observe
$$\sum k_i = 210 \implies 3\frac{\sum k_i}{20}=31.5$$
therefore there exists some triple which sum is greater than that value.


Downgrading php from 5.4.9 to 5.3.3 on CentOS 6.3 w/ PDO and MySQL

Question: I'm running CentOS 6.3. My objective is to downgrade php from 5.4.9 to 5.3.3, with PDO support (for Magento). Magento isn't working. Furthermore, phpmyadmin isn't working because it complains the mysqli extension isn't installed.
Here's my phpinfo
http://188.8.131.52/phpinfo.php
Magento error message:
http://126.96.36.199/errors/report.php?id=1018227680846&skin=default
installed so far with yum:
[root@server etc]# rpm -qa | grep php
php-frameworks-1.0.3-1.noarch
php-cli-5.3.3-22.el6.x86_64
php-pdo-5.3.3-22.el6.x86_64
php-common-5.3.3-22.el6.x86_64
php-5.3.3-22.el6.x86_64

phpmysql error message
    http://22.214.171.124/vps/mysql_admin/index.php
Here's what I get when I try to install php-mysql
>root@server etc]# yum install php-mysql
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirror.itc.virginia.edu
 * epel: mirror.umd.edu
 * extras: mirror.liberty.edu
 * updates: mirror.umd.edu
Setting up Install Process
Resolving Dependencies
--> Running transaction check
---> Package php-mysql.x86_64 0:5.3.3-22.el6 will be installed
--> Processing Dependency: libmysqlclient.so.16(libmysqlclient_16)(64bit) for package: php-mysql-5.3.3-22.el6.x86_64
--> Processing Dependency: libmysqlclient.so.16()(64bit) for package: php-mysql-5.3.3-22.el6.x86_64
--> Finished Dependency Resolution
Error: Package: php-mysql-5.3.3-22.el6.x86_64 (base)
           Requires: libmysqlclient.so.16()(64bit)
           Available: MySQL-shared-5.1.63-1.glibc23.x86_64 (servergrove-rhel-6)
               libmysqlclient.so.16()(64bit)
           Available: mysql-libs-5.1.66-2.el6_3.x86_64 (base)
               libmysqlclient.so.16()(64bit)
           Available: mysql-libs-5.1.67-1.el6_3.x86_64 (updates)
               libmysqlclient.so.16()(64bit)
Error: Package: php-mysql-5.3.3-22.el6.x86_64 (base)
           Requires: libmysqlclient.so.16(libmysqlclient_16)(64bit)
           Available: MySQL-shared-5.1.63-1.glibc23.x86_64 (servergrove-rhel-6)
               libmysqlclient.so.16(libmysqlclient_16)(64bit)
           Available: mysql-libs-5.1.66-2.el6_3.x86_64 (base)
               libmysqlclient.so.16(libmysqlclient_16)(64bit)
           Available: mysql-libs-5.1.67-1.el6_3.x86_64 (updates)
               libmysqlclient.so.16(libmysqlclient_16)(64bit)
 You could try using --skip-broken to work around the problem
 You could try running: rpm -Va --nofiles --nodigest

I'm sure I'm making a simple mistake...any ideas? Thanks in advance.
Answer: Get rid of the conflicting third-party servergrove repository which is blocking your installation. (Not to mention probably causing all sorts of other trouble.)
Comment: your answer led me down the right path--fixed. thanks a ton.


how do you sort Radiobox column in c# wpf datagrid, as i want checked(Preferred) data record display on top?

Question: As WPF is not sorting Radiobox column. Can someone help?
Here is my code that display records.
XAML:
<code>    <DataGrid x:Name="DG_VendorPur" AutoGenerateColumns="False" ItemsSource="{Binding VendorProducts}" Grid.Row="7" Grid.RowSpan="4" FontFamily="Franklin Gothic Medium" FontSize="18" Background="#FFEBDCEB" AlternatingRowBackground="#FFDAE7F5" SelectionMode="Single" ColumnWidth="*" Grid.Column="5" Grid.ColumnSpan="6" SelectedCellsChanged="DG_VendorPur_SelectedCellsChanged">
                    <DataGrid.Columns>
                        <DataGridTemplateColumn Header="Preferred" Width="90">
                            <DataGridTemplateColumn.CellTemplate>
                                <DataTemplate>
                                    <RadioButton x:Name="DG_isPreferred" HorizontalAlignment="Center" GroupName="Preferred" IsChecked="{Binding Path=VP_isVendorActive, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" MaxWidth="25" />
                                </DataTemplate>
                            </DataGridTemplateColumn.CellTemplate>
                        </DataGridTemplateColumn>
                        <DataGridTextColumn     x:Name="DG_Vname"       Header=" Vendor Name "  MinWidth="50" Width="*" Binding="{Binding Path=VP_Vname}"       FontFamily="Calibri" />
                        <DataGridTextColumn     x:Name="DG_VItemNo"     Header=" Vendor SKU# "  MinWidth="50" Width="*" Binding="{Binding Path=VP_VendorSKU}"   FontFamily="Calibri"/>
                        <DataGridTextColumn     x:Name="DG_VCaseCost"   Header=" Case Cost "    MinWidth="50" Width="100" Binding="{Binding Path=VP_SKUcaseCost}" FontFamily="Calibri"/>
                        <DataGridTextColumn     x:Name="DG_VQtyPerCase" Header=" Qty/Case "     MinWidth="50" Width="100" Binding="{Binding Path=VP_QtyInCase}"   FontFamily="Calibri"/>
                    </DataGrid.Columns>
                </DataGrid>
</code>
XAML.CS :
<code>    sqliteCon.Open();
                string Product = TB_PscanID.Text;
                cmd.CommandText = "Select VP_Vname,VP_VendorSKU,VP_SKUcaseCost,VP_QtyInCase,VP_isVendorActive from VendorProducts where VP_ProductID= @WORD";
                cmd.Parameters.AddWithValue("@word", Product);
                cmd.Prepare();
                cmd.ExecuteNonQuery();
                SQLiteDataAdapter SDAdap = new SQLiteDataAdapter(cmd);
                DataTable DT = new DataTable("VendorProducts");
                SDAdap.Fill(DT);
                DG_VendorPur.ItemsSource = DT.DefaultView;
                sqliteCon.Close();
</code>
Comment: i used the following : DT.DefaultView.Sort = "VP_isVendorActive desc";      but it shows me runtime error: "Can't find column VP_isVendorActive"
Comment: the following: //DataView dv = DT.DefaultView;
                    //dv.Sort = "VP_Vname desc";
                    //DataTable sortedDT = dv.ToTable(); //   also give me same err: cannot find column VP_Vname;
Comment: This one also give me same err :    DT.DefaultView.Sort = "VendorProducts.VP_isVendorActive desc";
Comment: Solved: I sort the Sqlite Database in Select command : "Select VP_Vname,VP_VendorSKU,VP_SKUcaseCost,VP_QtyInCase,VP_isVendorActive from VendorProducts where VP_ProductID= @WORD ORDER BY VP_isVendorActive DESC";
Answer: Solved: I sort the Sqlite Database in Select command : "Select VP_Vname,VP_VendorSKU,VP_SKUcaseCost,VP_QtyInCase,VP_isVendorActive from VendorProducts where VP_ProductID= @WORD ORDER BY VP_isVendorActive DESC";


Identify scale name using Scala

Question: Does the program Scala (http://www.huygens-fokker.org/scala/) provide the ability to identify (i.e. name) a scale given its intervals or tones? Can't find the documentation to perform this operation.
Comment: I am by no means an expert on Scala but I would say _no_. That is beyond the scope of the software. The closest you can get is probably the "SHOW DATA" command.
Comment: Are you looking for a way to name *scales* or *tunings*? Scala has a very large database of *tunings* with names attached that can help with identification. If you're looking at a *scale* like 1 b2 3 4 b5 6 7 9 (or C Db E F Gb A B etc) and want to know whether it has a traditional name, that's a different question (which Scala indeed can't help you with, but I can a bit).
Comment: Thanks @helveticat yes, Scala is kind of confusing (to me at least) as to what it considers a tuning vs a scale. My intent is to identify scales.
Comment: Aha, then you might find this useful: https://archive.org/details/ScaleAndArpeggioResourcesAGuitarEncyclopedia. It's guitar-centric but contains a lot of scales with names. They're mostly based on the Carnatic system since Western music doesn't have set names for most "synthetic" scales. Disclaimer: I'm the author. There are a lot of other "scale dictionaries" around as well, and I take issue in the book with some of the traditional naming conventions, so do look around at other sources of course.
Answer: Yes, Scala can identify scales.
From the Scala website "Features" section:

Recognises more than 2900 musical modes. You can check any scale to see if it approximates an existing mode. (Bold original)

Identify scale name using Scala