Custom Editor for a node based on type

Question: Using Drupal 7, I'm working on a module and want to have it so when the module is installed it will set a new node type called "project" When a user is adding/editing a $note->type="project" I want to bring up a custom editor for my module that is for that node type. I have been looking for tutorials for nodes and editors for nodes but I wasn't able to find any good examples of making a custom node type and making and assigning a custom editor for a node type.
I also don't know what hooks I need to use to target the node editor. As of right now I'm following the steps from the following tutorial. http://www.sitepoint.com/creating-a-new-drupal-node-type/
Answer: The WYSIWYG module allows embedding any supported WYSIWYG editor to a field via a hook_form_alter()/hook_form_FORM_ID_alter() invocation. Here's a link to its documentation page. You can alter your custom node type form by altering the its body field #type & #format elements.
Note: To do this it also requires:

The WYSIWYG libraries pre-installed to the sites/all/libraries directory.
A pre-existing WYSIWYG profile created.

As such, you'll need to have add a wysiwyg dependency in your module's .info file and some how do the above work in #1/#2 inside your  hook_install invocation.
Comment: I think i may have described the problem in a way that is hard to understand. I don't want to change a single field. I want to override the entire edit page for the node. I want to make a full editor that shows up for this one type. It will look nothing like the normal editor that has each node field listed one after another. I have used the CKeditor in the past to change the widget for a field what i want to do now is have a full custom editor that will replace the node editor all together for the set node and no other node.
Comment: The `hook_form_alter()` & `hook_form_FORM_ID_alter()` functions will let you add/remove customize form elements as you see fit. You can use `drupal_add_js` & `drupal_add_css` in there to override the default theming if you're looking to present the form in manner different from its default incarnation.
Comment: so everything on that page can be altered by the `hook_form_alter()` & `hook_form_FORM_ID_alter()` hooks?
Comment: will this work if i want to for example a toolbar on a side that has draggable elements into a center section. This would then update the node.
Comment: You can alter all the form elements that will render in the content area of your theme with `hook_form_alter()`. Other parts of theme surrounding the form will stay the same unless you inject other JS/CSS (via `$form['#attached']['js']` & `$form['#attached']['css']`) to manipulate it. Your own limitation is what you're capable of with JS/CSS.

Custom Editor for a node based on type


Output the file name of images using the views_data_export module?

Question: I'm using the https://drupal.org/project/views_data_export module to export a Views list of content as a CSV file.
The content has an image field (multiple values in it) then the CSV data show nothing for the images. I need to output the name of the image file.
I tried adding a Relationship field:  File Usage: File but I get duplicated row (one for each image in each node)
I need to output a CSV file, something like:
<code>TITLE, IMAGES
"my dog title" , "dog-picture-1.jpg, dog-picture-2.jpg"
"my cat title" , "cat-picture-1.jpg, cat-picture-2.jpg"
</code>
How can I sort this out?
Answer: Use Rewrite the output of this field option and add your fields like title, image1, image2.
1). In image1 field, use the rewrite option and use the taken of your image like
[field_gallery_fid]
and set the Group multiple values like below image

2.) In image2 field, use the rewrite option and use the taken of your image like
"[title]" ,"[field_gallery_fid],[field_gallery_fid_1]"
and set the Group multiple values like below image

Note: Suppose if you have 10 images, you can repeat the above steps, but if you have "n" number of images, then it will not work out for you.
Comment: I have "n" number of images. thanks anyway
Answer: You have to install Image URL Formatter

This module add a url formatter for image field. Then you can output image url directly.
Most of the code, maybe more than 90%, is just copy from the drupal core. I think it is stable enough.
I have created a content type, and add an image field instance to it, later I use views to export the data of this content type.And I want to output the data,then I could import it into another drupal 7 site with feeds module. What I need is the URL of the image field, but I could not export the image URL directly. That is why I create this small module.
Comment: Please add some more details about WHY you recommended this module (apart from some module details that Krisna already added, to make it look less like a link-only answer, which often gets deleted by moderation, sinces that's considered as a low quality answer).


Find the value of the integral $I=\int_{-\infty}^\infty e^\frac{-y^2}{2}~dy$ .

Question: $$I=\int_{-\infty}^\infty e^\frac{-y^2}{2}~dy$$
Let $\dfrac{y^2}{2}=z$ ,
$y~dy=dz$
$$I=\int_{-\infty}^\infty\frac{e^{-z}}{\sqrt{2z}}dz$$
Comment: This is a popular integral and has likely been answered on this board before. The solution is also on youtube. edit:http://math.stackexchange.com/questions/429632/gaussian-integral
Comment: http://en.wikipedia.org/wiki/Gaussian_integral
Comment: multiply your integral for $\int_{-\infty}^{\infty}e^{-\frac{x^2}{2}}$ and then use two coordinate transformation
Comment: See also http://www.youtube.com/watch?v=nqNzKeVCYBU :)
Answer: Let $x^2 = y^2/2$, so $\mathrm{d}y = \sqrt{2}\,\mathrm{d}x$
then
$$
\int_{-\infty}^\infty e^{-y^2/2} \mathrm{d}y =
\sqrt{2}\int_{-\infty}^\infty e^{-x^2} \mathrm{d}x
$$
Can you recognize the last integral as the Gaussian Integral ?
Answer: $$I^2=\int_{\mathbb R}e^{-x^2/2}dx\cdot \int_{\mathbb R}e^{-y^2/2}dy=\int_{\mathbb R^2}e^{(-x^2-y^2)/2}dxdy=\\
=\lim_{n\to\infty}\int_{\{x^2+y^2\leq n^2\}}e^{(-x^2-y^2)/2}dxdy=\lim_{n\to+\infty}\int_0^{2\pi}\int_0^ne^{-r^2/2}rdrd\varphi=\\
=2\pi\lim_{n\to+\infty}(-e^{-n^2/2}+e^0)=2\pi.$$ Hence $I=\sqrt{2\pi}.$
Answer: Well, if you know something about distributions then you'll see that $\exp(-y^2/2)/\sqrt{2\pi}$ is the density of the normal distribution which integrates to one, so your answer is $\sqrt{2\pi}$.


Why can't I see  tags added to $form in hook_form_FORM_ID_alter?

Question: I want to modify the $form variable in an implementation of hook_form_FORM_ID_alter but can't seem to be able to set the #prefix and #suffix variables on field widget.
/**
 * @file
 * Implementations Module Hooks
 */

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Alter the node/create form for implementation types
 */
function implementations_form_node_implementation_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $prefix = '
';
  $suffix = '
';

  $form['field_parent_idea']['widget']['#prefix'] = $prefix;
  $form['field_parent_idea']['widget']['#suffix'] = $suffix;

  dpm($form['field_parent_idea']['widget']);
  dpm($form['field_parent_idea']['widget']['#prefix']);
  dpm($form['field_parent_idea']['widget']['#suffix']);
}

When I navigate to node/add/implementation I would expect to see the value of $form['field_parent_idea']['widget'] with the #prefix and #suffix variables set, but instead they're blank. Here's the relevant snippet showing the suffix/prefix values:
[#max_delta] => 0
[#prefix] =>
[#suffix] =>
[add_more] => Array

Why are they blank?
This is the full output of what I see.

Array
(
    [0] => Array
        (
            [target_id] => Array
                (
                    [#title] => stdClass Object
                        (
                            [__CLASS__] => Drupal\Core\StringTranslation\TranslatableMarkup
                            [translatedMarkup:protected] =>
                            [options:protected] => Array
                                (
                                )

                            [stringTranslation:protected] => stdClass Object
                                (
                                    [__CLASS__] => Drupal\Core\StringTranslation\TranslationManager
                                    [translators:protected] => Array
                                        (
                                            [30] => Array(1)
                                        )

                                    [sortedTranslators:protected] => Array
                                        (
                                            [0] => Drupal\Core\StringTranslation\Translator\CustomStrings
                                        )

                                    [defaultLangcode:protected] => en
                                    [_serviceId] => string_translation
                                )

                            [string:protected] => @title (value @number)
                            [arguments:protected] => Array
                                (
                                    [@title] => Parent Idea
                                    [@number] => 1
                                )

                        )

                    [#title_display] => invisible
                    [#description] =>
                    [#field_parents] => Array
                        (
                        )

                    [#required] => 1
                    [#delta] => 0
                    [#weight] => 0
                    [#type] => entity_autocomplete
                    [#target_type] => node
                    [#selection_handler] => default:node
                    [#selection_settings] => Array
                        (
                            [target_bundles] => Array
                                (
                                    [idea] => idea
                                )

                            [sort] => Array
                                (
                                    [field] => _none
                                )

                            [auto_create] =>
                            [auto_create_bundle] =>
                            [match_operator] => CONTAINS
                            [match_limit] => 10
                        )

                    [#validate_reference] =>
                    [#maxlength] => 1024
                    [#default_value] =>
                    [#size] => 60
                    [#placeholder] =>
                )

            [_weight] => Array
                (
                    [#type] => weight
                    [#title] => stdClass Object
                        (
                            [__CLASS__] => Drupal\Core\StringTranslation\TranslatableMarkup
                            [translatedMarkup:protected] =>
                            [options:protected] => Array
                                (
                                )

                            [stringTranslation:protected] => stdClass Object
                                (
                                    [__CLASS__] => Drupal\Core\StringTranslation\TranslationManager
                                    [translators:protected] => Array
                                        (
                                            [30] => Array(1)
                                        )

                                    [sortedTranslators:protected] => Array
                                        (
                                            [0] => Drupal\Core\StringTranslation\Translator\CustomStrings
                                        )

                                    [defaultLangcode:protected] => en
                                    [_serviceId] => string_translation
                                )

                            [string:protected] => Weight for row @number
                            [arguments:protected] => Array
                                (
                                    [@number] => 1
                                )

                        )

                    [#title_display] => invisible
                    [#delta] => 0
                    [#default_value] => 0
                    [#weight] => 100
                )

        )

    [#theme] => field_multiple_value_form
    [#field_name] => field_parent_idea
    [#cardinality] => -1
    [#cardinality_multiple] => 1
    [#required] => 1
    [#title] => Parent Idea
    [#description] =>
    [#max_delta] => 0
    [#prefix] =>

    [#suffix] =>

    [add_more] => Array
        (
            [#type] => submit
            [#name] => field_parent_idea_add_more
            [#value] => stdClass Object
                (
                    [__CLASS__] => Drupal\Core\StringTranslation\TranslatableMarkup
                    [translatedMarkup:protected] =>
                    [options:protected] => Array
                        (
                        )

                    [stringTranslation:protected] =>
                    [string:protected] => Add another item
                    [arguments:protected] => Array
                        (
                        )

                )

            [#attributes] => Array
                (
                    [class] => Array
                        (
                            [0] => field-add-more-submit
                        )

                )

            [#limit_validation_errors] => Array
                (
                    [0] => Array
                        (
                            [0] => field_parent_idea
                        )

                )

            [#submit] => Array
                (
                    [0] => Array
                        (
                            [0] => Drupal\Core\Field\Plugin\Field\FieldWidget\EntityReferenceAutocompleteWidget
                            [1] => addMoreSubmit
                        )

                )

            [#ajax] => Array
                (
                    [callback] => Array
                        (
                            [0] => Drupal\Core\Field\Plugin\Field\FieldWidget\EntityReferenceAutocompleteWidget
                            [1] => addMoreAjax
                        )

                    [wrapper] => field-parent-idea-add-more-wrapper
                    [effect] => fade
                )

        )

    [#after_build] => Array
        (
            [0] => Array
                (
                    [0] => Drupal\Core\Field\Plugin\Field\FieldWidget\EntityReferenceAutocompleteWidget
                    [1] => afterBuild
                )

        )

    [#field_parents] => Array
        (
        )

    [#parents] => Array
        (
            [0] => field_parent_idea
        )

    [#tree] => 1
)

At first I thought that the issue was because I was setting on a nested array variable, but that's exactly what the example code in the documentation does.

function hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if (isset($form['type']) && $form['type']['#value'] . '_node_settings' == $form_id) {
    $upload_enabled_types = \Drupal::config('mymodule.settings')
      ->get('upload_enabled_types');
    $form['workflow']['upload_' . $form['type']['#value']] = array(
      '#type' => 'radios',
      '#title' => t('Attachments'),
      '#default_value' => in_array($form['type']['#value'], $upload_enabled_types) ? 1 : 0,
      '#options' => array(
        t('Disabled'),
        t('Enabled'),
      ),
    );

    // Add a custom submit handler to save the array of types back to the config file.
    $form['actions']['submit']['#submit'][] = 'mymodule_upload_enabled_types_submit';
  }
}

Answer: For some reason dpm() fails to show #prefix & #suffix values, bug maybe? Use kint() instead. You'll need to enable the Kint module if you're using Devel 8.x-2.1. But if using Devel 4.0.1 you'll need to install kint via composer require kint-php/kint.
Dump aside, Drupal automatically strips the style= for security reasons.
Instead, it should be
$prefix = '
';

 Note: Assuming you're using the default Seven theme as admin theme. Otherwise, you would have to add this class to your admin's theme CSS and hide it.

The more Drupally correct way is to use hidden
$form['field_parent_idea']['widget']['#type'] = 'hidden';

Another way is to set #access to false, but you won't be able to change the value via JavaScript as the field doesn't get printed to the page.
$form['field_parent_idea']['widget']['#access'] = FALSE;

Comment: I'll accept 'downside', but this is how it's *always been when using dpm() or even just var_export() in drupal_set_message(). I tested it too, before I posted: `dpm(['#prefix' => '']);` will display just ```Array
(
    [#prefix] =>

)``` in the message area, but if you look at the page source you will see the "" like I said. This is how HTML works - if you try to print an HTML tag, the browser interprets it as HTML. (*always meaning since at least Drupal 5 ...)
Comment: Drupal isn't the issue here. The poster is setting a PHP array value like this: `$form['field_parent_idea']['widget']['#prefix'] = $prefix;` immediately followed by `dpm($form['field_parent_idea']['widget']['#prefix']);`. Drupal doesn't process that value at all, there's no sanitation involved and the Form API doesn't come into play. This is purely PHP. And of course it should display the value. The problem here is that the expectation is wrong - if #prefix is a `` tag, what should you expect to see when that value is rendered on an HTML page? Nothing. Which is exactly what happens.
Comment: **Note** If all of the above still fails, then you need to [increase your modules weight](https://drupal.stackexchange.com/questions/186506/how-to-reduce-increase-modules-weight-on-the-module-install-process) as there is another custom or contrib mudule altering the same field; thus, you'll want your module's alter hook to execute after/last.
Comment: I'm going to mark this as the answer as it helped me realise both why the original `div` changes weren't working, but also pointed me in the right direction regarding hiding the element at the hook level. Note that the solution ended up being `$form['field_parent_idea']['#type'] = 'hidden';` rather than modifying the widget element, but that might be a field-specific thing.
Comment: Yes, this answer is relevant to what I called the second problem "the form is not visibly altered as you expect". If you get to the point where you are modifying the correct form and adding the #prefix, then 'style' is not something that will work. But as to what I called the first problem, this is not a bug with dpm().
Comment: @anonymous `this is not a bug with dpm()` it is a bug or downside of dpm(), I tested it myself it's not speculation. It prints `#prefix` empty with `dpm()`.
Answer: There are two basic problems here. First, your debug output doesn't display what you expect, and second the form is not visibly altered as you expect.

dpm() displays the output in the messages area of the page. What you are trying to display is an array containing an HTML tag as one of its values - that value will be interpreted as an HTML tag when shown in the messages area.
 produces no visible output, which is why you think those array elements are "blank". But if you look at the page source you will see the
. Try using a regular non-HTML string as #prefix and #suffix and you will see this string in the output from the dpm(). First problem solved.

You're altering $form['field_parent_idea']['widget'] but you don't show us what that form element is. Not all form elements respect #prefix and #suffix, so without knowing the element we don't know what to expect. Indeed, your verbose output looks like you're using a custom #theme function, so it's even less clear what we expect to see. It's highly likely that your theme function is ignoring what you put into #prefix and #suffix.

When doing something like this for the first time, it's best if you start off with some simple things and get those working first. Have you successfully used hook_form_FORM_ID_alter() elsewhere? Try just changing the form title, for example, and see if you can get that to work. Try adding a #prefix to the "Title" textfield and get that to work. Taking these little steps and getting them to work will help you get past all the little things like function naming and form ID naming etc. THEN you can move on to some complex form element with its own #theme function. You probably have to theme that complex form element by overriding the template, not by adding a #prefix and #suffix. Or, if this really is a field widget, then by writing your own custom widget.
Comment: `Not all form elements respect #prefix and #suffix` this is incorrect. **[#prefix](https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7.x#prefix) accepts all elements.** Perhaps you confused it with **[#field_prefix]**(https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7.x#field_prefix)**
Comment: @No Sssweat Yes I agree that it doesn't appear to be the problem for the specific case of an entity reference field, it was just a potential problem and a starting point for debugging the issue. As I said there were two problems which were confusing the poster. Once the first was sorted then it appears the second was easily fixed by removing the 'style' as you recommended. That would not necessarily be sufficient in every case, but it was the correct answer here for the second problem.
Comment: If I inspect the html I see this for the prefix/suffix tags: `[#prefix] =\u0026gt; \u003Cdiv\u003E\n    [#suffix] =\u0026gt; \u003C\/div\u003E\n` so I think you're right regarding the first point, thanks for that! Regarding the 2nd point, the form element `parent_field_idea` is a Autocomplete custom field which reference content types. I'm not using any custom themes (just the default one from drupal).
Comment: @quant I can tell you're using an entity reference field based on the `target` in the dump. I was able to replicate your issue, for whatever reason `dpm(` shows empty but when using `kint(` it shows up. I guess its a bug of dpm. [My answer](https://drupal.stackexchange.com/a/297340/27710) has the correct solution.
Comment: No, I really mean #prefix and #suffix do not work, and certainly do not work the same, for all render elements. The fundamental problem is that these are defined on the RenderElement class, but each individual form element does NOT inherit all the capabilities of the parent RenderElement because the Form API is built on associative arrays, NOT on classes, so it's up to each individual element implementation to properly handle everything defined by the parent class. And that does not always happen.
Comment: @anonymous that doesn't appear the problem here, my answer still works on an entity reference field which appears to be what the OP is using.


What are the units of entropy of a normal distribution?

Question: I have a random process that follows a normal distribution. It's parameters are mean = 35 units, std.dev. = 8 units. I've seen from the wiki entry for the normal distribution that there is a formula to calculate the entropy. So plugging in the figures as:-
$$
    .5\log\left(2\pi e^1 8\cdot 8\right)
$$
I get a value of 1.52, which I take to be  per sample.  My question is what are these units?  What thing do I have 1.52 of?
Information entropy is (typically) measured in units of bits, after Claude Shannon's definition.  So can I take it that each sample generates 1.52 bits of entropy?  Clearly recording those samples generates information and therefore occupies a real and discrete amount of storage space. Ergo entropy cannot be unit less.
Comment: entropy is unitless
Comment: However the $\sigma$ may be in meters. Do we have something like $\log $ square meters?
Comment: You link to information entropy, which is shannon entropy, that is, the discrete case. You ask about entropy for the normal distribution, that is differential entropy, something entirely different.
Comment: Yes, unless you meant something else by "unit"
Comment: The point is that shannon and differential entropy has very different properties and must be treated separately
Answer: Shannon entropy is normally given "units" of bits or nats in information theory. Information theory includes the measurable concept of compression. Define a compression ratio as (ADC sample size) / (Shannon entropy of sample set). The numerator and denominator would both be described as "number of bits". The Shannon entropy of the sample set gives the smallest average number of bits per sample which could be achieved by entropy coding the sample set, such as using Huffman's approach. This context justifies applying the term "bits" to Shannon entropy. Note that the term entropy used in thermodynamics should not be confused with Shannon entropy used in information theory.
Answer: @Aksakal gave the answer in comments, entropy is unitless.  Still, there are some details to elaborate.  First, sometimes units are given as "nats" or "bits", for the cases of use of natural logs/binary logs, respectively.  But these are not really measurements units (like meter, kg, ...) in the physical sense, it corresponds more to writing the measurement in decimal or binary number systems.  A measurement of length in meters can be written in decimal or binary, that does not really change the unit of measurement of length used. The unit is meter in both cases.
Some details:  We treat Shannon (discrete) and differential (continuous) entropy separately.
$$ \DeclareMathOperator{\E}{\mathbb{E}}
   H(X) = -\sum_x p(x) \log p(x) = -\E_X \log p(X)
$$
where $p$ is the probability mass function of a discrete random variable. Then
$$
   H_d(X) = -\int f(x) \log f(x) \; dx = -\E_X \log f(X)
$$
where $f$ is the probability density function of a continuous random variable.  Now, from general principles the unit of measurement of the expectation (mean, average) of a variable (random or not) is the same as the unit of measurement of the variable itself.  This leaves us with the unit of measurement of $\log p(x), \log f(x)$ respectively. Again, from general principles (see lognormal distribution, standard-deviation and (physical) units  for discussion and references) the arguments of transcendental functions like $\log$ must be unitless.  That rises a problem, while $p(x)$ certainly is unitless, since probability is an absolute number, the density $f(x)$ measures probability pr unit of $x$, so if unit of $x$ is $\text{u}$, then unit of $f(x)$ is $\text{u}^{-1}$.  So, for the equation defining differential entropy $H_d$ to be dimensionally correct, we must assume the argument to log contains a "hidden" constant with numerical value 1 and unit $\text{u}$. But the conclusion follows, that both Shannon and differential entropy is unitless.  Still, one must remember that differential entropy scales with the unit of measurement of $X$, as discussed in https://en.wikipedia.org/wiki/Differential_entropy
Comment: But Shannon entropy is measured in bits, and absolutely not unit less.  I'm not sure where you get your idea of what it is, but Shannon (who invented information entropy) says it's measured in bits as he wrote in his _A Mathematical Theory of Communication_ paper.
Comment: Paul is absolutely right: the proof that entropy does have a unit lies in how it transforms when the base of the logarithm is changed.  The logarithm of the base is the scale of the unit.  Trying to dismiss that as "merely a description" misses the fact that this transformation rule forcibly demonstrates the entropy cannot be unitless.
Comment: Did you read my answer? Bits and nats is mentioned, as "units", but they are really only a description of the base of logs used. You can compare it with "radians", used as name of a unit , angle measure, but as angle measure is a quotient of two length, is really unitless. Bits, nats, like radians, is not a true unit like meter is
Comment: Here http://mathforum.org/library/drmath/view/64034.html is a link to a good discussion of the "parallell" issue of the unit of measurement of angles, as radians.
Comment: @whuber so the unit of the entropy comes from the log term? But third answer of this post https://math.stackexchange.com/questions/238390/units-of-a-log-of-a-physical-quantity argued that given log x is the sum of x raised to different power, how do we make sense of the unit of log(x)?
Comment: @Sam That answer assumes the *only* possible base of the logarithm is the natural logarithm.  The present question concerns how the result transforms when the natural logarithm is replaced by a different logarithm.


Object-fit doesn't work with fixed width and height

Question:

.block {
  width: 500px;
  height: 300px;
}

img {
  max-width: 100%;
  object-fit: contain;
}

In my opinion, the picture should shrink to fit into the block, but this does not happen. Why?
Answer: specify your image to the block
specify both height and width:
width: 100%;
height: 100%;

use object-fit: cover or object-fit: fill

.block {
  width: 500px;
  height: 300px;
  border: 1px solid black;
}

.block img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}


Find a whole number that is both perfect square and cube found between 2000 and 10000

Question: "Identify a whole number that is both perfect square and cube found between 2000 and 10000?"
Can somebody help me. I am stumped on this question and I have a test tomorrow.
Comment: Such a number must be a sixth power. Now, $$4^6=4096$$
Answer: If a number is both a perfect square and a perfect cube, it must be a sixth power. Now, $5^6 = 15625$ and $3^6 = 729$. So, the only possible number is $4^6 = 4096$.
Comment: Answer faster than me by a second haha.
Comment: Why must it be of the 6th power?
Comment: @SparticusEDM Suppose $n = a^2 = b^3$. Then $n$ is both a perfect square and perfect cube. This also implies that $a = b^{\frac{3}{2}} = b * b^{\frac{1}{2}}$ but, $b^{\frac{1}{2}}$ is not a whole number unless $b$ is a perfect square. If $b$ is a perfect square, then $n$ must be a 6th power.
Comment: So to be both a perfect square and a perfect cube will a number always be a sixth power?
Comment: @SparticusEDM Correct


Use the form of Green function to prove Harnack's inequality

Question: An exercise unsolved.
The complete question is: Let $u(x)$ be a harmonic function defined on the unit ball, with boundary condition: $u(x) = g , x\in\partial\Omega$. Let function $G$ be the Green function on unit ball. Then try to use the equation: $$u(x) = -\int_{\partial\Omega}u(y)\frac{\partial G}{\partial\boldsymbol{n}_y}(x,y)\,dS_y , x\in\Omega$$ to prove Harnack's inequality again.

Harnack's inequality: If $u(x)\in C^2(\Omega)$ is a non-negative harmonic function defined on $\Omega\subset\mathbb{R}^3$, then for any $\Omega'\subset\subset\Omega$, there exists constant $C = C(\Omega, \Omega')>0$ such that $$\frac{1}{C}u(y)\le u(x)\le Cu(y) , \forall x,y\in \bar{\Omega}'$$

I have computed the specific formula of $u(x)$: $$u(x) = \frac{1 - |x|^2}{4\pi}\int_{\partial B_1}\frac{g(y)}{|x-y|^3}\,dS_y$$ And I don't not how to continue.
Answer: I will continue with what I understand to be your assumption, that $\Omega$ is specialised to the unit ball in three dimensions. Then given $\Omega' \subset\subset \Omega$ there is some $r<1$ such that any $x\in \overline{\Omega'}$ must satisfy $\lvert x \rvert \le r$. Consequently for $x,y\in \overline{\Omega'}$,
\begin{eqnarray*}
  u(x)&=&\frac{1-\lvert x \rvert^{2}}{4\pi}
          \int_{\partial B_{1}} \frac{g(z)}{\lvert x - z \rvert^{3}} d S_{z}\\
      &\le& \frac{1}{4\pi}
            \int_{\partial B_{1}} \frac{g(z)}{\left(1-r\right)^{3}} d S_{z}
            = \frac{\left(1+r\right)^{3}}{4\pi \left(1-r\right)^{3}}
            \int_{\partial B_{1}} \frac{g(z)}{\left(1+r\right)^{3}} d S_{z}\\
  &\le& \frac{\left(1+r\right)^{3}}{4\pi \left(1-r\right)^{3}}
            \int_{\partial B_{1}} \frac{g(z)}{\lvert y-z\rvert^{3}} d S_{z}
        = \frac{\left(1+r\right)^{2}}{ \left(1-r\right)^{4}}\,
        \frac{1-r^{2}}{4\pi}
        \int_{\partial B_{1}} \frac{g(z)}{\lvert y-z\rvert^{3}} d S_{z}\\
  &\le& \frac{\left(1+r\right)^{2}}{ \left(1-r\right)^{4}}\,
        \frac{1-\lvert y \rvert^{2}}{4\pi}
        \int_{\partial B_{1}} \frac{g(z)}{\lvert y-z\rvert^{3}} d S_{z}
        = \frac{\left(1+r\right)^{2}}{ \left(1-r\right)^{4}} u(y).
\end{eqnarray*}
Comment: Great Work! Thank you Ali


A circle's sine wave is an ellipse's...

Question: We all know what a sine wave is, and how it relates to a circle.
What is the vertical and horizontal distance when I take a point and drag it along the perimeter of the ellipse?
It definitely has to be a sinusoidal function, as an ellipse is a closed conic, much like the circle...
Comment: $x = a\cos\theta$ and $y = b\sin\theta$, for an ellipse centered at the origin, with semi-major axis $a$, semi-minor axis $b$.
Answer: If you drag your point so that the angle to the origin increases at a constant rate, then @wltrup's comment gives you the answer.
If, on the other hand, you drag it at a constant speed (as if you were in a car driving along the ellipse at a steady 30 MPH), then $x$ and $y$, as functions of time, are fairly complicated. Note that if you're on a circle, "constant speed" and "constant angle change" are the same concept, so it's not clear, from your question, which one you wanted generalized.
If, instead of driving on an ellipse, you were driving on a leminscate (sort of a figure-8 kind of curve), it'd turn out that it's pretty difficult to write down the position as a function of time. But there's a remarkable thing: your position at time $2t$, is closely related to your position at time $t$. For the circle, the corresponding question would be "are the sine and cosine of $2\theta$ related to the sine and cosine of $\theta$?", and the answer, as you may know, is this:
Yes, they are, for
$$
\sin(2\theta) = 2 \sin \theta \cos \theta\\
\cos(2 \theta) = \cos^2 \theta - \sin^2 \theta,
$$
i.e., the coordinates of the second point can be written as polynomial expressions in the coordinates of the first point.
For the lemniscate, it turns out that the coords of the second point can be written as rational functions of the coords of the first point. Fagniano discovered this, told Euler about it, and Euler generalized out of all proportion and more or less invented Algebraic Geometry. (Or at least that's the story I got from a professor at Princeton about a million years ago when I was a ugrad there.)
So: your very simple question, or something quite like it, was the source of a major development in mathematics a few hundred years ago. Pretty neat, eh?
Comment: Thank you for the insight, Professor Hughes!
Answer: Since I came here in search of a steeper sine wave, I'll answer that:
y=sin((pi/2) sin(x))

That one was a bit squarish for my needs, I found you can keep a nice curve on it and still bring it back to the -1 and 1 boundaries by nesting sine waves within each other.
sin(sin(sin(x))) / sin(sin(1))

The logic I eventually figured out was this: we want the angle to change at a faster rate when it's not near pi/2 and 3pi/2, which is what a sine-wave does. So, if we did sin(sin(x)), that would cause it to move faster near the x axis. But that also means it only has values between -1 and 1, and and sin(1) doesn't get us to pi/2, so the height of our sine wave is diminished. It will never be higher than sin(1)~0.84, so we divide by sin(1) to stretch it vertically so that it's previous highest and lowest values get stretched to 1.

A circle's sine wave is an ellipse's...


If $S=1+\frac{1}{\sin x}+\frac{1}{\sin^2x}+...$ what's the measure of angle $x$?

Question: If $S=1+\dfrac{1}{\sin x}+\dfrac{1}{\sin^2x}+...+\dfrac{1}{\sin^n x}+...=\dfrac23,$ what's the measure of angle $x$?
We have an infinite geometric series with first term $a_1=1$ and common ratio $q=\dfrac{1}{\sin x}$. Then $$S=\dfrac{1}{1-\frac{1}{\sin x}}=\dfrac{\sin x}{\sin x-1}=\dfrac{2}{3}\iff3\sin x=2\sin x-2\iff\sin x=-2, $$ which has no solutions. Am I making a silly mistake somewhere?
Comment: Hint: what can be said about $q$ if $|\sin x|\leq 1$?
Comment: @Yalikesifulei, I am not sure. Can you further clarify for me?
Comment: The equation is not right: $S=\frac {1-\frac 1{\sin^{n+1}x}}{1-\frac 1{\sin x}}=\frac 23$.
Comment: @WindSoul Even if it were a finite series, you'd want that exponent to be $n+1$.
Comment: @J.G., can you show me how from $-1\le\sin x\le1$ I can make a statement for $\dfrac{1}{\sin x}$? I really cannot see it.
Comment: Hint: what if $-1\le\sin x<0$? What if $\sin x=0$? What if $0<\sin x\le1$?
Answer: This is a divergent serie.$|\sin(x)|\leq 1$ so the reciprocal is greater or equal to 1.
If you consider for example $\sin(x)=\dfrac{1}{2}$ you have $\dfrac{1}{\sin(x)}=2$
And the series became: $1+2+2^2+2^3+2^4+...\to\infty$
Answer: Assuming that the geometric series
$$
S(x)=1+\sum_{n=1}^{\infty}(\sin x)^{-n} \tag{1}
$$
converges, the OP showed that it equals $\frac{2}{3}$ if $\sin x=-2$. On the other hand, as
already explained by others, the series diverges if $x$ is real, for $|\sin x|\leq 1$. Now, although $\sin x=-2$ has no real solution, it has complex solutions. Indeed, if we write $x=u+iv$, where $u$ and $v$ are real, then$^{(*)}$
$$
\sin x = \sin(u+iv) = \sin u\cosh v + i\cos u \sinh v, \tag{2}
$$
hence
$$
\sin x = -2 \iff
\begin{cases}
    \sin u\cosh v = -2, \\
    \cos u\sinh v = 0.
\end{cases} \tag{3}
$$
One can easily check that $(3)$ has the following solutions:
\begin{align}
u&=-\frac{\pi}{2}+2n\pi\quad(n=0,\pm1,\pm2,\ldots), \\
v&=\cosh^{-1}(2)=\pm\ln(2+\sqrt{3}), \tag{4}
\end{align}
therefore $S(x)=\frac{2}{3}$ at the "angles" $x=(-\frac{\pi}{2}+2n\pi)\pm i\ln(2+\sqrt{3})$ $(n=0,\pm1,\pm2,\ldots)$.

$^{(*)}$https://en.wikipedia.org/wiki/Trigonometric_functions#In_the_complex_plane


HTML sendo construido antes de retorno da api em Angular

Question: Quero receber dados da minha API e construir cards com eles dinamicamente, para isso estou usando o 'binding' do Angular, porem meu HTML está sendo construído antes da resposta estar concluída, com isso ela é vista como undefined. Já tentei usar promises, mas sem sucesso, também tentei usar ngIf para que só gerasse os cards quando minha variável tivesse valor, outra vez sem sucesso.
Service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { IDisciplina } from 'src/app/shared/models/IDisciplina';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class DisciplinaService {

  private UrlBase = 'http://localhost:5000/api/disciplina';

  constructor(private http: HttpClient) { }

  getDisciplinaById(Id: number): Observable<IDisciplina[]>  {
    return this.http.get<IDisciplina[]>(`${this.UrlBase}/${Id}`);
  }

  getDisciplinaByTurma(TurmaId: number): Observable<IDisciplina[]>  {
    return this.http.get<IDisciplina[]>(`${this.UrlBase}/getByTurma/${TurmaId}`);
  }

}

component.ts
import { Component, OnInit } from '@angular/core';
import { DisciplinaService } from 'src/app/core/services/Disciplina/Disciplina.service';
import { IDisciplina } from 'src/app/shared/models/IDisciplina';

@Component({
  selector: 'app-Home',
  templateUrl: './Home.component.html',
  styleUrls: ['./Home.component.css']
})
export class HomeComponent implements OnInit {

  DisciplinaPorTurma: IDisciplina[];

  constructor(private disciplinaService: DisciplinaService) {}

  ngOnInit() {
    this.ReceberDisciplinas();
    console.log(this.DisciplinaPorTurma);
  }

  ReceberDisciplinas() {
    this.disciplinaService.getDisciplinaByTurma(2).subscribe(
      (Disciplina: IDisciplina[]) => this.DisciplinaPorTurma = Disciplina,
      error => console.log('Falha na chamada. Erro: ' + error),
      () => console.log('Chamada a API finalizada!'));
  }

}

HTML
<app-toolbar Titulo="UnipClassroom" LadoDireito="Henrique de Castro"></app-toolbar>

  <app-spinner></app-spinner>

        <mat-card class="tamanho-card margin-card mb-4">
          <mat-card-header>
            <mat-card-title>{{Disciplina.Nome}}</mat-card-title>
            <mat-card-subtitle>{{Disciplina.CursoId}}</mat-card-subtitle>
          </mat-card-header>
        </mat-card>

Comment: Ao invés de dar um **subscribe** no serviço em `HomeComponent.ts`, atribui a variável **DisciplinaPorTurma:** como sendo do tipo **`Observable`** e no loop do `Html` deixa com um **pipe async** assim **`*ngFor="let Disciplina of DisciplinaPorTurma | async"`**
Comment: Eu obtive dois erros ao fazer isso.
Primeiro no subscribe:
"Type 'IDisciplina[]' is missing the following properties from type 'Observable': _isScalar, source, operator, lift, and 5 more.ts(2740)"

A segunda foi com o pipe:
" InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'"
Answer: você estava na direção certa. O detalhe que o nosso amigo disse de usar o pipe async é válido. A primeiro momento é um pouco confuso mesmo, mas vamos lá. Primeiramente altere o tipo do seu atributo para um observable
DisciplinaPorTurma$: Observable<IDisciplina[]>;

Após isso altere o seu método de consulta para:
ReceberDisciplinas() {
   this.DisciplinaPorTurma$ = this.disciplinaService.getDisciplinaByTurma(2);
}

Inclusive essa abordagem é uma boa prática para evitar possíveis vazamentos de memória (memory leak).
Feita essas alterações no seu arquivo ts, agora é só adicionar o pipe async no seu template.

Para facilitar o entendimento, montei um exemplo no stackblitz


Bayesian approach to inference. Why do we pick specific values as our hypothesis?

Question: So say I'm dealing with M&M. I have 5 M&Ms and one of them is yellow. I want to know if the true proportion of M&Ms in the entire bag is 10% or 20%.
In the frequentist approach, my hypothesis would be:
H0: P = 10%
H1: P > 10%
However, in the Bayesian approach, I would say:
H0: P = 10%
H1: P = 20%
Philosophically, why is this?
Updated question
I'm going to attempt to solve this using the Bayesian approach. What am I missing?
Say our priors are:
P(H1) = 0.5
P(H2) = 0.5
$P(k = 1 | H1) = 0.33$ (I used binomial distribution)
$P(k = 1 | H2) = 0.41$ (I used binomial distribution)
So,
P(H1 | k = 1) = $\frac{0.5 * 33}{0.5 * 33 + 0.5 * 0.41} = 0.45$
P(H2 | k = 1) = $0.55$
So we choose H2.
Comment: Just an observation: you can test $H_0 : p=10\%$ against $H_1 : p=20\%$ using classical/frequentist methods. In fact, when both the null and the alternative are simple, there is a most powerful test available (which would probably have great appeal to a classical/frequentist statistician): https://en.wikipedia.org/wiki/Neyman%E2%80%93Pearson_lemma
Comment: This is not correct: a Bayesian analysis can evaluate any (point or compound) hypothesis against any (point or compound) hypothesis.
Answer: It's not a matter of philosophy, it's wether we get where is bayesian inference being done.
Remember that under bayesian inference estimates come from the posterior distribution.
In your problem the bayesian approach does not limit you on what type of hypothesis test you want to make. What limits you is wether your hypothesis statements make sense in relation to the posterior distribution.
For instance if your posterior is absolutely continous, making statements suck as $H_0 = k$ does not make any sense. This is because to make bayesian hypothesis tests you simply have to compute the probability of the $H_0$ statement from the posterior and atoms under continous distributions have 0 probability.
As for what your particular problem concerns, you can still test the simple vs compound case.
From your question I can see $P(H_0) = .45$ this is $H
_0: p = .1$, it is clear that $P(H
_1) = .65$ where $H_1: p > .1$ (this a kolmogorov axiom of probability), then you reject $H
_0$


Está Selecionando todos  com condicional Styling (React)

Question: Estou Com problema , estou desenvolvendo uma lista de tarefas em React , só que na hora de sublinhar tarefas , ele sublinha todas até as que não estão marcadas no checkbox
abaixo vou disponibilizar o código e o repositório do GitHub
Github: https://github.com/sajous/Lista-De-Tarefas
import { Button, Checkbox } from "@mui/material";
import React from "react";
import { useState, useEffect} from "react"
import { FaTrash , FaEdit} from 'react-icons/fa'
import './home.css'

export const Home = (props :any) => {

    const [item, setItem]:any = useState('');
    const [itemList, setItemList]:any = useState([])
    const [check , setCheck] :any = useState()

    const addItem = () => {
        if( item.length === 0) return;
        setItemList([item].concat(itemList))
        setItem('')
    }

    const handleKeyPress = (e:any) => {
        if(e.key === 'Enter'){
            if(e.currentTarget.value.trim().length === 0) return;
            setItemList([item].concat(itemList))
            setItem('')
        }
      }

      const teste =(e:any) =>{

        setCheck(!check)
      }

    return(

Minhas Tarefas

      <input type="text" placeholder="Item" value={item} name="item" onChange = {e => setItem(e.target.value)} onKeyDown={handleKeyPress} />
        <Button variant="text" className="Button" onClick={addItem}>➕</Button>

        {itemList.map((item:any, index:any) => (

<Checkbox checked={check} onChange={teste} inputProps={{ 'aria-label': 'controlled' }} /><div id={index} className={`sublinhado ${check ? 'sublinhado-activate' : 'sublinhado-desactivate'}`}>{item}
<FaTrash /> <FaEdit />

        ))}

    )

}

.container{

    background-color: #e3e3e3 ;
    margin: 10px 200px;
    padding-bottom: 50px;
    box-shadow: 1px 1px 5px 1px;
}

h1{
    padding-top: 50px;
    text-align: center;
}

input {
    text-align: center;
    border: none;
    outline: none;
    background-color: #fff;
    border-radius: 5px;
    padding: 10px;
    width: 50%;
    margin-left: 23%;
    box-shadow: 1px 1px 4px 1px ;
    font-size: 20px;

}

li {
    list-style: none;
    text-decoration: none;
    margin-top: 4px;
    margin-right:10px;
    box-shadow: 1px 1px 5px 1px;
    border-radius: 5px;
    margin-left: -30px;
    padding-top: 0px;
    padding-bottom: 10px;
    background-color: #fff;
    font-size: 25px;

}

a {
    text-decoration: none;
    color: #000000;
    float: right ;
    margin-right: 20px;
    margin-top: -40px;
    margin-bottom: 20px;
}

.sublinhado-desactivate{
    text-decoration: initial;
    text-align: center;
}

.sublinhado-activate{
    text-decoration: line-through;
    text-align: center;
}

Answer: O problema é que você está selecionando a classe nas
 de acordo com o valor "check" do estado. Quando você clica em qualquer checkbox, o valor de "check" vira "true", e é aplicada em todas as tags
 a classe 'sublinhado-activate'.


Showing that $\lim_{x\to c} f(x) > \alpha \Rightarrow f(c+h) > \alpha$ for $|h| < \delta $ where $\delta > 0 $

Question: The question is as follows :

Let f : (a,b) $\to \mathbb{R}$ and c $\epsilon$ (a,b) be such that $\lim_{x\to c}  f(x) > \alpha$. Prove that there exists some $\delta > 0 $ such that $f(c+h) >\alpha $ for all $|h| < \delta $

I have taken a rather lengthy approach of splitting it into 9 different cases as follows, but I am happy about my method.
Case 1 : monotonically increasing
Case 2 : monotonically decreasing
Case 3 : constant function
Case 4 : x is a point of minima
Case 5 : x is a point of maxima
Case 6 : constant function to the left of x = c and increasing to the right of x = c
Case 7 : constant function to the right of x = c and increasing to the left of x = c
Case 8 : constant function to the left of x = c and decreasing to the right of x = c
Case 9 : constant function to the right of x = c and decreasing to the left of x = c
I have managed to prove all cases but case 5 with ease.
I am unsure of how to proceed with a formal proof of case 5.
For all other cases I have used the basic definitions of increasing/decreasing/constant.
Can someone guide me how to proceed with proof of case 5 ?
Comment: Look at $y=x\sin(1/x)$ around $0$ (the function has "infinite oscillation" about 0).
Comment: Your cases are not exhaustive. Regardless, there is no need to consider different cases; just use the definition of limit. Start by taking  $\epsilon=L-\alpha$, where $L$ is the value of your limit.
Comment: Also, you need $h$ non-zero here...
Comment: Amazing !! A huge shout out to you @DavidMitra. Thanks you so much ! I was thinking what to do with the gap between f(c) and alpha and you're like take $\epsilon = L - \alpha$. Too good !
Comment: @DavidMitra why are my cases not exhaustive though ?
Answer: By limit definition $\forall \epsilon>0, \exists \delta>0, |x-c|<\delta \implies |f(x)-L|<\epsilon$. By hypothesis, we are given $L>\alpha$.
$L-\epsilon<f(x)<L+\epsilon$, rewriting the limit definition as a compound inequality.
So:
$L-\epsilon-\alpha<f(x)-\alpha<L+\epsilon-\alpha$.
Select $\epsilon<L-\alpha$. Then we guarantee $f(x)-\alpha>0$ for some $\delta$ and $c-\delta<x<c+\delta$ by the earlier statements. This inequality still holds for $c-h<x<c+h, |h|<\delta$ since it overlaps.


Location within form

Question: I am learning jazz standards, and wonder if anyone could offer advice on maintaining awareness of location within the form of the song, especially while improvising.
I have been trying to envision both the melody while comping chords and  to "hear" the chord tones while playing the melody, essentially visualizing the lead sheet and imaging the chord structure.
It's just very slow going, and I'm looking for tips.
Answer: This is really just practice and practice. What you need to do is to play the melody so many times that you'll hear it in your head nonstop. The same with the chord changes. Just play them over and over again. What might also help you is to listen to the song again again.
Keep in mind that this might take some time. Especially for inexperienced musicians, it might be hard to stay focused when they try to think the melody in their heads. But don't give up; we've all been there.
Comment: Although I keep hoping there's a shortcut, I think I'm resigned to the fact that the answer is just to play more.  There are certainly worse remedies!  Thank you for your answer.
Answer: There's the oft-quoted II-V-I, or ii-V-I sequence that occurs frequently in jazz (and lots of other music). Try to find those parts in each song, and once you do, at least the next couple of chords will be in a familiar pattern for you.
Another thing to try, in the initial stages (and for a bit of fun later) is to keep to one key. This way, you'll see the same little sequences far more easily. And it'll make your transposition better, too, both on instrument and on paper.
As Shev says, keep the melody and chord sequence in your head, because at the end of it all, that's what the song is, and both will merge in different ways as you improvise. Again, keeping to one key might give you chance to use specific sets of notes - provided you choose songs that don't modulate much, and so stay in a key longer.
Try just changing the timing of the melody line in some, so the same notes are used - maybe swapping some notes round in given bars. It's pretty safe, and will usually work.
Comment: Thank you for your thoughts, and I think these are good suggestions for improvising over the song.  I like the idea of changing the melody rhythmically, and the ii-V-I is certainly a sequence to have lodged in one's ears.  While excellent thoughts on improvisation, I think I am looking more for tips on how to keep track of where I am as the songs moves along.  I very much appreciate your consideration.
Comment: @user24766 - generally songs will rather like poems - they can be portrayed as lines, usually 4 bars long. This means that if a song is written out in poetry style, there'll be lines of 4 bars, so a 12 bar long song will have 3 lines. The beginning of each line will be fairly obvious musically. Visualising this should help keep you on track.
Answer: When playing over changes, the two most important notes of the chord are the 3rd & the 7th.
If your instrument doesn't require your feet, try tapping out playing the 3rd &/or 7th (any combo) when tapping your left foot on beats 1 & 3. When you practice soloing try landing on one of those chord notes on the 1st/3rd beat throughout the form. Begin by just playing any 2 notes (as long as the 1st/3rd beat is the 3rd/7th chord note.Work your way up to playing scales/chords/patterns over the changes then try playing what you hear in your head still aiming to hit those notes on the 1st/3rd beat.
As a bonus, you will find yourself playing more 'sweet' notes during your solos. I have found no better or faster way to hear & learn a tune. Well thought-out practice is the price we all must pay in order to express ourselves through our horns...good luck to you.

Location within form


Substituir aplicativo Android já publicado

Question: Fala pessoal!
Estou começando a programar através do Android Studio, porém depois da última atualização o aplicativo que desenvolvi apresentou uma série de erros e tentando acertar estes erros acredito que tenha mais atrapalhado do que ajudado. Como já havia publicado este aplicativo na Play Store, gostaria de saber se tem como iniciar um novo projeto e substituir o aplicativo já publicado.
Answer: Sim, você pode fazer isso mas ter dois requisitos:

Tem que ser o mesmo package do projeto anterior, o package é usado como identificador do seu aplicativo, então se ele mudar o google play vai entender que é um app diferente.
Tem que usar o mesmo certificado para assinar o app, ou seja quando você gerar o build do projeto você tem  que usar o mesmo certificado que usou antes. Guarde com cuidado o certificado pois se você perder ele não vai ser possivel enviar atualizações do app para a loja.

Tenha em mente que para você vai ser um app diferente mas se seguir essas regras para a google play vai ser so uma atualização do app
Comment: Muito obrigado!


How to reduce the number of variables in cluster analysis?

Question: I've got 10 (yes, only 10) cases over 1000 variables (e.g. measurements of concentrations of 1000 different compounds at 10 different time points).
I can group these cases into 3 clusters in 1000-dimensional space (complete linkage, cluster sizes 3, 3, and 4). This partitioning agrees with my expectations, but the clusters are not very well-defined. I suspect that some variables give no or little information, some are noise, and some others are responsible for this particular partitioning. I would like to find out the latter ones, that is, to reduce the number of variables (e.g. to 100-200), so that the cases are partitioned into the same 3 clusters, and these clusters are significantly better defined than the original ones (e.g. by silhouette coefficient).
This should be a subset of the original variables, not some new unobserved ones.
I have the following ideas:

Go through the variables one-by-one and compare cluster solutions in each 1-dimensional space to the original solution. Keep only those variables which produce similar results. Not sure if this would work.
Go through all the variables in original solution and remove one whose deletion results in the maximum increase in some kind of goodness measure like silhouette coefficient, repeat.
Attempt to find out those variables which are responsible for most of the variation, e.g. by doing a multidimensional scaling into a few dimensions, and then fit this back into original 1000 dimensions using procrustes rotation, keeping the ones which fit better. This would only work if only a few variables are responsible for the variation, as I understand.
Delete variables with lowest predictor importance?

Would any of this work? Should I try anything else?
Answer: The problem with dimensionality reduction and number of variables >> number of observations is that the $k$ observations that you have define an at most $k-1$ dimensional hyperplane on which the objects perfectly are located on.
So yes, anything more than 9 dimensions still has proven redundancies.
Many dimension reduction techniques - in particular PCA, SVD, but probably also MDS etc. - will essentially try to preserve this hyperplane.
Don't you have a way to reduce the number of dimensions that uses domain information that you have? I.e. if you know that your dimensions are expected to be highly correlated, remove dimensions that are the most correlated (pairwise is probably best). But note that even correlation is not very stable to compute when you have just 10 observations. You lose one degree of freedom for the mean, for example, which you can't really afford.
Comment: Unfortunately I don't have much domain information, rather, I am trying to gain it by finding out which variables produce this particular effect. The only thing that I expect a priori is that their amount is about 100-500, not 3 or 5. I am also not sure I'd want to remove the ones which are highly correlated, unless they affect the goodness of my clustering negatively.
Comment: If they don't affect it positively, you can remove them safely. They can be irrelevant but not harm easily, just by having a very low magnitude.
Answer: Here's something else you can try.
This data is similar to what they see in genomics, so you could look to that field for ideas of analysis.  In genomics there are lots of variables (20,000+), many of which are highly correlated with each other, and a relatively small number of rows.
If this were a genomics problem, 5 of your rows would be healthy controls and 5 would have some kind of malady and you'd want to find the genes (variables) which help you identify the disease - i.e. feature selection is the main problem.
In your case if you don't know that some of your rows are "good" and some is "bad", you could still use a technique that is good for datasets like this - a random forest.
R's randomForest library does unsupervised clustering.  In a nutshell, it will combine your 10x1000 matrix with another 10x1000 matrix consisting of random noise.  It then tries to build a model to differentiate between your matrix and the noise.
If you do know some of the rows are "good", then you could still use randomForest - just use it in "supervised" mode.
Regardless, a nice "side effect" of a random forest is you could then examine the importance() of each variable - a variable's importance is measured by averaging its performance across all the trees in used in the random forest.
You could sort this list in descending order of importance, take the top x number of variables, and consider these to be the ones accounting for the most variance in your matrix.
You'd also want to check out the importance metric itself - plot it maybe.  If it's flat across the entire range of variables, then no one variable(s) is more predictive than any other.  But if, as you suspect, some variables account for more variance, you should see a scree type plot.
I love Random Forests.  They are really fast and "embarassingly parallel".  They have a weakness of over emphasizing discrete variables with lots of values (e.g. State).  That doesn't seem to apply here.
EDIT:
Link to Breiman's site.  A pretty good explanation.
Comment: @dan - I had never heard of the Boruta package - it uses the randomForest package with some added on logic.  I'm going to check it out - thanks for the tip!  For your problem, you can still use randomForest in supervised mode with a formula like "ClusterId ~ ." - i.e. predict the Cluster using all the other variables.  Then you can examine the importance().  You might need to convert your ClusterId to a string so that randomForest can figure out that you want to do Classification Tree and not Regression Tree (it'll do both).  I hope this helps...
Comment: @Wake2Sleep - thanks! i do indeed get some results when using ClusterId~. with Boruta or just analyzing importance() of randomForest. However, they are not what one would expect. the "important" variables are mostly the ones with low observed values (concentrations), which thus do not affect clustering significantly. if one throws them away, the clustering remains the same. so they are not "important" as per my understanding of the word. Of course, one could throw away the variables with low observed values before clustering, but one wonders what is the sense of using this method then...
Comment: @Wake2Sleep - so I don't quite understand whether it's this method which for some reason is not appropriate for this particular task, or is it me who cannot interpret the results correctly. In my book "important" variables are the ones which produce (ideally) the same clustering of observations as the whole set of variables, and removing them breaks this clustering altogether. Boruta thinks it has found the important variables, but they behave differently.
Comment: the idea of using random forest for clustering is really nice. just a question though: how will it interpret if in the "original matrix" one of the variable has a constant value ? Won't it appear as one of the rules, and that variable as one of the important one to distinguish our data from random noise ?
Comment: Thanks for the idea. My rows (observations) are partitioned not into 2 ("good" and "bad"), but into 3 clusters, and I want to keep the variables which distinguish between them (that is, keeping these variables and discarding others results in clusters becoming tighter and better separated). So I have a 10x1000 data frame and a vector of length 10 specifying which cluster does which case belong to. What would the 'formula' or 'response vector', which randomForest needs, be in this case?  ..Isn't this also similar to what Boruta package does, using randomForests?
Comment: @cafe876 - not my idea!  All credit goes to Leo Breiman.  I will edit and add a link.
Comment: @cafe876 - Sorry forgot to answer your question - I would guess that yes, a constant would show up as very important.  As always, it's up to the analyst to make sense of what the computer is telling us.
Answer: You could try transposing the data and computing principal components to see which cases load on which components. It might be necessary to rotate the results to get clearer clusters, but ideally you could end up with three good components with each representing the groups you are expecting. Even if that doesn't work, you could then use the principal component scores to cluster your compounds into a smaller number of groups and select the compound closest to the centroid in that group to represent the group.
Comment: could you elaborate, please? if I compute princomp() on a transposed 10x1000 matrix, I get 10 components, of course. which ones would be 'good'? I also see that the resulting biplot produces 10 vectors which are grouped together in about the same way as the original observations are clustered.
How do I find the centroids of the respective groups?
thanks!
Comment: The number of components to use depends on the eigenvalues each component. A sharp drop in the eigenvalue indicates that the remaining components carry very little information. I was expecting that you would get about 2-4 "good" components and that 2-4 of your 10 cases would have high loadings on each of the "good" components. Without seeing the results, it is impossible to tell.
Comment: It sounds like you have recovered the pattern you expected in two components. I was expecting 3 since you have three groups, so look at that third eigenvalue. The "distance" matrix here is the covariance (or correlation) matrix. So the clusters are defined by groups of variables with high correlations not by Euclidean distance. Do the points (concentrations) on the biplot show any clustering?


C# erro no evento dymamico botao click

Question: Ao clicar no botao dynamico do evento click tiles , o mesmo abre varios sites carregados do arquivo settings.ini ... no caso deveria abrir um por um relativo ao nome e link mas abre todos ao mesmo tempo.
Obs: estou usando MetroTiles como botoes (Componentes MetroFramework).
Meu arquivo settings.ini
  [bot]
  b00=Debian
  b01=Mineos
  b02=Utorrent
  b03=Debian Apache Web Server
  b04=Debian Mysql Web Server
  b05=Ez Monitor
  b06=Netdata

  [web]
  h00=https://debian:10100/
  h01=https://debian:8443/
  h02=https://debian:8080/gui/
  h03=http://ccstudio.zapto.org/
  h04=http://debian/phpmyadmin/
  h05=http://debian/app/cc/linux/eZ/
  h06=http://debian:19999

Meu código
      //TILES ADD

        for (int i = 0; i < 15; i++)
        {
            var a = new IniFile("Settings.ini");
            var b = new MetroTile();
            var c = new MetroLabel();

            b.Height = 50;
            b.Width = 100;

            b.Margin = new Padding(5, 5, 5, 5);
            b.Click += new EventHandler(b_Click);
            b.MouseEnter += new EventHandler(b_Move);
            b.Text = a.Read("b0" + i . ToString(), "bot");
            //c.Text = a.Read("h0" + i . ToString(), "web");
            //c.Hide();
            b.UseCustomBackColor = true;
            b.BackColor = GetRandomColor();
            flowLayoutPanel1.Controls.Add(b);
           /// flowLayoutPanel1.Controls.Add(c);
        }

    }
    private void b_Click(object sender, EventArgs e)
    {
        var a = new IniFile("Settings.ini");
        for (int i = 1; i < 11; i++)
        {

            Process.Start(a.Read("h0" + i.ToString(), "web"));
        }
    }

Comment: Que erro que aparece ?
Comment: abre todos links ao clicar no 1º botao  (no caso) , e não um link a cada botão
Answer: Seu código está fazendo exatamente o que deveria, embora não seja o que você quer. Perceba que no evento Click dos Tiles, você percorre o IniFile inteiro e abre cada um dos links.
Pelo que eu entendi, você quer que cada Tile abra um link associado à ele. Há várias maneiras de fazer isso, mas o mais simples para o seu caso é o seguinte: ao invés de usar o mesmo evento para todos os Tiles, associe um evento diferente para cada um, já no momento da criação.
Veja o código. Removi as outras partes para que fique mais fácil para você visualizar a alteração.
for (int i = 0; i < 15; i++)
{
    var a = new IniFile("Settings.ini");
    var b = new MetroTile();

    // ... //

    var link = a.Read("h0" + i.ToString(), "web");
    b.Click += (obj, args) => Process.Start(link);

    // ... //
}

Comment: Vitor agradeço pela resposta ,mas o erro continua ainda pior agor aque fiquei perdido de vez obj,args  no visual C# pediu para criar um private EventHandler obj; foi criado mas diz que o args soh como statments
Comment: Estava faltando os parênteses no código. Já editei a resposta caso queira utilizá-la.
Comment: seu esta correto tambem ! era o que eu precisa Obrigado
Comment: a Proposito como seria for (int i = 0; i < 15; i++) para que lesse a quantidade de nomes no aqruivo settings ayutomaticamente no lugar do 15 seria uma leitura automatica do settings ini a quantidade se nomes ja salvos ....
Comment: Não sei qual classe `IniFile` você está usando. Dê uma olhada na documentação dela ou poste outra pergunta.
Comment: meu aqruivo ini usado é desta pagina
https://stackoverflow.com/questions/217902/reading-writing-an-ini-file
The tiny class
Answer: Eu atribuiria o link na propriedade Tag do Tile  e depois pegaria pelo sender que disparou o evento:
{
    for (int i = 0; i < 15; i++)
    {
        var a = new IniFile("Settings.ini");
        var b = new MetroTile();
        var c = new MetroLabel();

        b.Height = 50;
        b.Width = 100;

        b.Margin = new Padding(5, 5, 5, 5);
        b.Click += new EventHandler(b_Click);
        b.MouseEnter += new EventHandler(b_Move);
        b.Text = a.Read("b0" + i . ToString(), "bot");

        b.Tag = a.Read("h0" + i . ToString(), "web"); //atribui o link na tag do tile

        //c.Text = a.Read("h0" + i . ToString(), "web");
        //c.Hide();
        b.UseCustomBackColor = true;
        b.BackColor = GetRandomColor();
        flowLayoutPanel1.Controls.Add(b);
       /// flowLayoutPanel1.Controls.Add(c);
    }

}
private void b_Click(object sender, EventArgs e)
{
       Process.Start( ((MetroTile)sender).Tag.ToString() );
}

Comment: só uma observação, você pode declarar `var a = new IniFile("Settings.ini");` fora do loop, pois será igual em todas as iterações, evita esse "desperdício"  .
Comment: Obrigado este Resolveu agora funciona botao por botao !
Comment: @carloscoelho que bom, não esqueça de marcar como resposta! obrigado
Comment: a proposito como faria para ler a quantidade de nomes no aqruivo ini e usa-la aqui for (int i = 0; i < 15; i++) ao invez de 15 colocaria  o valor que ele leu dos nomes adicionados automaticamente
Comment: teria que ver sua classe que está lendo o ini, e certamente teria uma Lis<> com cada item do ini, abre uma pergunta com essa situação, para verificarmos melhor

C# erro no evento dymamico botao click


How to create internal and external links

Question: In drupal 4.x, in contents, links are created like this
[url=1]Some text[/url]
So when "Some text" click it open node 1.
Sometime it may link to external url also. like below:
[url=http://www.abc.com/somepage.html] external link [/url]
same thing how can i do it in drupal 7.x
Answer: To be honest, I don't know anything about Drupal 4.  I don't regard it as a platform to build on in 2014.
In Drupal 7, out of he box, you create links using plain HTML:
internal link
external link

There are a bunch of modules for Drupal 7 you can install that gives you other syntaxes for adding links to content. To mimic the square brackets around tags syntax you cite as example. Install the Bbcode module.  It uses markup based upon BBCode.  For a more modern style, similar to StackExchange, install the Markdown filter module. It let content authors use markup based upon John Gruber's Markdown.
Answer: If I understand your question correctly, then you need way to differentiate internal URL with External URL and there is way out.
If you want to give internal link just give like 'node/' in href where if you want to connect link with external URL, give full URL like 'http://www.google.com'.
Now, if you have question how drupal will recognize it, we have module extlink (https://drupal.org/project/extlink) which does that job.
hope this answers give you what you seeking for.


How to display the portfolio of a specific type?

Question: I am using webphysiology_portfolio plugin in my wordpress website.
This plugin have the portfolio types.
When I user this short code <code>[webphysiology_portfolio]</code> , It displays all portfolios on the page.
But I want to display the portfolios of a specific type.
So what is the short code I will use for this?
Thanks in advance.
Answer: Here's an example taken from: http://webphysiology.com/plugins/webphysiology-portfolio-plugin/#portfolio
<code>[webphysiology_portfolio portfolio_type=red]
</code>
Here's a screenshot taken from the same page:


How can I get rid of unsought data?

Question: I've written some code in python to scrape some titles and content under each titles. The scraper is doing fine except for the last container. I expect to parse fields from each container other than the last one. Here I used the word container to mean fieldset tag and the content within it. However, what can i do to get rid of the data from the last container and continue parsing data from the other ones using css selector, I repeat css selector?
Here is what I tried with:
from lxml.html import fromstring
import requests

res  = requests.get("http://www.webscantest.com/").text
soup = fromstring(res)
for data in soup.cssselect("fieldset"):
    title = data.cssselect("legend")[0].text
    content = [item.text.strip() for item in data.cssselect("a")]
    print(title,' '.join(content))

To shake off the data from the last container where div tag is noticed, I used selectors like this for data in soup.cssselect("fieldset:not(div)"): but still the same. However, I could have used for data in soup.cssselect("fieldset")[:-1]: to get the desired results but the container I wanna get rid of needs not to be in the last position always or they may recur several times within.
Here are the elements within which the data I'm after are located (first two are identical but the last one contains div tag):
<fieldset>
    <legend>JS tests:</legend>
        SOAP SPA page
        REST SPA page
        ReactJS test page
</fieldset>

<fieldset>
    <legend>JS tests:</legend>
        SOAP SPA page
        REST SPA page
        ReactJS test page
</fieldset>

<fieldset>
    <legend>Basic tests:</legend>

            <select name="redirect" onchange="javascript: gotoselect();">
                <option value="pickone">Pick a category </option>
                <option value="hrs">HTTP Response Splitting Tests</option>
                <option value="payment_analysis">Parameter Analysis Tests</option>
            </select>

        OS Command Inject Tests
        Java Grinder Tests
        Directory Browse Tests
        Resource Finder Tests
</fieldset>

Comment: lxml can also use `xpath`, or you only want `css`?
Comment: @eLRuLL , right you are. I'm only after any solution from css selector.
Answer: you can also use xpath with lxml, and it comes useful on this case, your code should looks like this:
from lxml.html import fromstring
import requests

res  = requests.get("http://www.webscantest.com/").text
soup = fromstring(res)
for data in soup.xpath("//fieldset[not(div)]"):
    title = data.cssselect("legend")[0].text
    content = [item.text.strip() for item in data.cssselect("a")]
    print(title,' '.join(content))

Only the elements without a direct div child will be matched.

How can I get rid of unsought data?


Will memory upgrade cause downtime on highly available Cloud SQL Postgres?

Question: We've a highly available Google Cloud SQL (PostgreSql 14) instance with decent traffic. If we increase the memory configuration, will it cause any downtime on reads/writes?
Will it trigger a fail-over, or will both the master and fail-over instances restart at the same time, causing a complete downtime?
Comment: Why not just ask your Google support line?
Answer: Changing/Upgrading the memory involves similar operations to changing vCPUs. It typically takes less than five minutes of downtime.
However, as the FAQ mentions, for large, heavily used instances, downtime can be up to an hour.

You could also check out this article. Hoping that this can help you upgrading your memory.


Singular Value Decomposition Column Space and Row Space

Question: I was listening to a lecture by Gilbert Strang and he said that in a SVD, the columns of $U$ are in the column space of $A$...
$$
\begin{aligned}
  A &= U \Sigma V^T \\
  AV &= U \Sigma
\end{aligned}
$$
so we can clearly see by this calculation that U is a combination of the columns of $A$, but then he said that $V$ was in the rowspace of $A$ which I was having a hard time justifying because he did not give an explanation for it. If I try the same thing I see
$$
U^TA = \Sigma V^T
$$
does multiplying from the left give a combination of the rows? or is there another way to justify this?
Comment: Taking the transpose of both sides of $A = U \Sigma V^T$ shows that $A^T = V \Sigma^T U^T$. This reveals that the columns of $V$ are in the column space of $A^T$.
Comment: ah ok that makes sense. Thanks. If you post as an answer ill accept it
Answer: You can transpose both sides of your equation $U^T A = \Sigma V^T$ to see that
$$
A^T U = V \Sigma^T.
$$
This shows that the columns of $V$ are in the column space of $A^T$.


How to use a JSF component in JavaScript

Question: I have the following javascript in a JSF page. Its basically using <h:outputText> statement in javascript if condition::

but I have the following error at the console::
SyntaxError: expected expression, got '<'
The < in <h:outputText> statement is causing the syntaxError problem.
I thought surrounding the javascript code with /* <![CDATA[ */ and /* ]]> */ will  solve it but it didn't.
How do I fix it?
Comment: That is a different thing... What I proposed was a 'narrow down your problem'... Indicating that the error you get is not jsf related. And adding such a tag in a javascript if statement is very weird anyway. That part looks like an http://xyproblem.info
Comment: replace `` and you have the same error. Not jsf related, not java related
Comment: @Kukeltje  what do you mean by replacing it with . How do i get my bean statement "searchListbean.displayPrintPopup" executed in the condition?
Comment: JavaScript is a language. ```if ()``` is not JavaScript. How does that HTML tag get there and why?
Comment: Try to simply use `#{searchListbean.displayPrintPopup}` (EL expression) instead of ``
Comment: CDATA only works around data, not around code. It doesn't change the way that JavaScript is read.
Comment: @JasperdeVries: good catch... I was totally on the wrong foot...
Comment: @JasperdeVries You can use your comment as answer so that i can accept it as the correct answer
Answer: The JSF component will not be rendered within a

See also:

How to pass backing bean value to JavaScript?


Robust correlation in python?

Question: Is some kind of robust (especially to outliers) correlation methods easily available in python? I have a suspicion that outliers might be causing false positives in my data.
Answer: Scikit-learn has an implementation of RANSAC and Theil-Sen regression, both commonly used robust estimation methods. You could also fit a linear model via stochastic gradient descent and choose to optimize a loss function like the Huber loss or \epsilon-insensitive loss, both of which would lead to a robust model.
Once you've fit your model using whatever method you like, you can compute the Pearson correlation on your data using your linear model.
Hope that helps!
Comment: Thanks! I would appreciate a more elaborate explanation on how to use a model to compute correlation...
Comment: Sure, you can compute it from the R^2 value. Sklearn has a scoring function to compute the [coefficient of determination, or R^2](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.r2_score.html#sklearn.metrics.r2_score). This is useful because the [coefficient of determination is the square of the Pearson correlation](https://en.wikipedia.org/wiki/Coefficient_of_determination).
Comment: Thanks again! I made it work - there is even a method `score` of the model object I could use. But is there a way to get a p-value for this correlation?..
Comment: Anyways, seems like I didn't need to worry about this issue, the values with Theil-Sen are in most cases very close to Pearson. However for the future I would be happy to have a p-value estimate too :)

Robust correlation in python?


Major difference between Angular 1.2.x vs Angular 1.6.x version

Question: I want to know the major difference between these versions like angular 1.6 supports UI router for routing and in angular 1.2 we have to use ng-route for routing
Comment: That's what the changelog is for: https://github.com/angular/angular.js/blob/master/CHANGELOG.md. The only different you list isn't correct. ui-router is not part of angular, and you can use it with whetever version of angular (provided its version is compatible).
Comment: AngularJS V1.2 is the last to support IE8. For more information, see [AngularJS Version Support Status](https://docs.angularjs.org/misc/version-support-status).
Answer: I would advise you to look at the post from Todd Motto :
https://toddmotto.com/angular-1-6-is-here
He is an Expert Developer at Google and covers every changes that happens in the Angular Stack.
Actually, you shouldn't only look at the changes from AngularJs 1.2 to 1.6 because between every minor version brings a slight change/approach to the framework.

FYI, the versionning notation correspond to : Major.Minor.Revision.

However, here is a list of notable changes between 1.2 and 1.6 :

angular.component() + lifecycle hooks
ngAnimate (ngAnimateSwap..)
Service / Factory
ngRoute

Also, Here is the official documentation that list every changes between minor version migration : https://docs.angularjs.org/guide/migration
Comment: I'm not looking for migration. I'm actually preparing a document where I have to specify why not to use Angular 1.2, as we are using an additional framework on top of Angular called westUI and higher version of Angular say 1.3 or 1.6 doesn't support WestUI.    I'm proposing a new approach all together where WestUI is out of concept.
Comment: @NikitaJain i need to do something similar in my company regarding upgrading angularjs 1.2 to 1.7, any chance you can share your findings?


I need to keep element reference to pass on

Question: When the user clicks on  tag it calls a function like the following:
;

This function generates HTML for a modal that needs to reference the first button.
func1(elem) {
  html='
' +
  ''+
  '
';

}

When the link inside the modal is clicked, func2() should save text into a data attribute inside the first link, but this is not working, returning:

"Uncaught SyntaxError: Unexpected identifier "
Comment: Where do you expect `e` to be defined? Technically you could use `onclick="func2(event.srcElement)"`, since `event` is defined in string-evaled event handlers, but this approach is considered bad practice and should be avoided.
Answer: First, don't use inline HTML event handling attributes (onclick, onmouseover, etc.), here's why.
But, your actual problem is that you are not properly declaring your function.
This:  func1(elem)
Needs to be this:  function func1(elem)
Next, you  elements must have some content for someone to see and click on and they must then be closed, which you didn't have.

function func1(elem) {
  html='
' + 'click me too'+ '
';
  document.body.innerHTML += html;
}
click me

If you rework your answer to use modern standards, the proper modern way to do this would be:

// Get references to DOM elements
var a1 = document.getElementById("firstAnchor");
a1.addEventListener("click", func1);

// Callback for first link:
function func1(e) {
  // Store original source element
  var src = e.srcElement;

  // Formally create new elements and configure them
  var d = document.createElement("div");
  d.classList.add("modaldiv");

  var a = document.createElement("a");
  a.href = "#";
  a.textContent = "Click me too!";
  // By hooking up to a wrapper function, we can have that function
  // pass arguments to the actual callback function:
  a.addEventListener("click", function(){
    func2(src);
  });

  // Add new elements to the document
  d.appendChild(a);
  document.body.appendChild(d);

}

function func2(firstSrc){
 console.log("func2 invoked and e.srcElement from first link is: ", firstSrc);
}
click me
Comment: Note that if you were to define `func2()`, you get `Uncaught ReferenceError: e is not defined` like I pointed out in comments. Perhaps you should address that too?
Comment: @PatrickRoberts I was working on an update to my answer, but had to take a phone call.
Comment: Sorry, didn't mean to make you feel rushed or anything. Very thorough answer now~
Comment: Hi scott,
Thank you for your answer, but the errors you pointed out like no keyword function. I do found the information about not using inline event handlers very usefull, thanks for that. The code was just to illustrate my need. Emphatizing the real problem is on how to pass somekind of reference to a dom element
Comment: @DiegoLeitão I'm not sure what you mean by *" but the errors you pointed out like no keyword function"* and my answer does show how to pass a reference to a DOM element.


Do I need to place a physical server/host within the DMZ to host servers/applications?

Question: We are moving to a new office, and part is to review our current LAN/WAN and server access to/from the web.
I understand how the DMZ works, but can't figure out if I need a physical server/host to be placed between my 2 firewalls, or I can do with subnetting/vNic the DMZ and the servers/virtual servers with vNic.
Today we have a single router and single firewall. Which behind it are all our servers, application servers, DC, VM hosts etc.
I have 2 applications today (on virtual servers), that are accessible from the web (firewall hole punches). Both do NOT use AD credentials, and are working with local DB users (remove the need for AD credentials).

Both are virtual servers in (currently) 1 of 3 VM Hosts.
I want to move these 2 applications into the DMZ.
That will require at least an IIS as well.

Placing a physical VM Host server that has 2 NIC's seems bit weird (that host will hold as many servers/applications servers that I need)

it's a single point of fail
and doesn't feel right (even though it can/should work)

and on the other hand, I can create a vNic in one of my hosts, and mapping it's IP to both Firwalls.
router > wan_firewall_dmz > vNic to server > dmz_firewall_lan > gives me less feeling of the security that the prior option does, and for some reason, I have a feeling I "miss" the DMZ idea.
Is that correct?
What is it that I am missing?
Comment: This is tough to follow. Why would you put a server between the two? Would you use it as a router? I'd recommend making a Visio drawing of the proposal with labels for all of the devices and uploading it.
Comment: Props to @voretaq7 for the edit and the question-coaching. :)
Comment: Not a router, updated Q with servers needed.
Answer:
Do I need to place a physical server/host within the DMZ to host servers/applications?

"Maybe" -- it depends on your level of paranoia / trust in virtualization.
If you're implementing a new DMZ the usual way to go about it would be to carve out a separate vLAN and put the DMZ subnet in it, creating effectively a virtual switch for your DMZ.
If you trust your virtualization software to not screw up vLANs you can create a virtual switch on your VM Hypervisor, drop it into the DMZ vLAN, and connect the hosts you want to isolate to that virtual switch.
You can assign the virtual switches to individual physical NICs (sending untagged traffic with the switch ports dropped into the appropriate vLAN), or with most VM systems you can connect the hypervisor to a "trunk port" on your switch and send all the vLAN traffic to your switch tagged and let the switch sort it out.
Single points of failure would be eliminated in the usual way (link aggregation, virtual machine failover appropriate to your hypervisor, etc.), and your overall maintenance burden shouldn't increase at all -- setting up the vLANs is a one-time thing.
Answer: You do not need a physical host in your DMZ. You can accomplish this with VLAN definition, or preferably, dedicated physical network interfaces (pNICS) from your virtual environment to your DMZ network.


Close all open files handles with C#

Question: I have an integration/regression test suite I built on top of SpecFlow (which uses NUnit underneath).  The problem I am having is that sometimes there is an exception in a test and a file might remain open.  This is a problem in follow on tests because they cannot read/write to this file.
Is there a way to detect what files a process has open and then close them all?
Comment: Yup, you detect it by opening the file.  You'll get an IOException.  No, closing a file owned by another process is not supported, Windows honors a request to not let *anyone* mess with a file.  Stop the process.
Answer: You should put your files in using blocks so that they are closed even if an exception is thrown.
Comment: @Jeffrey: It depends on the situation.
Comment: I know about using statements and I usually do use them, but there are times when using blocks don't make sense.  What do I do in those cases?
Answer: You should close the handles by either disposing them(best done with the using clause) or waiting for the finalizer. Finalizers probably won't work well for you since they might not run before the next test. So disposing them with either try...finally or using is the way to go.
While you can enumerate handles and close them, you should not. Since then the handle might be closed twice, which will cause undefined behavior and crashes.
Here is some Delphi sample code enumerating all handles of a process which you can filter down to file handles only:
program HandleEnum;

{$APPTYPE CONSOLE}

uses
  windows,
  SysUtils;

function EnablePrivilege(const Priv:String):boolean;
var
  rl: Cardinal;
  hToken: Cardinal;
  tkp: TOKEN_PRIVILEGES;
  p:^token_privileges;
begin
   p:=nil;
   result:=true;
   if Win32Platform <> VER_PLATFORM_WIN32_NT then exit;
   result:=false;
   if not OpenProcessToken(GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, hToken)
     then exit;
   if not LookupPrivilegeValue(nil, Pchar(Priv), tkp.Privileges[0].Luid)
     then exit;
   tkp.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;
   tkp.PrivilegeCount := 1;
   AdjustTokenPrivileges(hToken, False, tkp, 0, p^, rl);
   if GetLastError <> ERROR_SUCCESS then exit;
   result:=true;
end;

const  SystemHandleInformation     = 16;
       STATUS_INFO_LENGTH_MISMATCH =  4;
       htProcess                   =  5;
Type _SYSTEM_HANDLE_ENTRY=packed record
  OwnerPid:Cardinal;
  ObjectType:Byte;
  HandleFlags:Byte;
  HandleValue:word;
  ObjectPointer:Pointer;
  AccessMask:Cardinal;
 end;
Type _SYSTEM_HANDLE_INFORMATION=packed record
  Count:Cardinal;
  Data:array[0..0]of _SYSTEM_HANDLE_ENTRY;
 end;
function GetProcessId(Process:Cardinal):Cardinal;stdcall;external 'Kernel32.dll';
function NtQuerySystemInformation(
  SystemInformationClass:Cardinal;
  SystemInformation:Pointer;
  SystemInformationLength:Cardinal;
  ReturnLength:PCardinal
):Cardinal;stdcall;external 'ntdll.dll';

function GetModuleFileNameExA(
  hProcess:Cardinal;
  hModule:Cardinal;
  lpFilename:PChar;
  nSize:Cardinal
):Cardinal;stdcall;external 'Psapi.dll';

function EnumProcessModules(
  hProcess:Cardinal;
  lphModule:PCardinal;
  cb:Cardinal;
  lpcbNeeded:PCardinal
):BOOL;stdcall;external 'Psapi.dll';

procedure Enum(ProcID:Cardinal=0);
var RetLength:Cardinal;
    Status:Cardinal;
    Data:^_SYSTEM_HANDLE_INFORMATION;
    i:integer;
    hProcess,hDuplicate,PID,hModule,Temp:Cardinal;
    s:String;
begin
 EnablePrivilege('SeDebugPrivilege');
  Data:=nil;
  try
    RetLength:=0;
    GetMem(Data,sizeof(_SYSTEM_HANDLE_INFORMATION));
    Status:=NtQuerySystemInformation(SystemHandleInformation, Data, sizeof(_SYSTEM_HANDLE_INFORMATION), @RetLength);
    writeln(Status);
    FreeMem(Data);
    Data:=nil;
    GetMem(Data,RetLength);
    Status:=NtQuerySystemInformation(SystemHandleInformation, Data, RetLength, @RetLength);
    if Status<>0 then Raise Exception.create('Handle enumeration: NtQuerySystemInformation returned '+inttostr(Status));
    writeln('Offset ProcID, HandleID, HandleFlags, Mask, HandleType');
    for i := 0 to Data.Count-1 do
     begin
      if data.data[i].OwnerPid<=4 then continue;//System
      SetLastError(0);
      if Data.Data[i].ObjectType<>htProcess then continue;
      hProcess := OpenProcess( PROCESS_ALL_ACCESS, TRUE, Data.Data[i].OwnerPid );
      //writeln(inttostr(getlasterror));
      DuplicateHandle( hProcess, Data.Data[i].HandleValue, GetCurrentProcess(), @hDuplicate, 0, FALSE, DUPLICATE_SAME_ACCESS );
      //writeln(inttostr(getlasterror));
      PID:=GetProcessId(hDuplicate);
      //writeln(inttostr(getlasterror));
      setlength(s,1024);
      //writeln(inttostr(getlasterror));
      fillchar(S[1],length(S),0);
      EnumProcessModules( hProcess, @hModule,sizeof(hModule),@Temp);
      //writeln('B'+inttostr(getlasterror));
      SetLastError(0);
      setlength(S,GetModuleFileNameExA(hProcess,hModule,PChar(S),length(S)));
      //writeln(status);
      //writeln('A'+inttostr(getlasterror));
      closehandle(hDuplicate);
      //writeln(inttostr(getlasterror));
      closehandle(hProcess);
      if (PID<>ProcID)and(ProcID<>0) then continue;
      //writeln(inttostr(getlasterror));
      write(Data.Data[i].OwnerPid:10);
      write(Data.Data[i].HandleValue:10);
      write(Data.Data[i].HandleFlags:10);
      write(Data.Data[i].AccessMask:10);
      write(Data.Data[i].ObjectType:10);
      write(PID:10);
      writeln(S);
     end;
  finally
    FreeMem(Data);
  end;
end;

begin
  Enum(9924);
end.

Comment: The nopaste.info link is dead.
Comment: @LueTm I think I found the code in my archives
Comment: Thanks, that's sort of what I was heading for.
Comment: No paste link now redirects to spam site.

Close all open files handles with C#


How do I prove that the distances from boundary are equal for holomorphic convex set of $K$ and $K$?

Question: Let $\Omega(\subset \mathbb{C}^n)$ be a domain of holomorphy. Let $K$ be a compact subset of $\Omega$. Let $K_\Omega$ be the holomorphic convex hull of $K$. Then, how do I prove that $d(K,\partial\Omega)=d(K_\Omega,\partial\Omega)$?
Answer: I'll do only the case $n=1$ . Consider $\eta \in \partial \Omega$. The function $f_{\eta} \colon z\mapsto \frac{1}{z-\eta}$ is holomorphic on $\Omega$.
The supremum of $|f_{\eta}|$ on a compact subset $L$ of $\Omega$ is $\frac{1}{d(\eta, L)}$. Now, for every holomorphic function $f$ on $\Omega$ we have
$$\sup_{z \in K} |f(z)| = \sup_{z \in K_{\Omega}} |f(z)|$$
Applying this to $f_{\eta}$ we conclude
$$d(\eta, K) = d(\eta, K_{\Omega})$$
Answer: Theorem: For a domain $ \subset \mathbb{C}^n$ to be holomorphically convex, it is both necessary and sufficient that for any $K$ compactly embedded in $D$, $$d(K, \partial D) = d(\widehat{K}, \partial D).$$
Proof: Sufficiency is obvious. To show necessity, observe that the right hand side of the above expression never exceeds the left hand side. If the inequality is strict, then we could find a point $\zeta \in \widehat{K}$ such that $d(\zeta, \partial D) < d(K, \partial D)$. Using the Simultaneous Extension Lemma however, we know that any function $f \in \mathscr{O}(D)$ would then extend into the polydisk which is centred at $\zeta$ and has radius $d(K, \partial D)$. That is, beyond the boundary of $D$. This implies that $D$ is not a domain of holomorphy and we have the result.
Notice that intuitively, this theorem says that the passage from compact sets to their holomorphically convex hulls occurs without decreasing the distance to the boundary. This passage is therefore, in some sense, just filling holes and cavities.
Reference: Shabat's Introduction to Complex Analysis -- Part II. See page 184.
The simultaneous extension lemma can be found on page 183.
If you have any further questions, please do not hesitate to ask.
Comment: Why sufficiency is obvius?


Average of percentage of 2 numbers.

Question: If I have 24081 items sold at 45% off.
and 11386 items sold at 60% off.
What is the average percent off for all items sold?
Thanks for your help in advance!
Craig
(This is not homework :) )
Comment: Do the items all have the same price?
Comment: It doesn't really matter on the prices.  I actually don't need the price factor.  I just need to know the average percentage discount offered rather than the discounted price.
Answer: This is the average of $45 \%$ and $60 \%$, weighted by the respective number of items.

The total number of items is $$24081 + 11386 = 35467$$
The average percent is $$\frac{24081 \cdot 45\% + 11386 \cdot 60\%}{35467} \approx 49.82\%$$
Comment: That looks right to me.  Thanks very much for the answer and for showing how to achieved it as well!
Answer: It depends on the price of the items. The total percentage can be any number between 45% and 60%.
If the items all have the same price then you can just make the weighted mean of the two percentages.
Comment: You are formally right, but I think that the question should be interpreted differently. It is of no interest to know the average of the percentages... what one could be interested in should be the total discount.
Comment: If you think of "percent off" as a property of each item, then I think the question is asking for the average value of that property over all items. This doesn't seem to depend on price.
Comment: Makes sense, good point! +1
Comment: For completeness, it should still be the weighted mean of the percentages if the prices differ. Just weighted by the sum of prices in each group.

Average of percentage of 2 numbers.


Question about dimension of varieties: where is this hypothesis necessary?

Question: I found the following result on the web:
Theorem. Let $f:X\rightarrow Y$ be a morphism of varieties, and assume that the dimension of all fibers $n=f^{-1}(P)$ is the same for all $P\in Y$. Then $\dim X=\dim Y+n$.
Question 1: Should I also ask that all the fibers are irreducible (to enable me to talk about its dimension)?
Then the proof goes by induction on $\dim Y$, with the case $\dim Y=0$ trivial, since $Y$ must be a point.
On the inductive step, we may assume $Y$ is affine. For a nonzero regular function $g\in \mathcal{O}_Y(Y)$, we have that $Z(g)=\{y\in Y:g(y)=0\}$ has pure codimension $1$, hence any of its irreducible components has codimension $1$. Now, putting $X'=f^{-1}(Y')$, where $Y'$ is some irreducible component of $Z(g)$, we have by inductive hypothesis that $\dim X=\dim X'+1=\dim Y'+n+1=\dim Y+n$.
My attempt to justify the above conclusion is to observe that $$X'=Z(g\circ f)=\{x\in X:g\circ f(x)=0\}.$$ So, if $g\circ f$ is nonzero, then it has codimension $1$ on $X$ and everything works fine. However, I cannot guarantee this (at least I don't see how), so:
Question 2: The hypothesis about the dimension of the fibers can be used to justify my attempt? If not, how the hypothesis should be used to finish the inductive proof?
Thank you very much for your attention.
Comment: If $g$ is not zero, say $g(P)\neq 0$, for any $Q\in f^{-1}(P)$ (which is non empty by the hypothesis) we have $g(f(P))\neq 0$. The irreducible condition is not necessary because you can talk about dimension of any topological space
Comment: But my attempt is obviously wrong, since the equality $X'=Z(g\circ f)$ does not hold...
Comment: Okay. So, where is the hypothesis about the dimension of the fibers necessary? Thanks, by the way.
Answer: Given a non-zero $g\in\mathcal{O}(Y)$, let $Z_1,\ldots,Z_k$ be the irreducible components of $Z(g)$. The first thing you need to observe is that each $f^{-1}(Z_i)$ is union of irreducible components of $V(g\circ f)$. This is becuase for any irreducible component $W$ of the latter, $f(W)$ is an irreducible subset of the former. Given $i$, choose an irreducible component $W_i$ of $f^{-1}(Z_i)$ (hence of $V(g\circ f)$). Notice that $f:W_i\rightarrow Z_i$ verifies the hypothesis with the same $n$ (independent of $i$!, and here is where the hypothesis is important) and then you can apply induction.
You will see this better if you consider the case $\dim Y=1$ in which case $V(g)=\{P_1,\ldots,P_k\}$ and $V(g\circ f)=f^{-1}(P_1)\cup\ldots\cup f^{-1}(P_k)$.


How can I set focus on my next textbox in another row after saving?

Question: Hi I just wanted to ask you guys if how can I set my cursor to focus on the next text box after saving. I have a table where there is a text box and a save button on each row. All I wanted is when I click the save button it will focus on the next textbox in the next row? thank you in advance for helping me.
Comment: Or at the very least, your HTML code and JS in the question.
Answer: Try like this
$("#savebuttonId").click(function () {

    $(this).closest("tr").next().find("textarea").focus();
});

First you need to find the current parent tr using closest(), then use next() to find the next tr. Finally use find() to get the child textarea.