(multiple choice) Given a random sample of equally divided possibilities what is the true population mean

Question:
Online Test Scenario:

A random sample of $500$ is taken from a large population, which is known to be
equally divided between males and females, and values for the quantity of interest are recorded. On examination of the results, it is found that the sample taken includes $200$ females for which the mean is $10.2$ with standard deviation of $0.6$ and $300$ males for which the mean is $14.8$ and standard deviation $2.4$.

Question:

Which one of the following statements in NOT correct?

Taking the mean value of the data for the $500$ sampled would over-estimate the true population mean
The most accurate estimate of the mean of the quantity of interest would have been obtained by sampling equal numbers of males and females
Given the sample that was taken, the best estimate of the population mean is the average of the means of the males and females i.e. $12.5$
The estimate from the sample of the mean for females is likely to be more accurate than that for males

My Attempt:
My guess is that option $4)$ is incorrect because your told in the beginning the population is known to be divided equally?
Comment: I agree with you that option 4 is incorrect, but because it should say "The estimate .. for females is **less likely** to be more accurate than that of males" because of the smaller sample size for females.
Comment: The distribution for females is much more homogeneous, so I think it's arguably likely to be more accurate, despite the smaller sample. I think #3 is false, because averaging over the sample over-represents the males and their higher average quantity of interest. (That said, this is a pretty unusual random sample! The chance of a 200/300 split if the population has equally many males and females is extremely unlikely.)
Comment: @SteveKass #3 says averaging the means, not over the sample. They did $\frac{10.2+14.8}2=12.5$
Comment: @RayDansh so would you say $#3$ is correct?
Comment: Yes, it makes sense, because the population is said to contain an equal proportion of males and females.
Comment: @RayDansh Would you like to put a formal answer below so that i can give you the points (i.e. explain why each option is either true or false)?
Answer: Let $M$ be the mean of the males. Let $F$ be the mean of the females.
$1$) is correct because taking the mean value of the sample would mean the $M$ is weighted more than $F$ ($60$%-$40$%).
$2$) is kinda correct, though really as long as you take the average of $M$ and $F$, not of the entire sample group, you don't need to get equal samples of males and females.
$3$) is correct because it reiterates the idea of averaging $M$ and $F$, and not taking the mean of the entire sample itself.
$4$) [Credit to SteveKass] is correct because the larger standard deviation  associated with the sample of males offsets the larger sample size, so there is less accuracy in $M$.
So in conclusion, $2$ is iffy, because since we're averaging $M$ and $F$, sample size isn't as important.
Comment: Could you explain why 2 is iffy in comparison to the rest? i haven't covered "mean of the quantity of interest" so i'm googling it now.
Comment: "Mean of the quantity of interest" is just saying population mean; "quantity of interest" was the fancy word the question used for the thing measured.
Comment: I would argue that I brought up more than a good point... A $p$% confidence interval for the males here will be much wider than for the females, due to the differences in sample sizes and standard deviations, both of which matter directly. While the population distribution for the quantity of interest is unknown, for most real-life distributions the estimate for males will be less accurate because of the 4-times greater standard deviation. Put another way, the standard error for males is about $0.13$ and for females is about $0.04$. This is roughly an estimate of the accuracy of prediction.
Comment: @RayDansh: Think about a real example. Suppose a quantity of interest is very homogeneous for females (say it is between $0.99$ and $1.01$ for $99$% of females, but not for males (say it is between $0.8$ and $1.2$ for the middle $90$% of males). A sample average for females regardless of sample size will be within $0.02$ of the true female population mean. Many sample averages for males, even for large samples, will be further than $0.02$ away from the male population mean.
Comment: @SteveKass So I see what you're saying, would you agree then that statement 2 is incorrect?
Comment: So in conclusion #2 is false?
Comment: Yes, I think Steve and I agree it's the most incorrect.
Comment: Sorry for all my edits. I've remarked on all four statements in my answer now, and I hope I haven't gotten the numbers or the words true and false mixed up any more!
Answer: Statement #4 is likely true.
If the sample is indeed random, then the $200$ females constitute a random sample of the females in the population. Similarly, the $300$ males constitute a random sample of the males in the population.
A rough estimate of the how far a sample mean is from a population mean is the sample's standard error. Here, the standard error for females is ${0.6\over\sqrt{200}}\approx0.04$ and for males is ${2.4\over\sqrt{300}}\approx 0.14$. It's reasonable to assume then that the expected inaccuracy of the female sample mean (as an estimate of the female population mean) is about ${0.04\over0.14}\approx 0.29$ of the expected inaccuracy of the male sample mean as an estimate of the male population mean.
Statement #3 is likely true.
The best estimate we have from the sample is that the males population average is $14.8$ and the female population average is $10.2$. Based on these best estimates, and using the given that the population is half female and half male, one would expect the population average across males and females to be $10.2+14.8\over2$. (This is different from the sample average, which would be a weighted average of the two means.)
Statement #1 is likely true. The particular sample happens to have more than the expected number of males, and males appear to have a higher value of the quantity of interest, so the sample mean is likely an over-estimate.
Statement #2 is likely false. Assuming, as appears likely from the sample, that males' values of the quantity of interest are more spread out, a better estimate would be found by sampling more males. Consider this extreme scenario: A quantity of interest is constant and equal to $1$ for females in a population, but it is spread out between $0$ and $2$ for males, with an unknown mean. To estimate the sample mean, it would not be useful to sample more females than needed to suspect that the female average was constant.
[While not part of the question, it's worth noting that a random sample with the given male-female split is very unusual. Within the distribution of all random samples of size 500 from a population with equally many males as females, the $z$-score of a sample with $200$ females (instead of the expected $250$) is about $4.47$. Only $0.08$% of samples, or one in about $1250$, would have such an unbalanced distribution of males to females, if the population were indeed equally divided. This would make me question the premises of the question!]
Comment: Why is statement #3 false though?  It averages the means of the samples, not over the entire sample.
Comment: I'm confused... didn't you say earlier that the standard errors meant that #4 was true?
Comment: Sorry, I messed up the statement numbers in my first version of the answer. Fixed now, I hope!
Comment: Did you not say above that #2 is false?
Comment: I think my answer is clear and correct now.


Combine post values and remove empty

Question: I have two sets of arrays coming from $_POST. Keys for both will be numeric and the count will be the same, since they come in pairs as names and numbers:
$_POST[names]
(
    [0] => First
    [1] => Second
    [2] =>
    [3] => Fourth
)

$_POST[numbers]
(
    [0] => 10
    [1] =>
    [2] => 3
    [3] => 3
)

Now I need to combine those two, but remove each entry where either values are missing.
The result should be something like:
$finalArray
(
    [First] => 10
    [Fourth] => 3
)

Post data is dynamically created so there might be different values missing based on user input.
I tried doing something like:
if (array_key_exists('names', $_POST)) {
        $names = array_filter($_POST['names']);
        $numbers = array_filter($_POST['numbers']);

        if($names and $numbers) {
           $final = array_combine($names, $numbers);

        }

    }

But I can't seem to filter it correctly, since its giving me an error:

Warning: array_combine(): Both parameters should have an equal number of elements
Comment: can we assume that both arrays will always have the same count, and that keys will always be numeric?
Comment: Yes, both keys will be numeric and the count will be the same, since they come in pairs as names and numbers.
Comment: @Alko I have added some relevant comments to each answer.  Please look review the page for some insights that may be educational to you and others.
Answer: Here's a fun way:
$result = array_flip(array_flip(array_filter(array_combine($_POST['names'],
                                                           $_POST['numbers']))));

Comment: This is not trustworthy because `array_filter()` will kill `0` valued elements.
Comment: Double flipping will also damage the output when there are duplicate numbers in `$_POST['numbers']`.  http://sandbox.onlinephpfunctions.com/code/6fc1774f9ea5f804760ab0184c02a49b641e3aa8  Please improve/rewrite this answer, too much wrong with it right now.
Answer: How about using array_filter with ARRAY_FILTER_USE_BOTH flag on?
<?php
    $array1 = [
        0 => "First",
        1 => "Second",
        2 => "",
        3 => "Fourth",
    ];

    $array2 = [
        0 => 10,
        1 => "",
        2 => 3,
        3 => 3,
    ];

    var_dump(array_filter(array_combine($array1, $array2), function($value, $key) {
        return $key == "" || $value == "" ? false : $value;
    }, ARRAY_FILTER_USE_BOTH ));

/*
Output:

array(2) {
  ["First"]=>
  int(10)
  ["Fourth"]=>
  int(3)
}
*/

Comment: This is not trustworthy because `array_filter()` will kill `0` keyed/valued elements.  http://sandbox.onlinephpfunctions.com/code/3d5536ea2a35d83c12afd0c52ef2f3d03d7ec47d
Comment: I recommend this slight adjustment: `var_export(array_filter(array_combine($array1, $array2), function($value, $key) {
    return $key!=="" && $value!=="";
}, ARRAY_FILTER_USE_BOTH));`
Answer: // create array using $_POST['names'] as keys and $_POST['numbers'] as values
$result = array_combine($_POST['names'], $_POST['numbers']);
// remove entries that have empty values
$result = array_filter($result);
// remove entry with empty key
unset($result[null]);

print_r($result);

Comment: This is not trustworthy because `array_filter()` will kill `0` valued elements.
Answer: If both arrays will have the same count, and the keys will always be numeric, you could do the following:
$total = count($_POST['names']);
$final = array();
for ($i = 0; $i < $total; $i++) {
    if (trim($_POST['names'][$i]) != '' && trim($_POST['numbers'][$i]) != '') {
        $final[$_POST['names'][$i]] = $_POST['numbers'][$i];
    }
}

Or if you prefer to use a foreach instead of for
$final = array();
foreach ($_POST['names'] as $key => $value) {
    if (trim($value) != '' && trim($_POST['numbers'][$key]) != '') {
        $final[$value] = $_POST['numbers'][$key];
    }
}

Comment: This answer is `0` key & value "safe" and duplicate `numbers` "safe".  I would call this answer very clean if those `trim()` calls weren't in there.  For the scope of this question, the `trim()` calls are not necessary.  Good answer.  Demo: http://sandbox.onlinephpfunctions.com/code/f0f517f82460b9efd27325bbd247ca912083dcbf
Answer: Takeing your previous information into account:

both keys will be numeric and the count will be the same, since they come in pairs as names and numbers

$myNewArray = array();

$count = 0;
foreach ($_POST['names'] as $bufferArray)
{
  if (($bufferArray[$count]!=NULL)&&($_POST['numbers][$count]!=NULL))
  {
    array_push($myNewArray, array($bufferArray[$count] => $_POST['numbers][$count]);
  }
  $count++;
}

Let me know if that helps! :)

Note: I made some edits to the code.
Also, my previous code checks if the empty array spaces are NULL. If you want to check if they are either NULL or "" (empty), then replace the line of code with:
if (($bufferArray[$count]!=NULL)&&($_POST['numbers][$count]!=NULL)&&($bufferArray[$count]!="")&&($_POST['numbers][$count]!=""))
{...}

Comment: This method has multiple syntax errors.  After fixing them, it still mangles the output and doesn't get close to returning the correct result.  Downvoted.  Always test your code before posting so that you don't confuse future readers, waste their time, or trick unsuspecting researchers to use bad code.  Working demo of bad output: http://sandbox.onlinephpfunctions.com/code/128d6609efaa691a8ca02499316ff39370ec9028

Combine post values and remove empty


Xamarin.Forms.Xaml.XamlParseException

Question: Estou criando um projeto Xamarin para estudo, tenho uma MasterPage e dentro dela tenho o código a baixo:
Estou compilando para o Android e vejo que o problema esta nesta linha:
xmlns:pages="clr-namespace:MyOrders.Pages;assembly=MyOrders"

Caso queira baixar o projeto que estou usando para estudo
https://drive.google.com/file/d/0B-svO0-4L_-Nb3I3MVZpTndQWms/view?usp=sharing
Erro:

Xamarin.Forms.Xaml.XamlParseException: Position 11:6. Type
  MasterDetailpage not found in xmlns
  http://xamarin.com/schemas/2014/forms

<?xml version="1.0" encoding="utf-8" ?>
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:pages="clr-namespace:MyOrders.Pages;assembly=MyOrders"
             x:Class="MyOrders.Pages.MasterPage">

  <MasterDetailpage.Master>

    <pages:MenuPage>

    </pages:MenuPage>

  </MasterDetailpage.Master>

    <MasterDetailPage.Detail>

      <NavigationPage x:Name="Navigator">

        <x:Arguments>

          <pages:MainPage>

          </pages:MainPage>

        </x:Arguments>

      </NavigationPage>

    </MasterDetailPage.Detail>

</MasterDetailPage>

No código dela .cs tenho:
namespace MyOrders.Pages
{
    public partial class MasterPage : MasterDetailPage
    {
        public MasterPage()
        {
            InitializeComponent();
        }

        protected override void OnAppearing()
        {
            base.OnAppearing();
            App.Navigator = this.Navigator;
        }

    }
}

Answer: MasterDetailpage está com o 'p' minúsculo.
O certo seria MasterDetailPage com 'P' maiúsculo :)

Xamarin.Forms.Xaml.XamlParseException


Figsize in pixels in Matplotlib

Question: I am trying to make two side by side graphs take up half my screen (resolution of 1600). Matplotlib defines figure size in inches and dots per inch. How can I use these to make each 810 pixels and is there any difference between the two?
fig, ax = plt.subplots(figsize=(8,4), dpi=100)
fig, ax = plt.subplots(figsize=(4,2), dpi=200)

Comment: figsize is in inches and dpi is pixels per inch.  The obvious multiplication does not work?
Comment: I didn't know that figsize is inches. Thanks for the answer.
Answer: The product of your figure size and the resolution of the figure in dots-per-inch needs to match the desired width and height of the image. At a screen resolution of e.g. 1600 × 900 pixels an image should be 800 pixels wide to take up half your screen, so this looks good:
fig, ax = plt.subplots(figsize=(8, 4), dpi=100)

"The native figure size unit in Matplotlib is inches, deriving from print industry standards." You can, however, specify your figures in other units like centimeters or pixels, see Matplotlib documentation: Figure size in different units, so this should also work for you:
fig, ax = plt.subplots(figsize=(800*px, 400*px))

Figsize in pixels in Matplotlib


User registration form at a new menu path got error after submit

Question: I'm creating an employee directory. I created a menu path which renders user registration form with profile fields.
When I submit the form, I got some unknown errors. I did fill out every fields in the form, but drupal shows "required" errors.

Error
  The website encountered an unexpected error. Please try again later.

Password field is required.
You must enter a username.
You must enter an e-mail address.
Notice: Undefined index: array_parents in field_default_form_errors() (line 369 of
  D:\fakepath\testsite\modules\field\field.form.inc).
Recoverable fatal error: Argument 2 passed to drupal_array_get_nested_value() must be an array, null given, called
  in D:\fakepath\testsite\modules\field\field.form.inc on line 369 and
  defined in drupal_array_get_nested_value() (line 6490 of
  D:\fakepath\testsite\includes\common.inc).

I have hook_form_alter in which some fields are made hidden.
Here is my code snippet in my custom module.
<?php
/*
 * Implementation of hook_menu()
 */
function mymodule_menu(){
    $items['employee/create'] = array(
        'title' => t('Create Directory'),
        'page callback' => 'drupal_get_form',
        'access callback' => 'mymodule_access_directory',
        'page arguments' => array('mymodule_employee_create_form'),
        'type' => MENU_NORMAL_ITEM,
        'weight' => 0,
    );
    return $items;
}
/*
 * Implementation of access callback for the menu
 */
function mymodule_access_directory(){
    global $user;
    # administrator can only access this
    if( in_array('administrator', $user->roles) ){
        return TRUE;
    }
    return FALSE;
}
/**
 * Home page which shows latest entered ten legs with cheapest tickets
 */
function mymodule_employee_create_form(){
    drupal_set_title('Create Employee Directory');
    return drupal_get_form('user_register_form');
}

/**
 * Implementation of hook_form_alter
 * Override form structure
*/
function mymodule_form_alter(&$form, &$form_state, $form_id) {

    if($form_id == 'user_register_form'){
        if($_GET['q'] == 'employee/create'){ # admin only can access this page
            # hide drupal default role selection; default role is employee
            $form['account']['roles']['#default_value'] = array(6);
            _mymodule_hide_elem($form, 'roles', 'account');
            # hide auto assign role selection; default role is employee
            $form['autoassignrole_user']['user_roles']['#default_value'] = 6;
            _mymodule_hide_elem($form, 'autoassignrole_user');
            # hide Status
            _mymodule_hide_elem($form, 'status', 'account');
            # hide Notify
            _mymodule_hide_elem($form, 'notify', 'account');

            # Change "Create new account" to "Create"
            $form['actions']['submit']['#value'] = 'Create';
        }

    }
}

function _mymodule_hide_elem(&$form, $name, $group=NULL){
    if($group){
        $form[$group][$name]['#prefix']     = '
';
        $form[$group][$name]['#suffix']     = '
';
        $form[$group][$name]['#required']   = FALSE;
    }else{
        $form[$name]['#prefix']     = '
';
        $form[$name]['#suffix']     = '
';
        $form[$name]['#required']   = FALSE;
    }
}
?>

Comment: Related: [Error: Argument 2 passed to drupal_array_get_nested_value() must be of the type array, string given](http://drupal.stackexchange.com/q/175271/1908)
Answer: My mistake in my hook_menu(). The page arguments should be array('user_registration_form') and I removed the custom page callback mymodule_employee_create_form(). It did work as expected.
function mymodule_menu(){
    $items['employee/create'] = array(
        'title' => t('Create Directory'),
        'page callback' => 'drupal_get_form',
        'page arguments' => array('user_register_form'),
        'access callback' => 'mymodule_access_directory',
        'type' => MENU_NORMAL_ITEM,
        'weight' => 0,
    );
    return $items;
}


Baixar ficheiros com cordova armazenados na base dados

Question: Existe alguma forma de baixar documentos armazenados numa base de dados mysql, no meu aplicativo híbrido cordova?
Answer: Existe mais de uma forma para efetuar esse processo, mas o mais simples é a criação de um Web Service.
O que você precisa fazer é escolher uma linguagem de programação Web que tenha conhecimento e utilizar ela para conversar (buscar os dados) do banco de dados. Depois dentro de sua aplicação você utiliza JavaScript para fazer as solicitações desses dados. Simples requisções HTTP's já devem resolver, mas lembre-se de CORS, que sempre causa problemas em aplicações Cordova.


What is the motivation behind this sampling algorithm

Question: I was recently reading on methods for sampling from linear distributions of directions. This distribution on a direction $X$ is defined by the density
$$
p(x)=\frac{1}{2}(1-3\kappa)+3\kappa\frac{1+x}{2}\quad \text{   for  } x\in[-1,1],
$$
indexed by the fixed parameter $0\le\kappa\le\frac{1}{3}$.
T
his distribution is a mixture of two distributions. Therefore, one could do the sampling in stages. Define
$$
p_1=(1-3\kappa)
$$
and
$$
p_2=3\kappa
$$
which allows us to write
$$
p(x)=p_1d_1(x)+p_2d_2(x)
$$
Either of the two probabilities can be selected using the probability mixing method. That is, for a pdf given by
$$
P(x)=\sum\limits_{i=1}^np_id_i(x)
$$
with
$$
1=\sum\limits_{i=1}^np_i
$$
generate uniform random number $r\in(0,1)$ and checking if
$$
r\in\left( \sum\limits_{i=1}^{m-1}p_i, \sum\limits_{i=1}^{m}p_i \right)
$$
before generating from $d_i$.
In this particular case the sum has only two summands.
What I don't understand is the implementation of the above method.  Consider the following python script
<code>def sample(k0):
  k=abs(k0)
  r1=np.random.uniform()
  if r1<=(1.-3.*k):
      r2=np.random.uniform()
      # uniform sampling for the cosine in the range -1,1
      cos=2.*r2-1
  else:
  # what is the meaning of this part ?
      r2=np.random.uniform()
      r3=np.random.uniform()
      cos=2.*max(r2,r3)-1.
  return cos*k0/k

# to plot & run use
k0=0.1
x=np.array([sample(k0) for x in range(1000000) ])

plt.hist(x,bins=100,normed=True)
plt.show()
</code>
But the meaning of the above lines of code used to sample the direction remains unclear:
<code>  # what is the meaning of this part ?
      r2=np.random.uniform()
      r3=np.random.uniform()
      cos=2.*max(r2,r3)-1.
</code>
Why are two random uniforms and the max of them needed to sample the cosine?
I would be grateful if someone could explain this point.
Comment: @Xi'an the direction cosine $x$ is being sampled and the allowed values are $x\in[-1,1]$. $\kappa$ is just a constant. Thank you for the comment. I corrected the missing part from the explanation.
Answer: If $U_1,U_2\sim\cal{U}(0,1)$, then
$$V=\max\{U_1,U_2\}\sim 2v\mathbb{I}_{(0,1)}(v)$$
and by a change of variable (with Jacobian $\frac{1}{2}$)
$$W=2V-1\sim \frac{1}{2} \{w+1\}\mathbb{I}_{(-1,1)}(w)$$
which is exactly the meaning of the code
<code>  r2=np.random.uniform()
  r3=np.random.uniform()
  cos=2.*max(r2,r3)-1.
</code>
and it produces a simulation from the second part of the mixture density
$$d_2(x)=\frac{1+x}{2}\mathbb{I}_{(-1,1)}(x)$$
Comment: OK I get it now. $\left|\frac{v(w)}{dw}\right|\cdot 2v\cdot\mathbb{1}_{(0,1)}=\frac{1}{2}\cdot2\cdot\frac{w+1}{2}*\mathbb{1}_{(-1,1})$ since $W\in[-1,1]$. Thank you!
Comment: Thank you for your answer and for editing/imporving the question. Reading your answer I was not able to understand the meaning of the second equation. Could you please explain it.
Comment: I am sorry, I totally forgot.
Comment: I am sorry I meant $k>\frac{1}{3}$
Comment: I was reading again the book where this example comes from. They say that if the parameter $\kappa$ is negative, one can replace it by its absolute value $|\kappa|$ but multiply the value of the sampled 'x' by the sign of $\kappa$ i.e $x\cdot\frac{\kappa}{|\kappa|}$ or in the code `cos*k0/k`. Is there a theory behind that?


'System.Net.Http.Formatting.IContentNegotiator' has not been registered

Question: I'm normally a Java developer. Today I decided I wanted to learn how to build a serverless web application in Azure using Microsoft's tools.
Since I'm a Mac user I installed the Mac version of Visual Studio.
Next, I created a new Functions solution and chose the template named "Http trigger with parameters".
I then pressed the Run button and saw that it opened a console window with a URL that I could use to access the service.
But when I hit that URL with curl from another window, I got this:
System.Private.CoreLib: Exception while executing function: Demo. Autofac: The requested service 'System.Net.Http.Formatting.IContentNegotiator' has not been registered. To avoid this exception, either register a component to provide the service, check for service registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency.
Being new to Microsoft tools in general, I have no idea what to do next. I'm also a little surprised that Microsoft would ship a tool in which running a default template with no changes would not work.
Frank
Comment: There is an open git-hub issue with [this](https://github.com/Azure/azure-webjobs-sdk/issues/1492) it seems
Comment: "I'm also a little surprised that Microsoft would ship a tool in which running a default template with no changes would not work."
Then you're *definitely* new to working with Microsoft stuff...
Answer: I believe the specific issue is with calling the extension method CreateResponse() on the request object. On the default template you should see something like this at the end of the run() method;
<code>return req.CreateResponse(HttpStatusCode.OK);
</code>
Workaround is to instantiate and populate an HttpResponseMessage object explicitly.
Something like this works for me, after a normal CRUD insert operation;
<code>// Save the entity and return a reference
var blobReference = await SaveBlob(blob);
// Create an HttpContent object to package the reference
var blobRefContent = new ObjectContent<BlobReference>(blobReference, (MediaTypeFormatter)MediaTypeFormatter.GetDefaultValueForType(typeof(BlobReference)));
// Create a response containing the reference and the original request, as well as a successful return code
var response = new HttpResponseMessage(HttpStatusCode.Created) { Content = blobRefContent, RequestMessage = req };
// Return the response
return response;
</code>


Android support library error after updating to 23.3.0

Question: I have been using android support v4 23.1.1 and recently tried to update it to 23.3.0 ( the latest one when this was asked) but I got the following error:

Error:Conflict with dependency 'com.android.support:support-annotations'.
  Resolved versions for app (23.3.0) and test app (23.1.1) differ.
  See http://g.co/androidstudio/app-test-app-conflict for details.

So far I have found this https://code.google.com/p/android/issues/detail?id=206137
I went to both the links but I could not fix my issue, how do I fix this issue?
Edit:
I have these in my dependencies
compile 'com.android.support:support-v4:23.3.0'
compile 'com.android.support:appcompat-v7:23.3.0'
compile 'com.android.support:recyclerview-v7:23.3.0'
compile 'com.android.support:cardview-v7:23.3.0'
compile 'com.android.support:design:23.3.0'

Previously all the versions were 23.1.1 and it worked fine the error occurred after updating
Edit:
Gradle Version 2.10
Gradle Plugin Version 2.0.0
buildToolsVersion "23.0.3"

Answer: For those people who are still facing this problem just add this line to your dependencies.
androidTestCompile 'com.android.support:support-annotations:23.3.0'

It solved my problem.
UPDATE:
If you have this error nowadays, you can just insert the new versioncode (23.3.0 in this case, or 27.1.1 in May '18) as it is described in the error into the above described solution.
Comment: Try adding  androidTestCompile 'com.android.support:support-v4:23.4.0'
Comment: SO - Stack Overflow
Comment: Tried your solution but still facing error:

`Error:Conflict with dependency 'com.android.support:support-v4'. Resolved versions for app (23.4.0) and test app (23.1.1) differ. See http://g.co/androidstudio/app-test-app-conflict for details.`

Gradle dependency:     `androidTestCompile 'com.android.support:support-annotations:23.4.0'`

Can you please suggest ?
Comment: Still leaves me with `Error:Conflict with dependency 'com.android.support:appcompat-v7'. Resolved versions for app (23.4.0) and test app (23.1.1) differ. See http://g.co/androidstudio/app-test-app-conflict for details.`. But upon adding `androidTestCompile 'com.android.support:appcompat-v7:23.4.0'` results in errors within values.xml `Error:(72) Error retrieving parent for item: No resource found that matches the given name 'TextAppearance.AppCompat.Display1'. ...`
Comment: Had to do the same to get my project to build since I upgraded to Android Studio 2.3. Thanks
Answer: For those who still facing the problem, above answer did not help me in android studio 2.2 Preview.
add this to your gradle file.
configurations.all {
  resolutionStrategy {
    force 'com.android.support:support-annotations:23.1.1'
 }
}

This fixed my issue.
Reference:
https://github.com/JakeWharton/u2020/blob/05a57bf43b9b61f16d32cbe8717af77cd608b0fb/build.gradle#L136-L140
Comment: Seems to have fixed mine too, in AS 2.2 Preview 3 that is
Answer: Just exemplifying Akshayraj's answer
Original Gradle file:
dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    [...]

    compile 'com.android.support:support-annotations:25.3.0'
    androidTestCompile 'com.android.support.test:runner:0.5'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'

}

Received error:

Error:Conflict with dependency 'com.android.support:support-annotations' in project ':app'.
  Resolved versions for app (25.1.0) and test app (23.1.1) differ.
  See http://g.co/androidstudio/app-test-app-conflict for details. "

FIXED when I added:
androidTestCompile 'com.android.support:support-annotations:25.3.0'

Final File:
dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    [...]

    compile 'com.android.support:support-annotations:25.3.0'

    androidTestCompile 'com.android.support:support-annotations:25.3.0'
    androidTestCompile 'com.android.support.test:runner:0.5'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
}

Answer: My orignal app.gradle had:
dependencies {
    // App dependencies
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'

    // Testing-only dependencies
    androidTestCompile 'com.android.support.test:runner:0.3'
    androidTestCompile 'com.android.support.test:rules:0.3'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2'
}

which resulted in following error:
Error:Conflict with dependency 'com.android.support:support-annotations'. Resolved versions for app (23.4.0) and test app (22.2.0) differ. See http://g.co/androidstudio/app-test-app-conflict for details.
After reading the link suggested in error, I found theses lines:

When instrumentation tests are run, both the main APK and test APK
  share the same classpath. Gradle build will fail if the main APK and
  the test APK use the same library (e.g. Guava) but in different
  versions. If gradle didn't catch that, your app could behave
  differently during tests and during normal run (including crashing in
  one of the cases).

So I modified my app.gradle dependencies to:
dependencies {
    // App dependencies
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'

    // Testing-only dependencies
    androidTestCompile 'com.android.support:support-annotations:23.3.0'
    androidTestCompile 'com.android.support.test:runner:0.3'
    androidTestCompile 'com.android.support.test:rules:0.3'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2'
}

Even after the above change gradle was not happy :-(:
Error:Conflict with dependency 'com.android.support:support-annotations'. Resolved versions for app (23.4.0) and test app (23.3.0) differ. See http://g.co/androidstudio/app-test-app-conflict for details.
Change in test apk version was different! So I modified the version string as pasted below which worked for me:
(Nirvana)
dependencies {
    // App dependencies
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0' // main APK

    // Testing-only dependencies
    androidTestCompile 'com.android.support:support-annotations:23.4.0' //test APK
    androidTestCompile 'com.android.support.test:runner:0.3'
    androidTestCompile 'com.android.support.test:rules:0.3'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2'
}

Comment: a decent example on android gradle usage --> https://github.com/JakeWharton/u2020/blob/master/build.gradle
Comment: Didn't work for me unfortunately, but I see how your answer works. +1 for the explanation.
Answer: Took me a while to get out of this error. But this is what has worked for me, give it a try:
NOTE: Am using compileSdkVersion 26
I removed both androidTestImplementation 'com.android.support.test:runner:1.0.2'
& androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' in the dependencies block in build.gradle(Module: app). So I ended up with this:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "com.date.brian.cradletest"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
   buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {

    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.0'
    compile 'com.android.support:design:26.1.0'
    compile 'com.android.support:cardview-v7:26.1.0'
    compile 'com.android.support:recyclerview-v7:26.1.0'
    compile 'com.getbase:floatingactionbutton:1.9.0'
    compile 'de.hdodenhof:circleimageview:2.1.0'
    testImplementation 'junit:junit:4.12'
}

I hope this comes in handy!
Answer: You have to use the same version for app and androidTest APKs. To do this, specify the same version as your app,
androidTestCompile 'com.android.support:support-annotations:24.1.1'

where 24.1.1 is the version number of the dependency used in your app
Answer: compile 'com.android.support:design:24.1.1'

Answer: For me, The build tool version has to align with the dependency versions. So lets say the build tool version is 26.1.0, the Gradle dependency version has to obey it.
The simplest way is to create a version variable & use it. See the example below
ext {
    buildVersion = '26.1.0'
}

dependencies {
    compile "com.android.support:appcompat-v7:${buildVersion}"
}

Answer: Just exclude 'annotations'. No harm will be done
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})

Answer:
Open Android Studio
Navigate to Project > Gradle Scripts > build.gradle (Module:app)
Add dependencies {androidTestCompile 'com.android.support:support-annotations:xx.x.x'}
You can replace xx.x.x to version which is showing in an error
Save Gradle script
Build Project

Hope this will work! :)
Answer: It was solved after adding the last line:
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
compile 'com.android.support:support-annotations:27.1.1'}

Answer: remove test dependency from build.gradel file for resolving the issues
Answer: /*
Resolves dependency versions across test and production APKs, specifically, transitive
dependencies. This is required since Espresso internally has a dependency on support-annotations.
*/
configurations.all {
    resolutionStrategy.force "com.android.support:support-annotations:$rootProject.supportLibraryVersion"
}

Comment: While this code may answer the question, providing additional [context](https://meta.stackexchange.com/q/114762) regarding _how_ and/or _why_ it solves the problem would improve the answer's long-term value. It also doesn't hurt to mention why this answer is more appropriate than others.


Enviar um valor para o modal

Question: Tenho uma tabela com vários funcionários e nela conta a chapa de cada hum.
 Criei um modal que quando o gestor clicar no nome do funcionário é chamado um modal onde é possível inserir o numero da chapa.
 Motivo: existem situações que esse numero de chapa pode mudar.
 Duvida:
 como que eu ao clicar na tabela consigo armazenar a chapa do funcionário que foi clicado para eu poder fazer o update na tabela ?
Seguem meus códigos:

Script do modal:

Minha tabela:

  <?php
     $query_pesquisa = mysql_query("SELECT
       func_chapa AS CODIGO,
       func_nome  AS NOME
       FROM
            funcionarios
            WHERE
                 func_status='1'")or die(mysql_error());
    if (empty($query_pesquisa)) {
    echo "Nenhum registro encontrado.";
    }
    ?>

        CODIGO
        NOME

  <?php
     echo"
";
     while ($row = mysql_fetch_array($query_pesquisa)) {
     echo"
";
        echo"".$row['CODIGO']."	";
        echo"".$row['NOME']."	";
     echo"
";

   }
  echo"
";
 echo"
";

?>

Modal:

      X Fechar

ATUALIZA CHAPA:

      <form  action="atualizar.php" method="POST">
        CHAPA:
        <input type="text" name="chapa" id="chapa">

          <button type="submit" class="btn btn-primary">ATUALIZAR</button>
      </form>

Comment: Não entendi o que você quer. Você quer atualizar a pagina que tem a tabela ou tabela do banco de dados? O seu modal já chama a pagina atualizar.php, então se você voltar para a pagina que possui a tabela, já não estaria tudo atualizado?
Answer: ola utilize dessa forma
Link tabela
   <a href="#"  id="botfun" data-id="<?echo $id_funcionario?>"
   title="Editar">Fulanp

Modal

            <button type="button" class="close" data-dismiss="modal" aria-  hidden="true">×</button>

Solicitação de   Cancelamento

formulario.php
  <?php
  $id_funcionario = filter_input(INPUT_POST, 'idfone',
  FILTER_SANITIZE_NUMBER_INT);
  ?>

ATUALIZA CHAPA:

  <form  action="atualizar.php" method="POST">
    CHAPA:
    <input type="text" name="chapa" id="chapa">

      <button type="submit" class="btn btn-primary">ATUALIZAR</button>
  </form>

Enviar um valor para o modal


How to show the value after push Firebase android?

Question: I am currently working on my final project, i got confused about how to show the value (expenses) from my firebase because I am using push,
So this is my database
and here is my code to add it on database
    DatabaseReference itemsRef = mRef.child("Users/" +
    mAuth.getCurrentUser().getUid()).push();
    itemsRef.child("expenses").setValue(total);

    EditText itemedit = findViewById(R.id.macam1);
    macam1 = itemedit.getText().toString();
    itemsRef.child("items/").setValue(macam1 + ": " + item01);

    EditText itemedit2 = findViewById(R.id.macam2);
    macam2 = itemedit2.getText().toString();
    itemsRef.child("items2/").setValue(macam2 + ": " + item02);

my User.class
public class User {
    private  String name;
    private int balance,expenses;

    public  User(){

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getBalance() {
        return balance;
    }

    public void setBalance(int balance) {
        this.balance = balance;
    }

    public void setExpenses(int expenses) {
        this.expenses = expenses;
    }

    public int getExpenses() {
        return expenses;
    }

}

this is the code so far:
DatabaseReference mRef = FirebaseDatabase.getInstance().getReference("Users");
final String key =  mRef.push().getKey();
String userid=user.getUid();
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("Users").child(userid).child(key);
ref.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

            int expense = (int) dataSnapshot.child("expenses").getValue();
            TextView view = (TextView) findViewById(R.id.totalExpense);
            view.setText("" + expense);

    }

    @Override
    public void onCancelled(DatabaseError error) {

    }
});

the ref already gave the value of the randomid but still error on
int expense = (int) dataSnapshot.child("expenses").getValue();
Comment: Possible duplicate of [Firebase show if child exists](https://stackoverflow.com/questions/42699854/firebase-show-if-child-exists)
Answer: To retrieve expenses from the database, try the following:
FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
String userid=user.getUid();
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("Users").child(userid);
ref.addValueEventListener(new ValueEventListener() {
 @Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
  String expenses=datas.child("expenses").getValue().toString();

  }
}

@Override
public void onCancelled(DatabaseError error) {

  }
});

In your database, you have Users/userid/randomid/key:value. So let the datasnapshot be at the userid then loop inside the randomid to be able to retrieve the child expenses
Comment: Hello @peter, I tried it then it goes to null reference, sorry, I am forgot to mention I had User class then i add it into 'expenses=datas.child("expenses").getValue(User.class).getExpenses;' and it shows 'Can't convert object of type java.lang.Long to type myapplication.User'. Sorry for long comment, I already include user.class on my question.
Comment: dont use user class, just use it as in the answer
Comment: If you want to use the user's class then remove the for loop `for(DataSnapshot datas: dataSnapshot.getChildren()){` and do `User user=dataSnapshot.getValue(User.class);`
Comment: i tried without using user.class (as u suggest) it gave me 'java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference'
Comment: what is userid returning?
Comment: it's return the id: ZsJPie1JUGQBR5tpCw0qZNnZ4lQ2(correct),
and the error is at String expenses=datas.child("expenses").getValue().toString();
Comment: it gave 'java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer'
and also it is said that randomid had no setter/field ('W/ClassMapper: No setter/field for -LASvfCy7Xcw0-oXg-9Z').

Sorry man, too many questions :)
Comment: Try and retrieve items `String items=dataSnapshot.child("items").getValue().toString();` Also why did u add child(key) just loop inside of it


How to estimate data accuracy based on a sample?

Question: I have a moderate size dataset (~100k rows), with a flag ("Y"/"N") for each row.
I would like to estimate the accuracy of this flag by checking whether it is correct for a subset of rows (chosen at random).
Checking all rows is not an option, since it is a time consuming process that cannot be automated.
Of course finding a wrong flag (e.g. by having "Y" in the dataset and finding out that it should actually be "N") means that the accuracy cannot be 100%, but:

how can I estimate the accuracy based on a sample?
assuming that I check $n$ values (out of $N$, with $n<<N$) and they are all correct, how do I express (statistically) how much "confident" I am that the accuracy is $100\%$?

Edit:
For point 2, I thought of setting up a Chi-squared test for categorical data. The null-hypothesis $H_0$ would be that the "actual flag" and the flag written in the data are independent (i.e. $0\%$ accuracy of the flag).
Let's assume I am checking a random sample of size $n$ out of $N$ and find no mistake, so that the contingency table for $F_o$ and $F_d$ (respectively the observed flag and the flag obtained from the data) is the following:
$
\begin{array}{|r|r|r|r|}
\hline
        & F_o=Y   & F_o=N       & \mathrm{Sum}          \\ \hline
F_d=Y & n r & 0             & n r     \\ \hline
F_d=N & 0         & n (1-r) & n (1-r) \\ \hline
\mathrm{Sum}      & n  r & n  (1-r) & n             \\ \hline
\end{array}
$
The $\chi^2$ is then just $n$. For one degree of freedom and $n=10$ I get a $p$-value of $0.001$, more than enough to reject the hypothesis of $0\%$ accuracy.
I consider this solution not satisfactory for two reasons:

It is not very useful to reject the null-hypotesis of independence (that is, $0\%$ accuracy of the flag). I would rather test the hypothesis of $100\%$ accuracy
The formula is counterintuitive:

it does not depend on the total number of rows $N$: for $n=N$ the accuracy of the data can be determined exactly
I don't understand intuitively why I need only $10$ observations of a large dataset to basically rule out the possibility that the flag is inaccurate: if e.g. the value "Y" occurs very rarely in the data, I expect a larger sample to be needed.
Comment: This sounds like a proportion test: either you got the right label (1) or the wrong label (0), and then some kind of confidence interval for that proportion. Does that sound right?
Comment: Look into Laplace's rule of succession: https://en.wikipedia.org/wiki/Rule_of_succession. For the case where you don't have 100%, does a proportion test make sense?
Answer: This sounds like a proportion test: either you got the right label (1) or the wrong label (0), and then you want to calculate the proportion of 1s with some kind of confidence interval.
When you get all 1s, that puts you in an awkward situation where the is not variability. Laplace has a "rule of succession" where you take that variation-free sample and add a 1 and a 0 to it.


No Correlation but significant ANOVA

Question: I have one categorical variable(4 categories - parenting style) and 6 scale variables(integer numerical values - scores from tests). I want to find out if the parenting style influences the test scores.
Based on information I found online, I am only able to make a Pearson correlation between categorical variables and metrical once only if the categorical ones have only 2 values: 0 and 1. This is why I created 4 new categorical variables, each with a value of 0 or 1 corresponding to the presence/absence of a parenting style. Then I calculated a Pearson correlation.
All the results were insignificant(very high p value).
If I perform a One-Way ANOVA, I get highly significant results(Sig 2-tailed is 0).
Are these results compatible? They seem not to be. What am I doing wrong?
Comment: Maybe doing nothing wrong. You're just using two fundamentally different measures of association that need not always agree. See my Answer for some details.
Answer: First, you need to distinguish between 'association' and 'correlation'. Suppose you have $k$ levels of a factor that represent a categorical variable (parenting style) and test scores that seek to give useful numerical measurements of some aspect of parenting. If a one-way ANOVA using this
categorical variable and this numerical variable, gives significant results, then you have significant association between the two variables.
Now suppose that the $k$ levels of the factor are numerical values, and the response variable is numerical. (Perhaps the factor involves different amounts of irrigation and the response variable is yield per acre of
a crop.) Then it makes sense to find the Pearson correlation between measured amounts of water and crop yields. This sample correlation may be far enough from $0$ to be statistically significant.
In your problem, suppose it makes sense to view the $k$
different parenting styles on an ordinal scale. (Maybe different amounts of time spent with a child, different levels of strictness in adhering to family rules, etc.)
Then it would make sense to find the Spearman correlation between ordinal style and a numerical test score. (Spearman correlation looks at ranks and ordinal data can be ranked.)
In this case of ordinal styles and numerical test scores,
you may have a significant result from an ANOVA and also a  Spearman correlation significantly different from $0.$
But it is possible for ANOVA to be significant and Spearman correlation not significant, for ANOVA not to be
significant and Spearman correlation significant, or neither to be significant.
ANOVA and Spearman correlation use different formulas and need not agree as to significance. In particular, an association that is detected by ANOVA need not be detected by Spearman sample correlation $r_S.$
Here are fake data to illustrate ANOVA and Spearman correlation. (Sampling and computations in R.)
set.seed(2020)
x1 = rnorm(50, 100, 10)
x2 = rnorm(50, 105, 10)
x3 = rnorm(50, 110, 10)
x4 = rnorm(50, 115, 10)
x = c(x1,x2,x3,x4)
g = rep(1:4, each=50)

par(mfrow=c(2,1))
 stripchart(x~g, ylim=c(.5,4.5), pch="|")
 boxplot(x~g, horizontal=T, col="skyblue2")
par(mfrow=c(1,1))

The Spearman correlation depends on the order of numbering of the four parenting styles. As numbered first below, test scores tend to increase as styles run from 1 through 4,
as seen in the stripcharts and boxplots above.
cor(x, g, meth="s")
[1] 0.3687901       # Order 1-2-3-4, Higher r.S
g2 = rep(c(1,4,3,2), each=50)
cor(x, g2, meth="s")
[1] 0.07459459      # Order 1-4-3-2, Lower r.S

The results of the ANOVA are the same for ANY ordering
of the four parenting styles. (ANOVA pays no attention to the order of listing of the $k=4$ levels of the factor variable.)
oneway.test(x ~ g)

        One-way analysis of means
     (not assuming equal variances)

data:  x and g
F = 11.35, num df = 3.00, denom df = 108.74,
  p-value = 1.554e-06

oneway.test(x ~ g2)$p.val
[1] 1.553761e-06

Comment: Indeed, I changed the ordering of the four parenting styles. The correlation had a random order and ANOVA had them ordered from low to high implication. I was not aware that this can impact the correlation.Can I run a correlation between the categorical parenting style( type 0,1,2,3) and test score(10-90)? Is this something valid?
Comment: Of course you can _do_ the correlation. Question is whether it shows anything _new._ Does the order of parenting style suggested by ANOVA make logical sense based on description of styles? That is, had you realized in advance that order of levels is important would you have used exactly that order? Will this order seem natural from descriptions of styles so that people reading an account of your work will agree it's reasonable without knowing the data? // Not fair to try all $4!=24$ orders, see which gives highest $r_S$ and say "I really knew that all along."

No Correlation but significant ANOVA


Name for the sense of how many items are present

Question: Sorry, this might be slightly off topic: there's a word for the ability to look at a small set of items are know how many are there without counting them, but I can't remember what it is and I can't find it on google. Can anyone tell me what this word is?
For instance, if you put a four apples in front of a very young child and ask how many there are, they will probably have to count them to tell you (especially if they are not in a "conventional" layout of four items). However, an older person has this ability and can immediately answer without counting them.
Answer: Subitizing. (Apparently there's a lower bound on characters in an answer - please excuse the parentheses.)
Comment: Perfect, thanks!


Fix for Windows Server 2012 R2 Hyper-V host identifying its network as 'Public' instead of 'Domain' on boot as the network gateway is one of its VMs?

Question: I have a Windows Server 2012 R2 box with the Hyper-V role installed which is also Domain Controller. The server is in a DMZ area of the network, and the only other Windows box is a Server 2012 R2 virtual machine on the same server. The server also hosts a Web Proxy VM which is the network gateway.
The issue I have is that every time the server is booted, because the Web Proxy VM is not yet started, the server can't find the gateway IP and doesn't identify it's own network adapter as 'Domain', it is instead labelled as 'Public'. Disabling and re-enabling the NIC corrects this issue, but can't be done remotely as RDP ports are not open for 'Public' networks, necessitating a trip to the server room.
What is the best way to get the server to re-evaluate the network it is connected to such that it identifies it as 'Domain' and applies the correct firewall rules, within a reasonable time after boot but such that the Web Proxy VM has had time to boot also?
Comment: 1. Install a second Hyper-V host that you can migrated the virtual machines to when you need to reboot this host, and vice versa. 2. Allow RDP inbound in your Public firewall rule for your specific ip address or internal network. This will ensure that you can RDP to the host regardless of the network/firewall profile in use.
Answer: It's not a particularly good practice to have management access to a host server depending on services provided by a guest VM in this way. Otherwise what happens if you need to stop/restart/reconfigure that VM while connected via the gateway it is providing? You'd probably be better off with a separate management NIC.
Anyway, that said, the service that makes the determination of what firewall profile to load is the "Network Location Awareness" service. Restarting that will have the same effect as disabling/re-enabling the NIC in this case so you could perhaps schedule a net stop nlasvc, net start nlasvc (and the dependent services like the network list service) to run after you think the guest VM has had time to boot.
Otherwise enable RDP through the Public firewall profile to ease troubleshooting. If the server is in the DMZ then the DMZ firewall should be keeping the internet out and prevent it becoming a security hole.
Comment: Thanks for the pointer towards the Network Location Awareness Service, I'll look at scheduling that for a restart 10 minutes after boot. Management of the Hyper-V host will actually be via IP KVM in the near future, so the RDP isn't going to be an issue long term, but I appreciate it's not a great setup where a reboot can prevent further access!


Drupal and node relationships

Question: For our final CS project, we have been tasked with building a project management system for a large corporation (which the company wants us to use Drupal). So far we have a few entities created (project, request, and task). A project can have many tasks, and a project can only have one request attached (the request is created first, once approved, a project is created).
Since Drupal is really more of a content (blogs/comments/articles/pages) management system, it is difficult to create dynamic forms that allow showing tasks attached to a project with the ability to add tasks directly within the project "form". I guess this would kind of be a master/detail view.
How can I go about building these types of add/edit/details "forms"? My first two ideas are:

Build custom add/edit/delete forms for each entity type
Build a node-add-project.tpl.php, node-edit-project.tpl.php, etc... for each complex view required

The downside to this is that my fields in my forms are now hard-coded. One requirement is that this system must be dynamic so the end-user can add a field if they need to.
How can I go about this? Templates? Custom Forms?
By the way I have googled, and googled, and googled (probably 5-8 hours) of different things (master details, complex forms, complex entity relationship forms) to no avail.
I am aware of the nodereference and entity reference (and all other reference) types. But these only allow you to use a dropdown list, or a select list, etc...
EDIT:
It is looking like building the database with the Schema API, and utilizing the Form, Theme, and security APIs are going to be our best bet.
Here is a good read.
Comment: Node Reference module also allows you to use a text field that will suggest what you're looking for, as you type, from database (much like Google's autocomplete suggestions). Is that useful for you, or what do you have in mind?
Comment: Not really, one of the requirements is the ability to add tasks to a project (easily) - from the view project screen. So having to create a new task, and then specify the project doesn't really make sense (especially if you just CAME from that project).
Comment: http://drupal.org/project/nodereference_url may help with that situation; you can create a link that will automatically set the nodereference field value based on a url parameter to the node form.
Comment: Do you need to do this all programatically? If so there are a ton of API's which could support you, I would suggest taking a look. If you want it dynamic would it be cheating to use modules like Display Suite (this really sorts out a lot of tpl.php requirements) so you can customise the display of each nodes type...
Comment: IS it necessary to use entity, as looking at your requirement You can do all this with creating contain type and you do not need to do everything with coding in CMS like drupal.
Comment: Yes, this system will be used in a corporate environment, and some "entities" have 50-100 fields. Storing that across 50-100 tables does not make sense. Now multiply that times 30-40 entities, and you have 2000+ tables. And if we ever have to build custom queries ... ouch.
Answer: You should be able to duplicate this functionality using the Field Collection module.
In short, you attach a Field Collection field to an entity, and then define the Field Collection in a separate UI (/admin/structure/field-collections) by attaching additional fields to it. It will behave like (and is in fact internally represented as) a first-class entity, and the module allows you to manage these items from the same parent form you attached the Field Collection field to, complete with drag-and-drop for reordering and the like. It also has a number of other nice features, such as letting users with appropriate permissions add/edit/delete Field Collection items while viewing the parent node without having to go into the edit form itself.
Comment: I will take a look, when I looked at it initially it didn't seem to do what I need, but this could in fact be very handy. Thanks!
Answer: Not exactly what you asked: Are you sure you want/must build this with Drupal? If you have to, have a look at entities. Be prepared to live with young and not perfect documented features. Entities are the Drupal thing of business classes. Nodes are one incarnation of them to manage content.
Comment: Ultimately this is what I had to do. Yes this must be developed with Drupal (my professor, and the businesses requirements). It's actually working out quite nicely, now, instead of having hacked together "content types" linked with references, I have complete control over my entities defined by hook_schema and hook_entity_info, including fieldable entities to allow for dynamic fielding. Not sure how this will work with reporting though, will be an interesting semester :).
Comment: You can use fields and views with entities. This requires some extra work but especially views commes in very handy when you need report and overview screens. What is sometimes a good aproach to find code examples is to find a contrib module which is using your approach.

Drupal and node relationships


Using setPictureSize and Camera Parameters

Question: I've looked into figuring out how to set the size of a picture, and I stumbled upon CameraParameters and the setPictureSize method associated with it.  The problem is, I can't figure out how to use any of these.  I don't know what needs to be imported, what object to create, how to use the setPictureSize method, or where to even place that code.  I have 2 chunks of code that I feel may be a good place to use setPictureSize.  These chunks are:
    takePicture = (Button) findViewById(R.id.takePicture);

    takePicture.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (name.getText().length() == 0 || experimentInput.getText().length() == 0) {
                showDialog(DIALOG_REJECT);
                return;
            }

            ContentValues values = new ContentValues();
            imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);

            time = getTime() ;

            startActivityForResult(intent, CAMERA_PIC_REQUESTED);
        }

    });

and:
public static File convertImageUriToFile (Uri imageUri, Activity activity)  {
    if (activity == null) Log.d("test", "NULL!");
    Cursor cursor = null;
    try {

        String [] proj={MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID, MediaStore.Images.ImageColumns.ORIENTATION};
        cursor = activity.managedQuery( imageUri,
                proj, // Which columns to return
                null,       // WHERE clause; which rows to return (all rows)
                null,       // WHERE clause selection arguments (none)
                null); // Order-by clause (ascending by name)
        int file_ColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        int orientation_ColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.ORIENTATION);
        if (cursor.moveToFirst()) {
            @SuppressWarnings("unused")
                String orientation =  cursor.getString(orientation_ColumnIndex);
            return new File(cursor.getString(file_ColumnIndex));
        }
        return null;
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    if(cursor!=null)
    {
        //HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
        //THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
    else return null;
}

So, my question is, how do I use setPictureSize and where should I put it?  No website, nor the android development guide, nor any other related StackOverflow question was helpful to me.
Editted Code:
public Bitmap getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        if(cursor!=null)
        {
            //HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
            //THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();

            int desiredImageWidth = 100;  // pixels
            int desiredImageHeight = 100; // pixels
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inSampleSize = 2; // will cut the size of the image in half; OPTIONAL
            Bitmap newImage = Bitmap.createScaledBitmap(BitmapFactory.decodeFile(cursor.getString(column_index), o),
                                                       desiredImageWidth,
                                                       desiredImageHeight,
                                                       false);

            return newImage; //cursor.getString(column_index);
        }
        else return null;
    }

Answer: That's used for when you're actually using the camera through a custom View.  What you're doing right here is sending an implicit intent to Android to open another Activity that uses the camera to take a picture.
In this case, you can limit the size of your image by using MediaStore.EXTRA_SIZE_LIMIT.  If you want to specify the dimensions of the image, than you have to load it from the URI that it was saved to, create a new scaled image, then resave it over the old one.
Once you have the URI of the image (which is from the DATA attribute in the projection), you can resize the image like so:
int desiredImageWidth = 100;  // pixels
int desiredImageHeight = 100; // pixels
BitmapFactory.Options o = new BitmapFactory.Options();
o.inSampleSize = 2; // will cut the size of the image in half; OPTIONAL
Bitmap newImage = Bitmap.createScaleBitmap(BitmapFactory.decodeFile(imagePath, o),
                                           desiredImageWidth,
                                           desiredImageHeight,
                                           false);

Then save it over the old one.
Comment: That sounds reasonable.  Where exactly am I putting this though?  Somewhere in the `convertImageUriToFile` method or the `getPath` method?
Comment: Personally I wouldn't put the bitmap encoding inside any one of those methods since each server their own purpose quite well.  `imagePath` must be a String object directly to the image file (not an android content uri), and it looks like `getPath()` will retrieve exactly that for you.  You should also be able to get that information from the `File` object your `convertImageUriToFile()` method returns using `getAbsolutePath()` or `getPath()`.
Comment: I sort of understand what you're saying.  To do what you mentioned, I must use a String object rather than an android content uri.  My question is, being a novice Android programmer, what do I need to change to do this?  Do I need to put `String[] projection` somewhere/return it to something?
Comment: Your `getPath()` method will return the string you need if it's successful.  You can change it to a `getBitmap` type method if you want and use `cursor.getString(column_index);` as the imagePath.
Comment: I added an edit to the bottom of my question.  Is this what you mean?
Comment: I ran my app using the code I have above.  The picture has not re-sized to 100x100.
Comment: Are you displaying it in a layout?  If so, are the layout parameters match_parent, fill_parent or wrap_content?  It will stretch the image out if the View is in match_parent or fill_parent.
Comment: I'm sending the picture off to a website.  It is still huge on the website, not limited to the size I want.
Comment: Do you think maybe perhaps this is a problem not so much on my phone, but on the website itself?  It seems that the image on the website always fills the screen...
Comment: It could be.  I don't know.  I just know that the image scales on my phone when I do it and show it on a View.  What you can do in this case is get the image from your phone.  You can save it to an external SD card, then use the DDMS in Eclipse to access the file system.  Download the image from the phone and see what dimensions it is.
Comment: The dimensions are coming out as 1536 x 2048. They should be 1024 x 786 (which is actually half of that).
Comment: Would you know how to convert from a Bitmap to a File?  I see in my code originally its trying to covert a Uri to a File using a method, so I instead made this a Bitmap to a File (the Bitmap being the one you had me implement in the code you provided), perhaps this would work.  I have a feeling its just ignoring the Bitmap code at this moment.
Comment: http://stackoverflow.com/questions/649154/android-bitmap-save-to-location

I think the answer to that question would be what you're looking for.  `fileName` in this context would be the direct path of the file you want to write too (can be a String of the URL or a File object).  Compress `newImage` to the `outputstream` which should write it to the file. The solution at the top may work too.
Comment: Converting an already captured photo to a different resolution will distort the image if `actualPhotoHeight / intendedPhotoHeight != actualPhotoWidth / intendedPhotoWidth`. Simply put, image will be distorted if scale ratio of sides doesn't match


Why is a projection matrix of an orthogonal projection symmetric?

Question: I am quite new to this, so I hope you forgive me if the question is naïve. (Context: I am learning econometrics from Davidson & MacKinnon's book "Econometric Theory and Methods", and they do not seem to explain this; I've also looked at Luenberger's optimization book that deals with projections at an a bit more advanced level, but with no luck).
Suppose that I have an orthogonal projection $\mathbb P$ with is associated projection matrix $\bf P$. I am interested in projecting each vector in $\mathbb{R}^n$ into some subspace $A \subset \mathbb{R}^n$.
Question: why does it follow that $\bf{P}=P$$^T$, that is, $\bf P$ is symmetric? What textbook could I look at for this result?
Comment: https://en.wikipedia.org/wiki/Projection_(linear_algebra)#Orthogonal_projections
Answer: This is a fundamental results from linear algebra on orthogonal projections. A relatively simple approach is as follows. If $u_1, \ldots, u_m$ are orthonormal vectors spanning an $m$-dimensional subspace $A$, and $\mathbf{U}$ is the $n \times p$ matrix with the $u_i$'s as the columns, then
$$\mathbf{P} = \mathbf{U}\mathbf{U}^T.$$
This follows directly from the fact that the orthogonal projection of $x$ onto $A$ can be computed in terms of the orthonormal basis of $A$ as
$$\sum_{i=1}^m u_i u_i^T x.$$
It follows directly from the formula above that $\mathbf{P}^2 = \mathbf{P}$ and that $\mathbf{P}^T = \mathbf{P}.$
It is also possible to give a different argument. If $\mathbf{P}$ is a projection matrix for an orthogonal projection, then, by definition, for all $x,y \in \mathbb{R}^n$
$$\mathbf{P}x \perp y-\mathbf{P}y.$$
Consequently,
$$0 = (\mathbf{P} x)^T (y - \mathbf{P}y) = x^T \mathbf{P}^T (I - \mathbf{P}) y = x^T (\mathbf{P}^T - \mathbf{P}^T \mathbf{P}) y $$
for all $x, y \in \mathbb{R}^n$. This shows that $\mathbf{P}^T = \mathbf{P}^T \mathbf{P}$, whence
$$\mathbf{P} = (\mathbf{P}^T)^T = (\mathbf{P}^T \mathbf{P})^T = \mathbf{P}^T \mathbf{P} = \mathbf{P}^T.$$
Comment: @Milan Thank you for noticing.  Observe that $x=x^T$ for $x\in\mathbb{R}^n$ is possible only when $n=1$, which is uninteresting. What happened simply is that a few transposes were lost on the $x$'s in the penultimate line.  I have restored the missing transposes to make the algebra correct.
Comment: It is not enough characters for me to be able to edit it, but $\mathbf{U}$ is an $n \times m$ matrix; not an $n \times p$ matrix. Not sure where $p$ came from.
Comment: Thanks for your insightful comment(s)! Somehow the Wikipedia article, which mentioned something about self-adjointness of the projection operator threw me off, as your proofs are not that difficult. :) BTW, do you have a favorite linear algebra text that deals with this kind of stuff?
Comment: The elementary linear algebra book I know the best does not cover this. The best references I know are advanced books on functional analysis. The [Linear algebra done right](http://books.google.com/books?id=ovIYVIlithQC&printsec=frontcover&source=gbs_ge_summary_r&cad=0#v=onepage&q&f=false) book looks good, but I don't know it.
Comment: A note: NRH's answer assumes that $x = x^T$.
That is, the only case in which $(Px)^T = xP^T$ (as claimed in the equality $(Px)^T(y-Py)=xP^T(I-P)y$) is when $x = x^T$ because for any linear map $P$ and vector $x$, $$(Px)^T = x^TP^T.$$
This does not affect really the result of the proof, as the implication that $P^T - P^TP = 0$ holds in both cases, but I thought it would be worth mentioning.
Answer: An attempt at geometrical intuition...
Recall that:

A symmetric matrix is self adjoint.
A scalar product is determined only by the components in the mutual linear space (and independent of the orthogonal components of any of the vectors).

What you want to "see" is that a projection is self adjoint thus symmetric-- following (1). Why is this so?
Consider the scalar product of a vector $x$ with the projection $A$ of a second vector $y$: $ \langle x,Ay \rangle$. Following (2), the product will depend only on the components of $x$ in the span of the projection of $y$. So the product should be the same as $\langle Ax,Ay \rangle$, and also $\langle Ax,y\rangle $ following the same argument.
Since $A$ is self adjoint- it is symmetric.
Comment: Thanks a lot! Before reading your comment, I was quite confused about why self-adjointness is crucial here. Now I have some clue, thanks!


Mixing of @SessionScoped and @Model in CDI documentation

Question: Java EE 6 newcomer question ahead, so beware...
I keep reading introductory CDI material like
http://docs.jboss.org/cdi/spec/1.0/html_single/#d0e268
I'm wondering throughout that document why they are mixing @SessionScoped with @Model, which is defined as being @RequestScoped plus @Named and a few other things I don't understand.
Why aren't the beans, e.g. the Login bean, simply annotated with @Named + @SessionScoped? What's the gain here?
Thanks
Answer: You're right using @Named@SessionScoped`would achieve the same and would be clearer. In fact I wonder if some CDI impl couldn't throw an exception with this double scope (Weld doesn't).
BTW I encourage you to read Weld documentation which is a more concrete approach to CDI IMHO.


What path should I embark on as a new left handed guitar player

Question: Probably 20-25 years ago I bought an electric guitar but did not put forth the effort to learn much.  At the time the internet was fairly not as advanced as it is now.  I don't even remember if youtube existed back then, in any event I have always wanted to learn to play guitar.  I am now 44 years old and have decided I better start now or I will never start.
I am left handed and cannot hold a right handed guitar for the life of me so I decided that I want to buy a left handed guitar.  I found a couple of guitars I like (they are both from Taylor one is 214CE and the other is 314CE, the 314CE being much pricer due to being all wood).  In any event, I then decided to look for lessons and boy are they pricey.  Most of the lessons near me are around $45-50 (USD) every half hour, sometimes more.  I dont mind investing in this maybe when I am a little more comfortable with guitar.
As much as I want to be tutored or have an instructor, I decided at first I will try to do this alone.  However, I am having a very hard time knowing even where to start.  There are practically millions of sites claiming to teach you how to play guitar, along with millions of youtube videos, etc.  As much as I feel it is great that so much information is out there I feel it is overwhelming me to the point where I get tired just trying to look to learn.
Is there any recommendation for a total beginner like myself.  I don't know much aside from what the guitar is composed of, how to hold it, and that I want to and can only play left handed (please do not try to convince me to play right handed, I just cannot no matter how hard I try to hold a guitar - I have tried).  Should I start with chords?  Should I learn scales?  What order or what reference or even is there a path (possibly free or inexpensive at least for now) I could take to learn the guitar?
If it helps I am interested in artists like John Mayer, the Fray, Dave Matthews, Owl City, and similar artists. One thing I have to mention is as much as I wish I could play a lot (I see there are stories of people practicing 6 or more hours a day) it is just not practical for me.  I have 3 kids, a wife, a job, and the daily responsibilities of life.  I could commit to possibly 1 hour a day, and I know it isn't a lot but it is probably the maximum I can put in.  Can anyone point me to a path I should take to get me going without overwhelming me with so many different random sites / videos?
Comment: Does this answer your question? [Need Help in Starting to Learn Guitars?](https://music.stackexchange.com/questions/2348/need-help-in-starting-to-learn-guitars) (and numerous others)
Comment: You do not need to practice 6 hours a day to get somewhere. Practicing 15 minutes a day will still be much better than practicing 2 hours each month or so.
Comment: If you can't play a righty guitar then you're either in need of a good teacher or some resetting.   Take a look at the number of  "lefty" violins,  flutes, saxophones, pianos and ask yourself how all those left-handed musicians can play a "righty" instrument.
Comment: Although this is not asking about l.h. versus r.h., (where we have many q/a dupes), it is asking for resources, and as such, won't stand on this site, as it doesn't cater for such questions. Sorry.
Answer: EVERYONE'S a left-handed guitar player!  It's the LH that does the clever stuff, fingering all those chords and notes.  RH has a much more basic job to do.
But, whatever.   Whichever side you decide to hang, you'll need some lessons at the very outset in order to set up a basic technique.   THEN move over to self-study if you must.
One hour of daily practice is fine.  And try also to find a REASON to play, other than solitary self-development.   Join a band, play at church, etc. etc.   Otherwise I guarantee you'll go the way of most adult beginners, rapid initial progress but frustration with the long business of consolidation and loss of interest.
Answer: First of all: There isn't really left- or righthandedness in music. Music requires high control over very specific muscles, both on the right and the left side. This is the reason why many left handed players are able to learn a "right-handed" instrument just fine. But if in your case playing on a mirrored guitar feels more natural to you, go for it. Making it harder for yourself will force you to put much effort into making it work and will mean you can focus less on musicality. (The disadvantage of doing this is of course the availability of such instruments, which is not that much of a problem for you as you probably do not want to go full professional mode anyway, so you will be able to stick to one instrument.)
So then how do you start? Learning guitar is not really different on a left handed guitar, so you should start like on a regular guitar. Learning guitar (just as any instrument) requires you to build up specific muscles and coordination. So simply saying "start by practicing scales" or "start by practicing chord" will not really give you a good start.
The best way would really be to get lessons. You do not need weekly lessons, even a lesson every two weeks or even once a month are better than nothing. You might feel like investing into a lesson when you are not yet comfortable is a waste, but in fact it is the fasted way to get started because a teacher will be able to quickly correct you, making the learning process much more efficient. Also a good teacher will give you a lot of structure. A teacher will consider what techniques you should practice at any point, and a teacher will be able to help you pick literature that is not so easy you get bored but not so hard that you get frustrated. (Also a teacher will be able to cater to your wishes of what you want to do. Do you want to go classical? Do you want to be able to simply play an accompaniment using chords? Do you want to go rock guitar? Jazz guitar?)
If you really do not want to invest into lessons at this point get yourself a guitar book targeted at your level and age. You may ask your music store for a recommendation (even if it is an online store), and there are many recommendations to be found online.
A guitar book will usually have a decent concept on how to proceed learning the instrument, even if it cannot give you the feedback a teacher can give you.
Answer: Although it was a long time ago, I got my start on guitar in beginner group lessons, which in my case were held weekly at a park district community center by an instructor who also directed band at the local public school.
Group lessons were much more affordable than private lessons and still established the fundamentals of the instrument.  There was a mix of ages, from elementary schoolers through adults.
You still get the benefit of a live person watching and correcting your technique (which you wouldn't get from a YouTube video).
Once you've gotten a good start, then you could think about investing in private one-on-one lessons.
Your left-handedness shouldn't make a difference at all if you buy a left-handed instrument.


Sum of a series with

Question: I am trying to compute the sum of the following series:
$$
\sum_{n=1}^\infty 3^{n-1}\sin^{3}\left(a \over \,3^{n}\right)
$$
The series is clearly convergent by the ratio test, as well as by comparison with $(\frac{a}{3^n})^3$. If I take the derivative with respect to $a$, I am eventually left with $\cos(\frac{a}{3^n})-\cos^3(\frac{a}{3^n})$, which doesn't seem very helpful, plus I'm not sure it's okay to take the derivative. Multiplying by sine functions to try to get a telescopical sum didn't lead me anywhere. Any ideas will be appreciated. Thanks!
Answer: As a hint:$$\sin(3x)=3\sin x-4\sin^3x \to \color{red}{\sin^3(x)=\frac14\Big(3\sin x-\sin(3x)\Big)}$$so
$$\sum_{n=1}^\infty 3^{n-1}\sin ^3{\frac{a}{3^n}}=\\
\frac14\sum_{n=1}^\infty 3^{n-1}(3\sin {\frac{a}{3^n}}-\sin {\frac{3a}{3^n}})=\\
\frac14\sum_{n=1}^\infty (3^n\sin {\frac{a}{3^n}}-3^{n-1}\sin {\frac{a}{3^{n-1}}})=\\
\frac14\sum_{n=1}^\infty (f(n)-f(n-1))$$
Comment: Yes, should I propose an edit to your post with the full solution?
Comment: woah easy peasy lemon-squeezy (+1)
Comment: Oh, okay, I see. Thanks for the help, I'll accept your answer!
Comment: @Wolfuryo: your welcome, Can you take over now ?
Comment: @Wolfuryo:No, take it easy.

Sum of a series with


Android Camera Parameter setPictureSize causes streaked picture

Question: I am trying to take a picture using the Android camera. I have a requirement to capture a 1600 (w) x 1200 (h) image (3rd party vendor requirement). My code seems to work fine for many phone cameras but the setPictureSize causes a crash on some phones (Samsung Galaxy S4, Samsung Galaxy Note) and causes a streaked picture on others (Nexus 7 Tablet). On at least the Nexus the size I desire is showing up in the getSupportPictureSizes list.
I have tried specifying the orientation but it didn't help. Taking the picture with the default picture size works fine.
Here is an example of the streaking:

For my image capture I have a requirement of 1600x1200, jpg, 30% compression, so I am capturing a JPG file.
I think I have three choices:
1) Figure out how to capture the 1600x1200 size without a crash or streaking, or
2) Figure out how to change the size of the default picture size to a JPG that is 1600x1200.
3) Something else that is currently unknown to me.
I have found some other postings that have similar issues but not quite the same. I am in my 2nd day of trying things but am not finding a solution. Here is one posting that got close:
Camera picture to Bitmap results in messed up image (none of the suggestions helped me)
Here is the section of my code that worked fine for until I ran into the S4/Note/Nexus 7. I have added a bit of debugging code for now:
Camera.Parameters parameters = mCamera.getParameters();
Camera.Size size = getBestPreviewSize(width, height, parameters);

if (size != null) {
    int pictureWidth = 1600;
    int pictureHeight = 1200;

    // testing
    Camera.Size test = parameters.getPictureSize();
    List<Camera.Size> testSizes = parameters.getSupportedPictureSizes();
    for ( int i = 0; i < testSizes.size(); i++ ) {
        test = testSizes.get(i);
    }

    test = testSizes.get(3);
    // get(3) is 1600 x 1200
    pictureWidth = test.width;
    pictureHeight = test.height;

    parameters.setPictureFormat(ImageFormat.JPEG);
    parameters.setPictureSize(pictureWidth, pictureHeight);
    parameters.setJpegQuality(30);
    parameters.setPreviewSize(size.width, size.height);

    // catch any exception
    try {
        // make sure the preview is stopped
        mCamera.stopPreview();

        mCamera.setParameters(parameters);
        didConfig = true;
    catch(Exception e) {
        // some error presentation was removed for brevity
        // since didConfig not set to TRUE it will fail gracefully
    }
}

Here is the section of my code that saves the JPG file:
PictureCallback jpegCallback = new PictureCallback() {
    public void onPictureTaken(byte[] data, Camera camera) {
        if ( data.length > 0 ) {

            String fileName = "image.jpg";

            File file = new File(getFilesDir(), fileName);
                String filePath = file.getAbsolutePath();

             boolean goodWrite = false;
             try {
                 OutputStream os = new FileOutputStream(file);
                 os.write(data);
                 os.close();

                goodWrite = true;
            } catch (IOException e) {
                 goodWrite = false;
             }

             if ( goodWrite ) {
                // go on to the Preview
             } else {
                // TODO return an error to the calling activity
             }

        }

        Log.d(TAG, "onPictureTaken - jpeg");
    }
};

Any suggestions on how to correctly set up the camera parameters for taking photos or how to crop or resize the resulting photo would be great. Especially if it will work with older cameras (API level 8 or later)! Based on needing the full width of the picture I can only crop off the top.
Thanks!
EDIT: Here is what I ended up doing:
I started by processing the Camera.Parameters getSupportedPictureSizes to use the first one that had the height and width both greater than my desired size, AND the same width:height ratio. I set the Camera parameters to that picture size.
Then once the picture was taken:
BitmapFactory.Options options = new BitmapFactory.Options();;
options.inPurgeable = true;

// convert the byte array to a bitmap, taking care to allow for garbage collection
Bitmap original = BitmapFactory.decodeByteArray(input , 0, input.length, options);
// resize the bitmap to my desired scale
Bitmap resized = Bitmap.createScaledBitmap(original, 1600, 1200, true);

// create a new byte array and output the bitmap to a compressed JPG
ByteArrayOutputStream blob = new ByteArrayOutputStream();
resized.compress(Bitmap.CompressFormat.JPEG, 30, blob);

// recycle the memory since bitmaps seem to have slightly different garbage collection
original.recycle();
resized.recycle();

byte[] desired = blob.toByteArray();

Then I write out the desired jpg to a file for upload.
Answer: test = testSizes.get(3);
// get(3) is 1600 x 1200

There is no requirement that the array have 4+ elements, let alone that the fourth element be 1600x1200.

1) Figure out how to capture the 1600x1200 size without a crash or streaking

There is no guarantee that every device is capable of taking a picture with that exact resolution. You cannot specify arbitrary values for the resolution -- it must be one of the supported picture sizes. Some devices support arbitrary values, while other devices will give you corrupted output (as is the case here) or will flat-out crash.

2) Figure out how to change the size of the default picture size to a JPG that is 1600x1200

I am not aware that there is a "default picture size", and, beyond that, such a size will be immutable, since it is the default. Changing the picture size is your option #1 above.

3) Something else that is currently unknown to me.

For devices that support a resolution that is bigger on both axes, take a picture in that resolution, then crop to 1600x1200.
For all other devices, where one or both axes are smaller than desired, take a picture in whatever resolution suits you (largest, closest match to 4:3 aspect ratio, etc.), and then stretch/crop to get to 1600x1200.
Comment: What's strange to me is that the 1600x1200 size was listed as a supported picture size but I still got corrupted output. I am unable to stretch or shrink one direction because of vendor requirements (check image capture for deposit). I can crop off the top based on how the user might align the image in the preview window. Would I need to use a bitmap to do image manipulation and then convert to jpg? (By default size I meant the size from getPictureSize() before I changed any settings.)
Comment: @Gravitoid: "What's strange to me is that the 1600x1200 size was listed as a supported picture size but I still got corrupted output" -- that's certainly possible. I usually focus on the highest camera resolutions, and there are definitely devices that report resolutions that give flawed output. "I am unable to stretch or shrink one direction because of vendor requirements" -- then you cannot write your app, because there is no requirement that a camera support **exactly** 1600 or 1200 pixels on any given axis.
Comment: @Gravitoid: Moreover, I am puzzled as to why you are worrying about the "streaking". By your own admission, **your app crashes** on some devices. A streaked image is a positive result by comparison.
Comment: Thanks for the good info. My concern is the crash happens on a Samsung Galaxy S4, a very popular phone, and I'm reluctant to say that phone isn't supported by my app. I would rather find a solution that works for the S4 as well as all the phones that already work. The streaking/corruption is on the Nexus 7 tablet, and, while better than a crash, still not a usable result (I happen to have the Nexus in my possession, but no S4). If I use the highest possible resolution, or the one currently set if it matches a 4:3 ratio, any suggestions on how to get to 1600x1200?
Comment: @Gravitoid: "I'm reluctant to say that phone isn't supported by my app" -- your vendor needs to accept reality, that not every camera will bend to their will. Cropping and/or scaling are simply inevitable. "any suggestions on how to get to 1600x1200?" -- you have to crop or scale, as I covered in my answer. There are `createBitmap()` and `createScaledBitmap()` that can handle this.
Comment: "Some devices support arbitrary values" -- very weird!


Excel/VBA: Skip error and continue w/ code execution

Question: Problem: My macro doesn't do what I want. I have an excel file with multiple columns. What I want is the macro

to look for specific headers (if they exist in the file), then
selects the entire column and
resize it as specified in the script. If the specified header doesn't exist in the file, the code should move on the next one without giving any error.

The code below changes the "Problem Description" size from 50 to 6  although 6 is the size for "Corrective Action Required?" header (which is not applicable in this case as that header doesn't exist and hence the resizing requirement of 6 s/b simply ignored).
But that didn't happened. Instead, the size of previous condition (changing the column size of "Problem Description" to 50 ) did change to 6.
Should I use a different method to write this macro and avoid using OnErrorResumeNext?
Sub Resize_specific_columns_OnErrResNxt()

'
' finds specific columns based on changed header names and resize them

    On Error Resume Next
     Cells.Find(what:="data domain", After:=ActiveCell, LookIn:= _
        xlValues, lookat:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext _
        , MatchCase:=False, SearchFormat:=False).Activate
    ActiveCell.EntireColumn.Select
    Selection.ColumnWidth = 8

    On Error Resume Next
     Cells.Find(what:="eDIM#", After:=ActiveCell, LookIn:= _
        xlValues, lookat:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext _
        , MatchCase:=False, SearchFormat:=False).Activate
    ActiveCell.EntireColumn.Select
    Selection.ColumnWidth = 6

    On Error Resume Next
     Cells.Find(what:="Problem Description", After:=ActiveCell, LookIn:= _
        xlValues, lookat:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext _
        , MatchCase:=False, SearchFormat:=False).Activate
    ActiveCell.EntireColumn.Select
    Selection.ColumnWidth = 50

    On Error Resume Next
     Cells.Find(what:="Corrective Action Required?", After:=ActiveCell, LookIn:= _
        xlValues, lookat:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext _
        , MatchCase:=False, SearchFormat:=False).Activate
    ActiveCell.EntireColumn.Select
    Selection.ColumnWidth = 6

Answer: Here is an example of one of your Finds, you can copy>>paste this method to the other ones.
The recommended way to use a Find is to Set a Range to the Find result, and afterwards you can check if the Range = Is Nothing, which means the Find was unsuccessful finding the text/number you were looking for.
Code
' finds specific columns based on changed header names and resize them
Dim FndRng As Range

Set FndRng = Cells.Find(what:="data domain", After:=ActiveCell, LookIn:= _
    xlValues, lookat:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext _
    , MatchCase:=False, SearchFormat:=False)

If Not FndRng Is Nothing Then '<-- find was successful
    FndRng.EntireColumn.ColumnWidth = 8
End If
Set FndRng = Nothing '<-- clear Range before next Find

Comment: this is so cool! worked like a charm! thank you so much for your prompt answer!
Answer: On Error Resume Next resumes to the next "line", but the 3 lines can be combined into 1:
On Error Resume Next

Cells.Find("data domain").EntireColumn.ColumnWidth = 8

Cells.Find("eDIM#").EntireColumn.ColumnWidth = 6

Cells.Find("Problem Description").EntireColumn.ColumnWidth = 50

Cells.Find("Corrective Action Required?").EntireColumn.ColumnWidth = 6

On Error Goto 0     ' optional if there is more code after that should not ignore errors


export views data to text file in the background

Question: I am using views data export module to generate a text file and that works perfectly. but instead of asking me to save it to my local computer.
What I want to do is save it directly on the server, I would like to run this is the background if possible as large amounts of data take time to generate.
Ideally I would like to run this for each user in the background on cron run so I presume I will need to setup some batch job to run.
Answer: Well, I think you can set a cron job on server. You just need to add a drush command in crontab file. Drush command :
drush views-data-export [view-name] [display-id] [output-file]

Views data export provides this drush command.
Edit :

If you don't have drush installed on your server then you can take the idea from code of views_data_export.drush.inc.

Or :

In simple way you can run the code following in hook_cron :
$output = views_embed_view('ViewName', 'views_data_export_1');
file_unmanaged_save_data($Output , 'private://output.xls', FILE_EXISTS_REPLACE);

As per https://www.drupal.org/node/1875456#comment-7524421.
Comment: I don't have access to drush on the server so i cant do that sadly :(
Comment: @Jerry updated my answer.


what does chord "Co" or "Fo" etc., mean on an accordion

Question: I took accordion lessons 50 years ago, and now I'm trying to re learn everything.
Comment: On the actual accordion, are the "o" actually little circles that are in the upper right, like a degree sign?
Answer: In the following, lowercase chord names stand for actual accordion chord buttons, uppercase names are either regular chord names or single notes.
c° is also known as cdim, the diminished chord.  It's A-C-E♭.  The actual inversion depends on where the Stradella chord octave is located.  This isn't a full diminished chord, of course, but it is nevertheless called that on the accordion.  If you add the proper fifth by playing the two buttons c°+cm, you actually get the chord Cm6.
It's little-known that on accordions with just three chord rows (because of three bass rows and/or a Belgian system, or just five rows anyway) the seventh row isn't F7=E♭-F-A but rather E♭-A-C which is functionally indistinguishable in typical counterbass play involving the F bass button.
So if you don't have a diminished chord row, play f7 instead of c°, b♭7 instead of f°, and c7 instead of g°.  That will be exactly accurate.
Russian 6-row bass bayans actually put the c° chord in the same row as F, making for A-F-f-fm-f7-c° .  That makes it easy to press f7 and c° with the same finger in case you need the full F7 with the fifth included.
Answer: Generally this would be written as a superscript 0 like a degree mark as mentioned above. So you are looking at C° or F°. This represents a diminished 7th chord (missing the fifth). On a Stradella bass accordion, this would be the sixth row.
C° (accordion) would be the notes C, Eb, and A. Stradella bass skips the fifth in the Dominant 7th and diminished 7th chords (to keep the sound balances with the three-note major and minor chords.) The missing F# (or Gb) can be filled by the right hand.
Comment: Also no idea what you're talking about with an Italian augmented sixth. I don't see any connection between either the incorrect C, Eb, Ab you suggest or the C, Eb, A (Bbb) that actually happens on accordion C°.
Comment: My mistake. It is a C, Eb, A chord. The Italian Sixth is the Dominant Seventh (C-E-A# enharmonically C-E-Bb). (I just noticed I described this better for another question.)
Comment: Is that really a C diminished 7th chord? I thought a fully diminished 7th would be Bbb which is also A natural.
Comment: I'm actually disappointed that it's not also/actually the Italian 6th. That would be cool. But maybe not as useful as a diminished 7th. Note that fully diminished 7th chords are root ambiguous (allowing for inversion). In other words, Cdim7, Ebdim7, Gbdim7, and Adim7 all are made up of exactly those four notes.