Examples for obstructions to a $Spin^c$ structure

Question: For a real vector bundle $E$ of rank 3 on the base manifold $M$, the obstruction to having a $Spin^c$ structure on this vector bundle is given by the integral Stiefel-Whitney classes $W_3 = \beta w_2(E)$, where $\beta$ is the Bockstein homomorphism.
Are there any explicit examples of real vector bundles $E$ of rank 3 on 3-manifolds and on 4-manifolds for which the obstruction class $W_3$ is non-vanishing?
In physics terms, I am asking in what situation an $SO(3)$ gauge field on 3-manifolds or 4-manifolds cannot be lifted to a $U(2) = Spin^c(3)$ gauge field?
Answer: If $M$ is an orientable 3-manifold then any real vector bundle $E\rightarrow M$ of rank $\geq 2$ admits a $Spin^c$-structure. This follows since duality shows $H^3(M)$ to be torsion free giving $\beta \omega_2=0$.
Now consider $M=S^1\times \mathbb{R}P^2$. The Kunneth theorem shows that $H^3(S^1\times \mathbb{R}P^2)\cong \mathbb{Z}_2$, generated by an element $\beta (x)$ where $x\in H^2(S^1\times \mathbb{R}P^2;\mathbb{Z}_2)$ and $\beta:H^2(S^1\times \mathbb{R}P^2;\mathbb{Z}_2)\rightarrow H^3(S^1\times \mathbb{R}P^2)$ is the Bockstein connecting map. Moreover obstruction theory show that $x$ classifies some rank 3 real vector bundle $E\rightarrow S^1\times\mathbb{R}P^2$ in that $\omega_2(E)=x$. In particular $\beta(x)\neq 0$ and $E$ does not admit a $Spin^c$-structure.
Similarly if $M$ is an orientable $4$-manifold then it is well known that its tangent bundle admits a $Spin^c$-structure. See for instance the note "All 4-Manifolds Have $Spin^c$-Structures" by Teichner and Vogt (available at http://people.mpim-bonn.mpg.de/teichner/Papers/spin.pdf). It is not true for non-orientable 4-manifolds, however, and the the tangent bundle of of $\mathbb{R}P^2\times\mathbb{R}P^2$, given as an example in the cited note, is easily verified to admit no $Spin^c$-structure.
For an example of an arbitrary rank $3$ real vector bundle over an orientable $4$-manifold that does not admit a $Spin^c$-structure simply note that the vector bundle $E\rightarrow S^1\times \mathbb{R}P^2$ given as my previous example extends to a vector bundle $E'\rightarrow S^1\times \mathbb{R}P^3$ which by the same reasoning admits no $Spin^c$-structure.


$ax+by=cx+dy$, where $x$ and $y$ are variables. Does $a=c$, $b=d$?

Question: If I have the equation $ax+by=cx+dy$, where $x$ and $y$ are variables and $a,b,c,d$ are coeficients. And also this equation holds for all $x$ and $y$. Can we conclude from this equation that $a=c$ and $b=d$? If we can, is there some theorem about that or proof?
Comment: If the given equality holds for all real $x$ and $y$ we can make the suggested conclusion (comparison of coefficients).
Comment: @Peter Yes, holds for all x and y (I added edition to the post).
Answer: If it holds for all values of $x,y$ then it holds for $x =1; y = 0$ and for $x=0; y=1$.
So $a*1 + b*0 = c*1 + d*0$ and $a*0 + b*1 = c*0 + d*1$.
Answer: write your equation in the form
$$x(a-c)=y(d-b)$$ if this is fulfilled for all real $x,y$ then it must be $$a=c$$ and $$b=d$$
Answer: If this equation needs to be hold for arbitrary $x$ and $y$, then it is a 'YES'; otherwise it is a 'NO'


Advanced Views Filter

Question: I would like to build a view (slideshow) of profiles, which is relatively easy to do. However I would like to filter them based on a node field of the page the view will be displayed on.
I defined a new content type called Category, where I describe categories in more detail. One of the node fields is called category.
My profiles also have a field category. The idea is that when a user views the node Category A, I would like to display a view showing all the profiles belonging to Category A. When the view Category B, I would like to display all the profiles belonging to Category B.
Can this be done via Contextual Filters? If so, how?
I'm not sure if this helps but the Category values are stored in Taxonomy.
Comment: Ok finally figured it out, answer was in http://drupal.stackexchange.com/questions/13594. Important step 5 onwards
Comment: Ok finally figured it out, answer was in [this question][1]. Important step 5 onwards

  [1]: http://drupal.stackexchange.com/questions/13594
Comment: Sorry tried to answer the question but it converted it to comment. Will try again.
Answer:
Add contextual filter on term id
select Provide default value
select type content id from url
also change your path to [your_path]/%
Comment: Thanks but this works on page views, but not on block views.
Answer: Sorry for the confusion with the comments above. So hopefully the system will accept this as the answer:
In summary make sure you following all steps provided in the answer including:

Under "When the filter value IS in the URL or a default is provided" check "Specify Validation criteria"
Select the vocabulary being used.
Under "Filter Value type" pick term name converted to term ID"
Checking "Transform dashes in URL to spaces in term name filter values" will insure that any auto generated path alias' that have converted spaces to dashes are properly handled. Try your view with this checked and unchecked.

Advanced Views Filter


Errors from custom FieldItemList::getConstraints() displayed next to every single property

Question: Summary
Errors set by constraints on custom field types appear next to every single property by default.
We can use the ::errorElement() method on the widget to place errors that come from the ::getConstraints() method of the field item.
However, errors that come from ::getConstraints() in a custom field item list will not go through ::errorElement(). How can we reasonably place them?
Details
My original problem ist very complicated. I've drastically simplified it to show only what's essential. We start with a very simple custom field type with 2 number properties.
class YearRangeType extends FieldItemBase {
  public static function propertyDefinitions($field_definition) {
    $properties['start'] = DataDefinition::create('integer');
    $properties['end'] = DataDefinition::create('integer');
    return $properties;
  }

  public static function schema($field_definition) {
    $schema = ['columns' => [
      'start' => ['type' => 'int',],
      'end' => ['type' => 'int',],
    ],];
    return $schema;
  }

  public function isEmpty() {
    $start = $this->get('start')->getValue();
    $end = $this->get('end')->getValue();
    return !($start || $end);
  }
}

We define a custom FieldItemList for it that adds a simple validation: checking if at least 2 items are present.
class YearRangeItemList extends FieldItemList {
  public function getConstraints() {
    $constraints = parent::getConstraints();
    $constraints[] = $this->getTypedDataManager()
      ->getValidationConstraintManager()
      ->create('Count', [
        'min' => 2
      ]);
    return $constraints;
  }
}

When I try to save only one item, the field will look like this:

If the errors would result from YearRangeType::getConstraints(), we could use theerrorElement()` method of the widget to place them.
However, the Drupal core class WidgetBase does deliberately not pass errors set by the item list to errorElement(), see these lines in the Drupal core code (version 8.8.1).
How else should we place them?
Answer: We can place the errors with three modifications in the widget class.
First, we add the empty form element non_field_errors we can attach the errors to.
class YearRangeWidget extends WidgetBase {
    ...
    public function form($items, &$form, $form_state, $get_delta = NULL) {
        $formElement = parent::form($items, $form, $form_state, $get_delta);
        $formElement['non_field_errors'] = ['#type' => 'item'];
        return $formElement;
    }
    ...
}

Second, in the flagErrors method, we collect all errors that do not belong to any property and call a separate method to treat them.
class YearRangeWidget extends WidgetBase {
    ...
    public function flagErrors($items, $violations, $form, $form_state) {
        $listViolations = [];
        foreach ($violations as $key => $violation) {
            if ($violation->getPropertyPath() === '') {
                $listViolations[] = $violation;
                $violations->remove($key);
            }
        }
        parent::flagErrors($items, $violations, $form, $form_state);
        $this->flagNonFieldErrors($items, $listViolations, $form, $form_state);
    }
    ...
}

Third, we define the method treating the separated errors.
class YearRangeWidget extends WidgetBase {
    ...
    public function flagNonFieldErrors($items, $violations, $form, $form_state) {
        $field = $items->getName();
        foreach ($violations as $violation) {
            $form_state->setError(
                $form[$field]['non_field_errors'],
                $violation->getMessage()
            );
        }
    }
    ...
}


Real time scheduling

Question: I'm trying to measure the execution time of a process that I call via the command line (i.e., I want to find out how long it takes to for the process to finish). Is there any algorithm to calculate it ?
Answer: Use the built-in time command:
For example:
<code>#time tail /var/log/messages

Messages...
Messages...

real    0m0.016s
user    0m0.000s
sys     0m0.004s
</code>
For more specific and details, use:
<code>#/usr/bin/time -v sleep 1
       Command being timed: "sleep 1"
       User time (seconds): 0.00
       System time (seconds): 0.00
       Percent of CPU this job got: 1%
       Elapsed (wall clock) time (h:mm:ss or m:ss): 0:01.05
       Average shared text size (kbytes): 0
       Average unshared data size (kbytes): 0
       Average stack size (kbytes): 0
       Average total size (kbytes): 0
       Maximum resident set size (kbytes): 0
       Average resident set size (kbytes): 0
       Major (requiring I/O) page faults: 0
       Minor (reclaiming a frame) page faults: 210
       Voluntary context switches: 2
       Involuntary context switches: 1
       Swaps: 0
       File system inputs: 0
       File system outputs: 0
       Socket messages sent: 0
       Socket messages received: 0
       Signals delivered: 0
       Page size (bytes): 4096
       Exit status: 0
</code>

Real time scheduling


Xcopy a folder and subfolders with os.system and python3

Question: Hi I am using python and I want to copy a folder and its subfolder, I am using this code:
source = "C:\\boleta_v1\\bd"
target = "C:\\boleta_v1\\" + folder_name

output = os.system ("""xcopy "%s" "%s" /E""" % (source, target))

When I see the result, it copied but it just copied the files inside the folder not the folder with the files inside, so I wonder, how can I copy the folder and its subfolder and files inside with os.system in Python
Thanks
Comment: Are you aware that Python's built-in `shutil.copytree` can do that, in a system-independent way?  If you insist on using `xcopy`, then you kist need to set `target = "C:\\boleta_v1\\"+folder_name+"\\bd"`.
Answer: You can use mkdir (or md) to create the directory you want. That is:
source = "C:\\boleta_v1\\bd"
target = "C:\\boleta_v1\\" + folder_name
target = os.path.join(target, "bd")

os.system("""md "%s" """ % (target))
output = os.system ("""xcopy "%s" "%s" /E""" % (source, target))

Comment: Note that this approach allows shell injection vulnerabilities if an attacker can choose the `folder_name`; particularly if they can pick a name that contains literal quotes. And even if you don't have attacks on your system, it still means there are filenames your code doesn't work with.
Comment: It copied the bd folder but it did not copy the subdolders and files inside it


How to swich the color theme in WinUI3 manually?

Question: I want to build a combobox to let user choose which theme they want the app to display.
I added a combobox on my WinUI projects's settings page
The code go like this:

<ComboBox x:Name="themeMode" SelectionChanged="Themes_SelectionChanged">
    <ComboBoxItem>Light</ComboBoxItem>
    <ComboBoxItem>Dark</ComboBoxItem>
    <ComboBoxItem>Defaut</ComboBoxItem>
</ComboBox>

But I don't know how to defined "Themes_SelectionChanged"
(I have found some ways, but I think they're too complex to implement just this simple functionality, aren't there any simple way to acieve this?)
Answer: Let's say this ComboBox is in MainPage.xaml.
<ComboBox x:Name="themeMode" SelectionChanged="Themes_SelectionChanged">
    <ComboBoxItem>Light</ComboBoxItem>
    <ComboBoxItem>Dark</ComboBoxItem>
    <ComboBoxItem>Defaut</ComboBoxItem>
</ComboBox>

then in MainPage.xaml.cs
private void Themes_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (sender is ComboBox comboBox &&
        comboBox.SelectedItem is ComboBoxItem comboBoxItem &&
        comboBoxItem.Content is string themeString &&
        Enum.TryParse(themeString, out ElementTheme theme) is true)
    {
        this.RequestedTheme = theme;
    }
}

Also, instead of manually adding items in XAML, you can do it this way.
In MainPage.xaml:
public ImmutableArray<string> ElementThemeOptions { get; } = ImmutableArray.Create(Enum.GetNames<ElementTheme>());

private void Themes_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (sender is ComboBox comboBox &&
        comboBox.SelectedValue is string themeString &&
        Enum.TryParse(themeString, out ElementTheme theme) is true)
    {
        this.RequestedTheme = theme;
    }
}

And in MainPage.xaml:
<ComboBox
    ItemsSource="{x:Bind ElementThemeOptions}"
    SelectionChanged="Themes_SelectionChanged" />

UPDATE
Don't forget to do this in the root page, MainPage in this case.
<Window
    ...
    ...>
    <local:MainPage />
</Window>

Comment: If this solved your problem, please accept the answer so we can close this session.
Comment: Sorry, English is not my native language, so the expression may be a little unclear. And, yes, that's basically what I'm trying to say
Comment: It works! But what else if my ComboBox is in an Expander, how can I modify the code so that its selection works for the entire window?
Comment: It should work as long as `this` is the root page, which should be the content of  your `MainWindow`.
Comment: Thanks, this sloved my problem
Comment: @WuXiuheng Can you flag this somehow so that others can find the workable solution easily?


What is the practical importance of the aggregated precision and recall?

Question: I am working on movielens 100K movie data for recommendation system.
I divide the data into test and training and calculate the precision and recall. In testing there are more than 10K users chosen randomly.
I am able to find the precision and recall for an individual user.
I wanted to know:
Is there any practical importance to the aggregated precision and recall?
Comment: In case of prediction, we have MAE or RMSE to consider all the predicted values and we can give aggregated result. Like this, I wanted to know can we aggregate precision and recall ?
Comment: I'm not 100% what the question is but one way you can combine precision and recall is via the F-measure : (2PR) /(P+R)
Comment: This is in context of recommender system. For individual user I give 10 movies as recommendations. For this single user, out of this 10, 4 to 5 (let say 4 on avg) are good.  For some other user 3 are good. These numerical values have importance - precision. My question is if I aggregate all these values (precision from all users), can I boast that my recommender is x% (aggregated percentage) precise ? Or this aggregated value have no importance.
Comment: Hm, I could give you an educated guess on this, but I think its better you ask this same question over on http://stats.stackexchange.com/
Answer: You will see Precision/Recall results reported in academic papers as a aggregate, rather than 10,000 different P/R results. In that respect it gives the reader a very general sense of RS performance. Typically you will see Precision/Recall represented as a curve (as seen here: http://www.cs.washington.edu/ai/mln/images/image001.png). You tend to see that at Recall = 1, Precision is low, and where Precision = 1, recall is low. You can easily create one of these curves in Excel or Google Sheets from your 10,000 results.
As mentioned in the comments F-measure is a way to combine P/R to generate a mean value, although you need to be aware of the limitations of the F measure before you go "boasting" about it. It is not uncommon to justify some sort of weighting for either precision or recall depending on your application domain, so just be aware that the basic F-measure is balanced (both precision and recall are treated as equally important).
Receiver Operator Characteristic (https://en.wikipedia.org/wiki/Receiver_operating_characteristic) is also commonly used along side P/R curves, and f-measure in recommender system evaluation. If you are looking for extra credit then I would recommend using multiple methods to evaluate RS performance such as P/R curve, F measure, AUC, and ROC.


How to get the "fragment" part of an url in a nuxt middleware?

Question: I want to get the access_token in the url after a redirection from AWS COGNITO in a "implicit" oauth flow.
AWS Cognito redirect the browser to : https://mydomain/#access_token=xxxxx
I want to get the "access_token=xxxxx" part for storage, in a nuxt "middleware".
It doesn't seam to be in the "context.req" object. Where can I find it ?
Comment: It might be in `context.$route`.
Comment: Alas, context.$route is empty :(

Do I need to add a specific module or something ?
Comment: I tried a `console.warn(context)` and the access_token is nowhere ...
Comment: Are you using Nuxt in SSR mode? The fragment is never sent to server, this is something you can only do in the browser. It should be in the `$route.hash` property.
Comment: Damned ! Yes, I use SSR mode, I want to test this for a futur project which will need some SEO.  But after carefull consideration, it's true that I don't need the "connected" information server side ... "personnals informations" are not to be exposed to search engines or cached. Thanks !
Answer: The Implicit flow doesn't return an authorization code like the Authorization flow does. You'll get the access token directly in the response body.
Here is a link with more info.
Implicit Flow
Comment: What OP wrote was *I want to get the* **access_token**
Comment: As I said, the access token is in the body. Authorization codes come in the URI. Access tokens come in the response body.
Comment: https://aws.amazon.com/blogs/mobile/understanding-amazon-cognito-user-pool-oauth-2-0-grants/ -> read the bit what Amazon Cognito does in implicit flow and where it places the data. Then read what the OP asked and try to figure out why you're posting the wrong answer.
Comment: N.B is right, Cognito put the access token in the fragment part of the url, not in the body ... I can't find a way to change this behaviour ... So i'm stuck with this ...


Using Custom Formatters module to output an image's URI

Question: I'm trying to make a formatter which prints an image's URI instead of the image itself. My problem is I don't know what the formatter is expected to return. The help information is apparently not working on my install.
So, what does it expect as it's return value? This is what I've tried:
function image_path_formatter($vars) {
    $element['content'] = $vars['#items'][0]['uri'];
    return $element;
}

My view has this in content:

Edit formatter

Comment: See http://drupal.org/node/1188398#comment-4658330 for issue with Contextual links module integration in Custom Formatters 7.x-2.x.
Answer: You should take a look at the file module, which does a lot of this already
For Drupal 7:
/**
 * Implements hook_field_formatter_info().
 */
function file_field_formatter_info() {
  return array(
    'file_default' => array(
      'label' => t('Generic file'),
      'field types' => array('file'),
    ),
    ...
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function file_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  switch ($display['type']) {
    case 'file_default':
      foreach ($items as $delta => $item) {
        $element[$delta] = array(
          '#theme' => 'file_link',
          '#file' => (object) $item,
        );
      }
      break;
    ...
  }
  return $element;
}

You could copy this and create your own theme function, all it needs to do, would be to print the uri and you're done.
Answer: Here's what worked for me:
In the custom formatter PHP code:
if (function_exists('image_path_formatter')) {
    return image_path_formatter($variables);
} else {
    return null;
}

And in template.php
function image_path_formatter($vars) {
    return $vars['#items'][0]['uri'];
}

Answer: The Custom Formatters module should have an example of how to handle Image formatters using PHP by default.  I just enabled the 7.x-2.2 version and it had this in the default formatters.  I'd look there to get an idea of how to approach it.

When you click on edit, here's what you get:
// Formatter settings.
$settings = $variables['#display']['settings'];

$element = array();
foreach ($variables['#items'] as $delta => $item) {
  $element[$delta] = array(
    '#type' => 'link',
    '#href' => file_create_url(image_style_path($settings['destination_image_style'], $item['uri'])),
    '#title' => theme('image_style', array(
      'style_name' => $settings['source_image_style'],
      'path' => $item['uri'],
    )),
    '#options' => array(
      'html' => TRUE,
    ),
  );
}
return $element;


Listar todos synonyms no Oracle

Question: Como faço para listar todos os synonyms(sinônimos) presentes em meu banco de dados? Preciso saber quais que estão criados para comparar entre bancos o que existe. Tentei com o código abaixo mas não retorna sinônimos:
select * from all_objects

Answer: select * from all_synonyms;

Existe uma view para cada tipo de objecto que tu crias.
exemplo: all_tables, all_views, all_procedures......
Comment: pow vacilei, resolveu. kkkk consegui trazer os synonyms. valeu Renato.
Comment: Quando não souber que tabela do metadados usar ... select * from DICT
Comment: Eu prefiro usar a `user_synonyns`, por trazer somente os que estão válidos, do usuário conectado.

Listar todos synonyms no Oracle


Mann-Whitney vs. t-test to compare two samples with different distributions

Question: How should I test the statistical difference of a mean (or median?) concentration of an enzyme between two groups of patients where the distribution in one group is normal, whereas in other it is non-normal? The distribution of values for the entire study population is non-normal. Do I use a Mann-Whitney test, or Student's T-test?
Comment: What are your sample sizes?
Comment: On what basis can you assert the distribution of one of the populations?
Answer: The first thing you should do is to decide on what question is really important to answer.  You say that the 2 groups have different distributions, is the difference in mean or median really the most important thing when you already know of a distributional difference?
Consider that you are looking at 2 different treatments to lower cholesterol.  The first will actually raise the cholesterol in most patients, but a few will have very drastic reductions (along with medical complications either due to or resulting in the drop in cholesterol), the second treatment will result in a moderate reduction in cholesterol in all patients with some small variation between the patients.  Given the above information, do you really care which has higher mean/median reduction?
If you decide that the mean or median difference really is a question of interest (and what will you do if the mean favors one group and the median favors the other group?) then there are some additional questions to ask.  How non-normal is the 2nd group? (and how non-normal is the 1st group, are you really sure it is normal? or just close enough)?  If the non-normality is not severe (how severe can be a function of the sample size and shape) then the t-test could be reasonable.  Other approaches that do not require the normality and let you compare means or medians are permutation and bootstrap tests (but make sure that you are comfortable with the assumptions required for those).  The Mann-Whitney/Wilcoxon test is actually a special case of the permutation test (but the statistic being compared is not the median (or mean) without further assumptions).
Answer: One assumption of the two sample t-test is that both samples come from a normal population. If you are convinced your samples both do not come from normal populations, you could use the Wilcoxon rank-sum test to test for difference in medians.
Comment: @Frank I used to think that, too, until I did some simulations and was surprised at some of the "bad" situations in which the t-test worked well. The issue is how much non-normality messes up the *standard error* (not the SD) *relative to how the sampling mean varies.* Now I adopt a more nuanced attitude: the t-test can be remarkably resistant to many kinds of non-normality. It appears to get into most trouble with strongly skewed distributions (and I'm not persuaded that some of the efforts to incorporate skewness adjustments are any good except in very special circumstances).
Comment: This is not true. This is a necessary requirement for the t-test to be *exact*. However, we often use asymptotic tests, such as the maximum likelihood test for inference in regression models with specified working probability models.
Comment: @AdamO, $P$-values from the $t$-test can be horribly inaccurate if its assumptions are not satisfied.  Non-normality messes up the standard deviation more than it messes up the mean.
Comment: Rand Wilcox has shown that a tiny bit of contamination from a normal with higher variance, not even noticeable when plotting the density, can make the $t$ statistic have a distribution that is very far from the $t$ distribution.
Comment: For the sake of others who may read this thread in the future: The question refers to the Mann-Whitney test, and @user27008 refers to the Wilcoxon rank-sum test. These are two different names for the same test.
Comment: http://www.sciencedirect.com/science/article/pii/S0895435612002752
Comment: The Mann-Whitney/Wilcoxon test is **not** a test for difference in medians (or means). See the answers [this question](http://stats.stackexchange.com/questions/11084/why-is-the-mannwhitney-u-test-significant-when-the-medians-are-equal) for details. And especially since the original poster had data were one group was normal and the other not, this test would not be an appropriate test for testing differences in medians or means.
Comment: Good call.  I hadn't thought of it that way, but that makes sense.  I'm sure you could explain this better than me, but if Ana's t-test isn't exact, then wouldn't it be preferable to use the rank-sum test, which from my understanding will provide larger power in this situation?
Comment: @FrankHarrell do you happen to have a citation for that? I tend to abuse "classical" asymptotic results and I'd very much like to read about it.


Downloaded File not supported from laravel using vue.js

Question: My function can download the exact file I want using laravel and vue.js, but when I try to open the downloaded file, it show unsupported file type.
My vue.js function to get the file info:
downloadFile(file){
  this.$axios.post(`file/download`, file).then(({data}) => {
    this.download(data, file)
  })
},

My Laravel controller:
$file = public_path() . "/images/" . $request['file_name'];
$headers = ['Content-Type' => 'application/jpeg'];
return response()->download($file, $request['file_name'], $headers);

And finally, my vue.js function to download the image creating the URL link:
download(data, file) {
    const url = window.URL.createObjectURL(new Blob([data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', file.file_name);
    document.body.appendChild(link);

    link.click();
}

Comment: The MIME should be `image/jpeg`
Comment: @apokryfos I already add that, but it does not work too.
Answer: Because the backend already returns "download" data
You shouldn't fetch it in the frontend and then open it in a new tab. You can open it in a new tab without fetching
downloadFile(fileName){
 this.download(fileName)
},

download(file_name) {
    const link = document.createElement('a');
    link.href = `yoururl/${file_name}`;
    link.setAttribute('download', file_name);
    document.body.appendChild(link);
    link.click();
}

Also in the backend part you should have a method like this with "get" route
public function download($filename) {
  $file = public_path() . "/images/" . $filename;
  $headers = ['Content-Type' => 'application/jpeg'];
  return response()->download($file, $filename, $headers);
}


Is a heat-map of gene expression more informative if Z-scores are used instead of actual expression measurement values?

Question: I have a heat-map of gene expression measurements (log2-transformed microarray signals, after inter-microarray data normalization, etc.) that I am using to illustrate the expression of 72 genes ('rows' of the heat-map) which I had identified as differentially expressed among different sub-groups of the 60 samples ('columns' of the heat-map, ordered by sub-groups) of my study. The ranges of gene measurements are within the 1-12 range (e.g., 4-8 for gene X, 2-10 for gene Y, and so on). It is a two-color heat-map, with the brightest green, black, and brightest red colors of the color scale used for values 1, 4 and 12, respectively.
A reviewer has commented that the heat-map will be more informative if Z-scores of the gene expression measurements are used instead. I don't get this because to me it seems that the heat-map will be less informative; Z-scoring will reduce the dimensionality of the data as one can no longer compare one gene to another for a given sample.
Can anyone comment on this? Thanks.
An image showing the current and reviewer-proposed heat-maps can be seen here: https://i.stack.imgur.com/haeZ9.png
Comment: Thanks, that helps me understand (as does @fosgen's answer).  It's nothing to do with your question, but in passing, I strongly recommend avoiding relying on red-green contrasts, because of the color blindness problem.
Comment: Sorry that this isn't my field so probably others would know from the context; but what are the three dimensions (horizontal position, vertical position, and color) of your heatmap? Is the reviewer suggesing just changing whatever is currently mapped to colour to be a standardised version the same variable (standardisation of some sort - again apologies I don't know what this means in your case), in which case I don't see how it reduces the dimensionality you are showing.  Doesn't make it a good idea, of course, that depends on what you are trying to see.
Comment: Thanks for the comment. I have clarified some details in the question, and have added a link to an image of the heat-map.
Answer: What the reviewer may be referring to is the bottom legend of your figure. It goes from 1 to 12, with 4 right in the middle, which is discomforting. This makes your absolute log expression values difficult to interpret, because when a gene goes from bright green to black, its expression level is multiplied by 16, but when it goes from black to bright red, it is multiplied by 256. In short, I don't think your figure could be "more informative", but the information could be more intuitive.
As explained by @fosgen, Z-scores are centered and normalized, so the user can interpret a color as $x$ standard deviations from the mean and have an intuitive idea of the relative variation of that value.
Like @fosgen, I think you should go for standardization by gene (standardization by cell type does not make sense to me in that context). Black will be the average expression across different cell types (set to 0) and the color distribution will be symmetrical on both sides.
Showing the (relative) gene-wise variation of expression is standard in the field, but you might have specific reasons to show the (absolute) log2-microarray measurements, in which case you can expose them to the reviewers. But I would still straigthen the color gradient to ease interpretation.
Comment: Thanks! I have provided a link in the question to an image that shows both types of heat-maps next to each other.
Comment: Good job!! This is less of a color explosion :D It also draws the emphasis on the diagonal square which show the groups of genes up-regulated or down-regulated in the groups of cells. The information is the same, but I personally find it more intuitive.
Answer: The answer depends on what kind of comparison have to be shown on the figure. If we want to show differences between genes, it is good to make Z-score by samples (force each sample to have zero mean and standard deviation=1). If we want to show differences between samples, it is good to make Z-score by genes (force each gene to have zero mean and standard deviation=1). Original heat-map contains both information. So the phrase that it is "less informative" does not suit here. But redundant information makes useful information hard to see. Z-scoring does not reduce dimensionality, but throw away information about means and standard deviations in rows or columns (genes or samples). Think what information and what comparison you are discussing in paper and make proper Z-scoring if some information is redundant, else if all is useful - leave the original heat-map and explain this point to your reviewer.
Comment: Looking at your figure, I can suggest that standartization by genes may be helpful. Try it and see whether the resulted heat-map supports your inferences more clearly. Note that mir-1826 expression is constant, and thus may be deleted from figure, but mentioned in text. Also, you may add mean expression value near each gene in order to save the possibility of gene comparison after Z-scoring


How to bind method to a HoverButton?

Question: I've been looking for hours but I can't find anything useful. Any help appreciated!
I'm writing a Kinect application using WPF with the Coding4Fun toolkit and the MVVM pattern.
I'd like to put all my kinect related logic in my ViewModel and bind those methods to a HoverButton (found in the C4F toolkit).
A normal button had the 'Command' property, However the HoverButton does not.
So in short:
I want to bind the click event of a HoverButton to a method in my ViewModel.
My XAML:
<Window x:Class="KinectTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:fun="clr-namespace:Coding4Fun.Kinect.Wpf.Controls;assembly=Coding4Fun.Kinect.Wpf" Title="MainWindow" Height="350" Width="525"
    Loaded="WindowLoaded"
    Closed="WindowClosed"
    Cursor="None"
    >
<Grid Name="MainGrid" MouseMove="GridHoverMouseMove" DataContext="_viewModel">

    <Canvas Name="SkeletonCanvas" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Background="Black">
        <fun:HoverButton Name="KinectUp" ImageSource="/Images/blue_glass.png" ActiveImageSource="/Images/blue_glass.png" ImageSize="100" Canvas.Top="26" TimeInterval="1000">

        </fun:HoverButton>
        <fun:HoverButton Name="KinectDown" ImageSource="/Images/red_glass.png" ActiveImageSource="/Images/red_glass.png" ImageSize="100" Canvas.Bottom="26" TimeInterval="1000"/>

    </Canvas>
    <Image Name="ColorImage" VerticalAlignment="Bottom" HorizontalAlignment="Right" Width="120" Height="120"></Image>
            <TextBlock Name="Notification" Foreground="White" FontSize="50" VerticalAlignment="Top" HorizontalAlignment="Stretch" TextAlignment="Center" Text="{Binding Path=Notification, Mode=TwoWay}"></TextBlock>
    <Canvas Name="CanvMouse" Background="Transparent" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
        <Image Name="imgMouse" Width="70" Source="/Images/handround_green.png"></Image>
    </Canvas>
</Grid>
</Window>

My ViewModel:
internal class MainViewModel : INotifyPropertyChanged
{

    public event PropertyChangedEventHandler PropertyChanged;
    public ICommand KinectUpClick { get; private set; }
    public ICommand KinectDownClick { get; private set; }

    private string _notification = "Hello";
    public SensorHelper SensorHelper { get; set; }

    public string Notification
    {
        get { return _notification; }
        set
        {
            _notification = value;
            PropertyChanged(this, new PropertyChangedEventArgs("Notification"));
        }
    }

    public MainViewModel()
    {
        KinectUpClick = new RelayCommand(PerformKinectUpClick, CanKinectUpClick);
        KinectDownClick = new RelayCommand(PerformKinectDownClick, CanKinectDownClick);

    }

    private bool CanKinectUpClick(object parameter)
    {
        return SensorHelper.CanMoveUp;
    }

    private bool CanKinectDownClick(object parameter)
    {
        return SensorHelper.CanMoveDown;
    }

    private void PerformKinectUpClick(object parameter)
    {

        ThreadPool.QueueUserWorkItem((o) =>
        {
            Notification = "Kinect goes up!";
            SensorHelper.MoveAngle(5);
            Notification = "Kinect ready...";
        });
    }

    private void PerformKinectDownClick(object parameter)
    {
        ThreadPool.QueueUserWorkItem((o) =>
        {
            Notification = "Kinect goes down!";
            SensorHelper.MoveAngle(-5);
            Notification = "Kinect ready...";
        });
        ;
    }
}
}

My Code-behind:
public partial class MainWindow : Window
{
    private readonly MainViewModel _viewModel;
    private SensorHelper _sensorHelper;

    public MainWindow()
    {
        InitializeComponent();
        _viewModel = new MainViewModel();
        MainGrid.DataContext = _viewModel;
    }

    private void WindowLoaded(object sender, RoutedEventArgs e)
    {
        try
        {
            _sensorHelper = new SensorHelper();
        }
        catch (Exception exception)
        {
            MessageBox.Show(exception.Message);
        }
        _viewModel.SensorHelper = _sensorHelper;
        _sensorHelper.InitializeSkeleton(ref SkeletonCanvas);
        //_sensorHelper.CaptureMouse(CanvMouse);
        _sensorHelper.InitializeColorFrame(ColorImage);
        _sensorHelper.StartKinect();
    }

    private void WindowClosed(object sender, EventArgs eventArgs)
    {
        _sensorHelper.StopKinect();
    }

    private void GridHoverMouseMove(object sender, MouseEventArgs e)
    {
        imgMouse.SetValue(Canvas.LeftProperty, e.GetPosition(CanvMouse).X - imgMouse.ActualWidth/2);
        imgMouse.SetValue(Canvas.TopProperty, e.GetPosition(CanvMouse).Y - imgMouse.ActualHeight/2);

        MouseHelper.CheckButton(KinectUp, imgMouse);
        MouseHelper.CheckButton(KinectDown, imgMouse);
    }
}

Answer: Okay, very simple, what you'll have to do is bind an ICommand/Command to an Event by using an EventToCommand which can be found in the MVVMLight Toolkit.
You can use Blend for that as well
Simple example :
<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:GalaSoft_MvvmLight_Command="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WPF4"
    x:Class="TestProject.Window5"
    x:Name="Window"
    Title="Window5"
    Width="640" Height="480">

    <Grid x:Name="LayoutRoot">
        <Button Content="Button" HorizontalAlignment="Left" Height="69" Margin="92,117,0,0" VerticalAlignment="Top" Width="206">

                    <GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding Kinect.MyCommand, Source={StaticResource Locator}}"/>

        </Button>
    </Grid>
</Window>

Comment: Try using the "mvvminpc"-snippet in the MVVMLight Toolkit. It's for properties with a Property Changed optimized for MVVM!

My example is on Pastebin - http://pastebin.com/4uVYJd63
Comment: Because sometimes you'll need info from another for example data for your view and the selected language in the viewmodel of your menu but that will nog be the case I think :)
Comment: Great solution, works nearly exact the way I wanted, however for some reason.. the text in the textbox doens't get updated anymore... Any ideas?
Comment: I installed MVVMLight with Nuget, but I seem unable to find the snippet :( *installing from web now*
Comment: Okay... I installed MVVMLight into Visual Studio, however the compiler claims "The name 'RaisePropertyChanged' does not exist in the current contex"
Comment: Your ViewModel needs to derive from ViewModelBase instead of INotifyPropertyChanged
Comment: I can create a sample solution tonight if you want?
Comment: I fixed it by not using the locator in my XAML, but just using old skool bindings. The locator class makes a new instance of the ViewModel. Is there any reason I should use the locator class rather than regular bindings?
Comment: SO now it works? I inserted it because in most cases it doesn't work without because I have a lot of ViewModels. You can mail me at hello[at]kinectingforwindows.com if not.

The locator is a sort of maincontroller. You don't need it if you have one ViewModel.
Comment: There is a MVVM template installed along with the Toolkit for your solutions that sets everything up for you. You can mail me questions about MVVM Light Toolkit to :)

How to bind method to a HoverButton?


Evaluate $\sum_ {n=1}^{\infty} \cot^{-1}(2n^2)$

Question: I was trying to solve up this equation but couldn't move ahead.
$$\sum_ {n=1}^{\infty} \cot^{-1}(2n^2)$$
I wrote the expression as $$\sum_ {n=1}^{\infty} \tan^{-1}\left( \frac{1}{2n^2}\right)$$
I wanted to change the expression into such a form such that it can take up the form of $\tan^{-1}A-\tan^{-1}B$ so that all the terms except the second one get cancelled up but I am unable to think of any manipulation through which I can get the thing done.
Can anybody give me a hint on how to go ahead?
Comment: related http://www.mat.utfsm.cl/scientia/archivos/vol11/Art2.pdf
Answer: $$\sum_ {n=1}^{\infty} \tan^{-1}\left( \frac{1}{2n^2}\right)=\sum_ {n=1}^{\infty} \tan^{-1}\left( \frac{2n+1-(2n-1)}{1+(2n+1)(2n-1)}\right)$$
$$\sum_ {n=1}^{\infty} \tan^{-1}\left( \frac{2n+1-(2n-1)}{1+(2n+1)(2n-1)}\right)=\sum_ {n=1}^{\infty}\tan^{-1}(2n+1)-\tan^{-1}(2n-1)=\frac{\pi}{4}$$
Comment: Nice +1! and one could do similar stuff with $\cot^{-1}$, showing that $$\sum_1^N\cot^{-1}(2n^2)=\cot^{-1}\frac{N+1}{N}$$
Comment: yes we can do it  :)
Comment: please add your solution. it is nice
Comment: I just came back to this :-)
Answer: To recognize a telescopic sum as Behrouz did is the key for a simple proof.
I will go for the overkill. We have
$$ \sum_{n\geq 1}\arctan\frac{1}{2n^2}\leq \sum_{n\geq 1}\frac{1}{2n^2}=\frac{\pi^2}{12}<1\tag{1}$$
hence:
$$ \sum_{n\geq 1}\arctan\frac{1}{2n^2}=\text{Arg}\prod_{n\geq 1}\left(1+\frac{i}{2n^2}\right) \tag{2} $$
and since the Weierstrass product for the $\sinh$ function gives
$$ \prod_{n\geq 1}\left(1+\frac{z^2}{n^2}\right)=\frac{\sinh(z\pi)}{z\pi}\tag{3} $$
we have:
$$\sum_{n\geq 1}\arctan\frac{1}{2n^2}=\text{Arg}\left(\frac{\cosh\frac{\pi}{2}}{\pi}(1+i)\right)=\text{Arg}(1+i)=\color{red}{\frac{\pi}{4}}.\tag{4}$$

The advantage of this approach is that it computes
$$ \sum_{n\geq 1}\arctan\frac{1}{n^2}=\frac{\pi}{4}-\arctan\left(\frac{\tanh\frac{\pi}{\sqrt{2}}}{\tan\frac{\pi}{\sqrt{2}}}\right)\tag{5} $$
(and similar ones) too, where it is not easy at all to write the main of the LHS as a telescopic term.
Comment: Indeed your solution is so nice :-) +1
Answer: With $$2n^2=\frac{\Big(\frac{1}{n-1}+1\Big)\Big(\frac{1}{n}+1\Big)+1}{\Big(\frac{1}{n-1}+1\Big)-\Big(\frac{1}{n}+1\Big)}$$ we obtain $$\cot^{-1}(2n^2)=\cot^{-1}\Big(\frac{1}{n}+1\Big)-\cot^{-1}\Big(\frac{1}{n-1}+1\Big)$$ Hence $$\sum_1^N\cot^{-1}(2n^2)=\cot^{-1}\Big(\frac{1}{N}+1\Big).$$
Comment: Nice +1..... :)


Texture is showing artifact (bottom wraps to top) when using transparency in Godot

Question: When I add a png with transparency as the texture for a plane, I get these artifacts where the pixels wrap around to the opposite edge. Here, the bottom edge has non transparent pixels, so the top edge is showing some of the pixels wrapped around. Is there a way to get rid of this?
I'm using Godot 3.4.4, GLES2.
Answer: What you are telling me is that the texture is imported to repeat and you do not want that. Double check how you imported the texture: With the texture file selected in the File System panel, go to the import panel (if you changed them, you need to click "reimport"). And flags the texture resource has in the Inspector panel.


Set a date field equal to "current time" + "5 minutes" using tokens

Question: I am using the Field Timer module to display countdown timer on my article node.
Say my article node has the date/time field named (field_article_datetime)
This module will take the value of the date/time field (field_article_datetime) and convert it into a countdown timer in the display of the article.
When the article node is created, I want to set the value of the date/time field (field_article_datetime) equal to current time + 5 minutes.
To extract the current time, I am using the token [node:created] from the token module, but I cannot find a solution on how to add +5 minutes to the token [node:created].
EXAMPLE:
Say at 12/03/2019 08:50:15 PM, a user has created a new article node... So I need a solution to add +5 minutes to the created time so the date/time field named (field_article_datetime) will be equal to 12/03/2019 08:55:15 PM...
This way, the user will see a countdown timer for 5 minutes on the article node display page.
Note: I am using the Business Rules module (similar to Rules module) to set the value of the date/time field (field_article_datetime) with the help of the token module.

Update #1:
Say the node is already created on the site and I want after the submission of a webform to fetch & update the node with update time + 5 minutes.
I think the best Idea is to use a custom module which will do the below:

Fetch the article by nid.
Set the value of field_article_datetime equal to: updated time + 5 * 60.
Save the Node

Since the above actions will be triggered when a user will submit a webform, so why not create a customwebformhandler.php file.
I have created a custom webform handler file but I need help to finish it since I am not a programmer:
<?php

namespace Drupal\my_module_name\Plugin\WebformHandler;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\Core\Form\FormStateInterface;

use Drupal\node\Entity\Node;

use Drupal\webform\WebformInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;
use Drupal\webform\Entity\WebformSubmission;

/**
 * Update a node entity from a webform submission.
 *
 * @WebformHandler(
 *   id = "Update a node",
 *   label = @Translation("Update a node"),
 *   category = @Translation("Entity Update"),
 *   description = @Translation("Updates a node from Webform Submissions."),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_REQUIRED,
 * )
 */

class UpdateNodeWebformHandler extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */

  // Fetch & Update node object from webform-submission.

  // Function to be fired while submitting the Webform.
  public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
    // Get an array of the values from the submission.
    $values = $webform_submission->getData();

    // The webform has an element text field with machine name (update_nid) which
    // contains the node ID of the node to be updated.
    // This is the part where to fetch the node by the value of (update_nid) element.
        Some code here

    // This is the node Updating part.
    $created = $entity->updated->value;
    date_default_timezone_set('GMT');
    $createdadd5 = date('Y-m-d\TH:i:s', $created + 5 * 60);
    $entity->field_article_datetime->value = $createdadd5;

    // This is the node Saving part.
    $node->save();
  }
}

Answer: I can't think of a solution with just tokens. Here is a quick and dirty solution without tokens
Setup your Article datetime field so that has a default relative time of +5 minutes

You can hide this field with css so the user will not change it or you can do it in a hook_form_alter function in your MODULENAME.module file
// adjust node_article_form for your content type
if($form_id == 'node_article_form'  || $form_id == "node_article_edit_form"){
  $form["field_article_datetime"]['widget'][0]['value']['#attributes']['readonly'] = 'readonly';
}

Of course if a user takes much time to fill the form the set datetime might not reflect exactly the NODE CREATION TIME +5 minutes (as a datetime is set on form creation time)
If the above is not good enough you can probably use hook_entity_presave to adjust the time to be EXACTLY the creation time +5 minutes.
function MODULENAME_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  // adjust article to reflect your content type
  if ($entity->bundle() == "article" && $entity->isNew()) {
    $created = $entity->created->value;
    date_default_timezone_set('GMT');
    $createdadd5 = date('Y-m-d\TH:i:s', $created + 5 * 60);
    $entity->field_article_datetime->value = $createdadd5;
  }
}

NOTE: if you want to update the timer even on node update you can just delete the && $entity->isNew() part.
Comment: @ElieMasaad my solution is also complete and tested,  I have added a NOTE for what to do when the node is updated (which is not mentioned in your question original or update1).  Webform involvement was not in the original question either and still its not clear how it relates to article content type.  It seems you have added details to the question that change the approach to the solution.  Please try the proposed solution instead of asking for a change in direction of the solution.
Comment: Your first solution is perfect but as you said is not good enough bcz the default time is set only on form creation time. I might have a workaround solution but I need your coding skills since mine are so limited! Please refere to the update #1 of my question. Thank you
Comment: The is a second part that overcomes the first problem. Did you try it ? Perhaps you missed something ?
Comment: If you refer to the customwebformhandler code posted in the question, you will see that I left empty the part of fetching the node because I didn't know how to do it... In addition, I am not 100% sure if the part related to updating the entity is is correct or not...

Can you please check my above code ?
Comment: I forget to mention in my question I need also to **update** the `field_article_datetime` to be equal to `updated time + 5 minutes` every time the article node is updated...
Can you alter the code posted in your above answer to fit my requirement here ?
Comment: Webform was never mentioned in the original question, this confuses things so you better revisit and update your question accordingly.  What is the relation of webform and article ?   About your 2nd comment above I have already given you a way to update `field_article_datetime` to `update time + 5min` in my answer above .  Also note that your original question has a complete solution as I posted above.
Comment: Your answer is valid upon creating a new node... However, I need also to update the `field_article_datetime` to `update time + 5 min` every time the node article will be **updated**... Also my original question has a **half-complete** solution because the code is not yet completed (Not sure how to finish it)... *I will check my question and update it accordingly for you to better understand my requirement.
Comment: apologizes for the misunderstanding and thank you for the great support you provided and yes this works for me but because of this discussion, a new question popup in mind which i hope you can have a look to it: https://drupal.stackexchange.com/questions/277724/upon-submitting-a-webform-set-a-date-field-on-the-article-node-equals-to-curre


Does there exists a surjective group homomorphism from $(\mathbb{R},+)$ to $(\mathbb{Z},+)$?

Question: Examine whether there exists any surjective group homomorphism
(1) from $(\mathbb{Q}(\sqrt{2}),+)$ to $(\mathbb{Q},+)$
(2) from $(\mathbb{R},+)$ to $(\mathbb{Z},+)$
My try:
(1) I think $\phi :\mathbb{Q}(\sqrt{2})\rightarrow \mathbb{Q}$ given by $\phi(a+b\sqrt 2)=a$ works well here.
(2) I'm utterly clueless about this one.
I tried many things always hitting a road block:
I tried to figure of if $f:(\mathbb{R},+) \to (\mathbb{Z},+)$ such a homomorphism then how would a rational $\frac{a}{b} $ satisfying $f(\frac{a}{b}) =1$ look like. I eventually realized then it must be  $\frac{a}{b}=1$.
Now that we have $f(1)=1$ if we can each $a\in(0,1)$ figure out $f(a)$ then as every $r\in\mathbb{R}$ can be written as $r=n+a$ where $n\in\mathbb{Z}$ and $a\in(0,1)$ and $f(n+a)=f(n)+f(a)=n+f(a)$ we will be done.
I'm stuck here. Please help me out.
Comment: There's notion of divisibility for groups. Namely, group element $g$ is said to be $n$-divisible if $\exists h : h^n = g$. $n$-divisible group is one in which every element is $n$-divisible. You can easily show that property of being $n$-divisible is inherited by images, and $\mathbb R$ is obviously $n$-divisible for any $n$ while $\mathbb Z$ is not at all. (egreg's answer contains implicit version of this statement for 2-divisibility)
Answer: Part (1) is good.
For part (2) you're starting from the wrong side. There's no reason why $f(1)=1$. Indeed, if $f\colon G\to G'$ is a homomorphism of (additive) abelian groups, then also $a\mapsto 2f(a)$ defines a homomorphism.
Suppose there exists a surjective (group) homomorphism $f\colon\mathbb{R}\to\mathbb{Z}$. Then there is $r\in \mathbb{R}$ with $f(r)=1$.
Then $1=f(r)=f(2(r/2))=2f(r/2)$.
Answer: You have $f(1)=a$ for $n$ integer, $f(n)=an$ thus $f(n(1/n))=nf(1/n)=a$. Impossible if $n$ does not divide $a$.


Java: select object when parameter is given

Question: I'm a beginning Java-programmer
Now I have this problem:
I have a class named Producttype with a field named name.
I also have a class called Main. Now in the class Main I want to select an object from the class Producttype by asking the name.
How can I do this?
Thanks in advance
code of Producttype:
import java.util.*;
import javax.swing.*;

public class Producttype
{
    //velden
    private String naam;
    private String beschrijving;
    private double aankoopprijs;
    private double verkoopprijs;
    private int aantalGekocht;
    private int aantalVerkocht;

    //constructor
    /**
     * Constructor
     */
    public Producttype(String naam, String beschrijving, double aankoopprijs, double verkoopprijs){
        this.naam = naam;
        this.beschrijving = beschrijving;
        this.aankoopprijs = aankoopprijs;
        this.verkoopprijs = verkoopprijs;
        aantalGekocht = 0;
        aantalVerkocht = 0;
    }
   public void drukInfo(){
        System.out.println("-----------------------");
        System.out.println("Naam van het product: " + naam);
        System.out.println("Beschrijving van het product: " + beschrijving);
        System.out.println("Aankoopprijs: " + aankoopprijs + " euro");
        System.out.println("Verkoopprijs: " + verkoopprijs + " euro");
        System.out.println("Aantal gekocht: " + aantalGekocht + " stuks");
        System.out.println("Aantal verkocht: " + aantalVerkocht + " stuks");
        System.out.println("");
        System.out.println("Aantal stuks in stock: " + berekenAantalInStock());
        System.out.println("");
        System.out.println("Omzet momenteel: " + berekenOmzet() + " euro");
        System.out.println("Winst momenteel: " + berekenWinst() + " euro");
    }

In my 'Main' I got this:
private void printInfoOverProducttype()
    {
        String type = JOptionPane.showInputDialog("Give the name of the producctype you want info of.");

        String info = ??????????????????????????

        System.out.println(info);
    }

What I want is that "String info" in the method printInforOverProducctype() is executes the method drukInfo() from the class 'Producctype' from the object where the name equals string type
Comment: You may need to tell us more as your question seems incomplete and unaswerable to me. Do you have an array or collection such as an ArrayList of ProductType objects, and are you trying to select one whose name matches a particular String?
Comment: Please post source code of Main/Producttype classes.
Comment: Just read a book for Java beginners, or any tutorial on Java from the beginning.
Comment: It appears you want to treat a Java program as accessing a database.  Java doesn't work this way. If you want to create an object, you create it and if you want to lookup a collection you select it by key or index.
Answer: Your Main class needs to be able to access a Map of ProductType where the key is the name String:
public class Main {
    private Map<String, ProductType> products = new ConcurrentHashMap<String, ProductType>();

    public ProductType findProductTypeByName(String name) {
        return this.products.get(name);
    }
}


How to add term programmatically in Paragraph field?

Question: I have a paragraph with a taxonomy reference (autocomplete) field and I want to populate it when I create programmatically a pararagraph item.
I checked the option "Create referenced entities if they do not already exist" in this field.
I use this code, but I don't know how to find more informations to do that without Term::create (if it's possible) :
use Drupal\node\Entity\Node;
use Drupal\paragraphs\Entity\Paragraph;

        foreach ($field_value as $creator_type => $creator_name) {

            $paragraph = Paragraph::create(['type' => '_zotero_ref_creators']);
            //text field
            $paragraph->set('field_nom_prenom_createur', $creator_name);
            //taxo reference field
            $paragraph->set('field_type_createurs', $creator_type);

            //$paragraph->isNew();
            $paragraph->save();

            $paragraphn_field_value = array(
              'target_id' => $paragraph->id(),
              'target_revision_id' => $paragraph->getRevisionId(),
            );

            $node_reference->set('field_liste_contrib', $paragraphn_field_value);
          }

Answer: First load the node already created.
Second, create a paragraph like you did but for taxonomy term add "target_id" and for value choose a term id.
Set the paragraph value to your field of type paragraph from node. Also you need to save the node.
    $node = Node::load($nid);
     $paragraph = Paragraph::create([
            'type' => 'gallery_image',
            'field_type_createurs' => ['target_id' => $value],
          ]);
          $paragraph->save();

          $current[] = [
            'target_id' => $paragraph->id(),
            'target_revision_id' =>$paragraph->getRevisionId(),
          ];

   $node->set('your_field', $current);
   $node->save();

Varible $value is a term id.
Hope to help you.
Answer: It took awhile for this to sink in. Thinking of it as creating a paragraph entity on the node helped me with Paragraph::create. A first I was thinking of Paragraph::create as creating the paragraph type, which, of course, I had already created.
Here's some more example code that is mostly a repeat of @OPTASY's code. All the data is sanitized and, hopefully, the keys give a clear idea which fields are being referenced and when.
$node = Node::load($nid);

$current = [];
  $paragraph = Paragraph::create([
    'type' => 'my_paragraph_type',
    'field_from_my_paragraph_type' => ['target_id' => 1]
  ]);
  $paragraph->save();

$current[] = [
    'target_id' => $paragraph->id(),
    'target_revision_id' => $paragraph->getRevisionId(),
  ];

$node->set('field_from_my_content_type', $current);
$node->save();


Creating an Estimate in QBO Gives Error about LineDetail Type

Question: I am creating an estimate in QBO using the C# SDK. I am getting an error about LineDetail type not being included. Here's the JSON we are posting:
{"CustomerRef":{"value":"137"},
"CurrencyRef":{"value":"USD"},
"Line":[{"Description":"Roof - B1-011900908","Amount":527.48,"DetailType":"SalesOrderItemLineDetail","SalesItemLineDetail":{"Qty":1.0}}]}

I am getting this error
{"Fault":{"Error":[{"Message":"Required param missing, need to supply the required value for the API","Detail":"Required parameter Line.DetailType is missing in the request","code":"2020","element":"Line.DetailType"}],"type":"ValidationFault"},"time":"2019-12-09T12:38:25.648-08:00"}

Comment: I believe this `"DetailType":"SalesOrderItemLineDetail"` should be `"DetailType":"SalesItemLineDetail"`
Comment: Yea it is, add an answer and I'll give you the answer
Answer:
I am getting an error about LineDetail type not being included. Here's the JSON we are posting

{"CustomerRef":{"value":"137"},
"CurrencyRef":{"value":"USD"},
"Line":[{"Description":"Roof - B1-011900908","Amount":527.48,"DetailType":"SalesOrderItemLineDetail","SalesItemLineDetail":{"Qty":1.0}}]}

The parameter name and value for DetailType is:
 "DetailType":"SalesItemLineDetail"

Answer: On the line object I had
DetailType=LineDetailTypeEnum.SalesOrderItemLineDetail

Should have been:
DetailType=LineDetailTypeEnum.SalesItemLineDetail


Adding additional terms to a piecewise regression

Question: I am exploring the probability of flight in a seabird (1=flight, 0=no flight) using binomial logistic regression. My predictors are distance to a disturbance (continuous), hour of the day (continuous), site (factor), season (factor), sea state (dichotomous), and group size (dichotomous). I have explored the use of piecewise regression in relation to the distance to a disturbance as this variable spans a large range (out to 74 km) and there is no way that this is affecting flight at the largest distance.
When the model was fit with just reference to distance to a disturbance within the R program 'segmented' it points to a break in the data at 3.9 km. The slope up to this distance is negative and statistically significant while the slope estimate for distances further than 3.9 km is estimated to be 0 and non-significant.
I would like to now sequentially add in additional terms to the model to see if there is any reduction in the deviance when the additional terms are added. Can a term be added just to the section before or after the break? I cannot seem to find any information in the literature regarding this
My questions is can I do this? Or do I need to split the data into two chunks, before and after the breakpoint and explore additional terms this way.
Also the motivation to do this analysis is more to find and identify the breakpoint. Instead of adding in terms after I assess the breakpoint should I explore the breakpoint within a the model including all the terms? Would this find the break in the data in relation to the other terms or does the algorithm completely ignore the other terms in the model when searching for a break in the distance to disturbance variable.
Thanks,
Answer:
Can a term be added just to the section before or after the break?<

Sure. You just use an interaction term with the dummy variable for break (0 before break, 1 after break) --> variable*dummy
But are you sure you want to do this? You have the domain knowledge, but it is sort of like including the interaction without the main effect. Most would do variable + variable*dummy, this does make interpretation harder but usually seems reasonable to assume there is some effect prior to breakpoint

Instead of adding in terms after I assess the breakpoint should I
  explore the breakpoint within a the model including all the terms?

As far as I remember the segmented package allows you to do both. In my mind both are reasonable. If it is easy would prefer to do the latter, but often doesn't matter.

I have explored the use of piecewise regression in relation to the
  distance to a disturbance

I like piece-wise regression. But if you're trying to incorporate non-linearity in your model, some prefer GAM or restricted cubic splines. If this is for publication, I'd look at what the standard is in your field.
Comment: thanks for the advice. Would the addition of terms prior to searching for the break-point change the estimate of the break-point? The research question is more focused on finding the break as this can be thought of as an ecological threshold. I just wanted to make sure that I am accounting for the confounding variables that are known to affect flight probability. If there is no difference in how the break-point is determined I am less concerned about the other factors.
Comment: My understanding is the the {segmented} package uses the full model you've specified in determining the cut-point. So if you add additional terms it will include these in the estimated break-point.
Comment: Also wanted to add someone posted r code to do this yourself: http://www.r-bloggers.com/r-for-ecologists-putting-together-a-piecewise-regression/


Doubt on paracompactness and lorentz signature.

Question: While the study of Manifolds are quite interresting by itself, we know that General Relativity have on it's core the study of Manifolds. When we transport the Manifold mathematical structure to General Relativity it's quite common to don't pay atention about the physical motivations about the very basic constructs, i.e.,

A Spacetime is a four-dimentional, paracompact,connected,secound countable,hausdorff, locally Euclidean, topological manifold. $\tag{1}$

I found a particular physical motivation on $[1]$ which states:

The requirement that a spacetime is paracompact, ensures that it always admits a metric with lorentzian signature $\tag{2}$

Well, this have a form of a Theorem, and better: a theorem with physical implications about a highly abstract concept (paracompactness). I mean, the need of a topological space is to stablish the physical fact of a countinuous world. I think you could say that paracompactness is a requirement because physically our classical world have lorentzian signature.
So my doubt is: how can I prove the steatament $(2)$? Or, in other words, is there some reference which have this proof already done or, could you give me a hint?
$$ * * * $$
$[1]$ DE FELICE.F; CLARKE C.J.S. Relativity on Curved Manifolds
Answer: This is false.  For instance, $S^4$ satisfies all the conditions of (1) but does not admit a Lorentzian metric.  (This follows from the fact that the tangent bundle of $S^4$ does not contain a line bundle as a subbundle; see the answers to this question on MO for more details and discussion.)
I would also remark that (1) is generally very poorly written with significant redundancy among the listed conditions, and gives the impression of being written by someone who is not very familiar with the topic.  Definitions of "topological manifold" vary, but all of them include "locally Euclidean", and most include "Hausdorff" and either "second-countable" or "paracompact".  Any second-countable Hausdorff locally Euclidean space is automatically paracompact.  Any connected paracompact Hausdorff locally Euclidean space is automatically second-countable.
Comment: So why, physically, we need paracompactness?
Comment: It would be reasonable to say that we don't.  In any case, as I mentioned, the assumption of paracompactness follows from the other assumptions and so is redundant.


Creating a Column in Dataframe by slicing a string in the DF with start and end position from the integers in another column

Question: I am working on a dataframe which has strings  in a column  and integers in another  2 columns. Now I need to create a new  column which is a slicing of the string with start and end postion form the integer columns
Comment: Please provide enough code so others can better understand or reproduce the problem.
Answer: <code>import pandas as pd

df = pd.DataFrame([
    ['hello', 0, 2],
    ['world', 1, 3],
], columns=['string', 'start', 'end'])
mapper = lambda r: r.string[r.start:r.end]
df['sliced_string'] = df.apply(mapper, axis=1)axis=1)
print(df)
</code>
produces
<code>  string  start  end sliced_string
0  hello      0    2            he
1  world      1    3            or
</code>


MKMapViewDelegate: substitute of listening to region change event

Question: I have a map that helps a friends find each other. The number of friends are too high and scattered around the map. I want to only load the friends from my api that pertain to the current view the user sees. If the user swipes, different set of users are displayed.
Looking at the MKMapViewDelegate events, the only place suitable for what I want to do is:
<code>optional func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool)
</code>
but according to documentation, I shouldn't be adding complex code to it:
Discussion
This method is called whenever the currently displayed map region changes. During scrolling, this method may be called many times to report updates to the map position. Therefore, your implementation of this method should be as lightweight as possible to avoid affecting scrolling performance.
I've looked at the other events, no other events will give me what I want. Which other MKMapViewDelgate event do you think I should utilize!?
Comment: I'm using this function, and i realize that this function will be called when your map end dragging. You can check it, very easy.
Comment: @Tien I'm already using it and its getting large. The documentation note is alarming against overloading its logic. I was wondering if I shouldn't use this, then which event should I use?
Answer: Now I know quite a bit about it.
The answer is simply: No, there isn't! Sometimes there is no escape from adding more logic to that event. I had to do some workarounds by laying out switches to prevent it from further processing or allowing through.


can't find android project template in intilij idea

Question: I use intellij-idea and when I click on the project new -} on this page, I don't see Android.
I tried several ways, but it didn't work, like installing a plugin and changing a series of settings, but it didn't work.
Comment: Please provide enough code so others can better understand or reproduce the problem.
Answer: Android Studio
Google offers free-of-cost a special edition of IntelliJ built specifically for Android development: Android Studio.
IntelliJ with plugins
According to this tutorial, apparently you can do Android development if you install plugins for:

Android
Android Design Studio


how to sort ruby array by model action?

Question: I'm trying to make a project like cafe search service based on social network, and I want to sort Cafe array by points which other users gave.
class Cafe < ActiveRecord::Base

  belongs_to :user

  has_many :posts, dependent: :destroy
  has_many :tags, dependent: :destroy
  has_many :payments, dependent: :destroy
  has_many :payinfos, dependent: :destroy
  mount_uploader :image,CafeimageuploaderUploader
  mount_uploader :thumnail,CafeimageuploaderUploader

  geocoded_by :address
  after_validation :geocode
  def avg
    total = 0
    posts.each do |c|
      total += c.score
    end
    if posts.count == 0
        0
    else
      total.to_f / posts.count
    end
  end
end

this is Cafe model, 'avg' is point average that users gave.
class CreatePosts < ActiveRecord::Migration
  def change
    create_table :posts do |t|

      t.string :content              , null: false, default: ""
      t.string :image
      t.string :address              , null: false, default: "위치정보 없음"
      t.string :hashstr
      t.datetime :writtentime
      t.integer :user_id
      t.integer :cafe_id             , null: false, default: 0
      t.integer :score, default:0
      t.timestamps null: false
    end
  end
end

Here's post columns.
What I want to do is sort new Cafe array by this avg action.(is it called model action, right??)
give me some advice, thank you.
Comment: _Sidenote:_ `posts.each { |c| total += c.score }` is quite inefficient. Use `posts.sum(&:score)` instead to move calculation to the db layer.
Answer: I would add an attribute average_score to cafe model and a after_save callback method to post model. If a post will be safed you take all posts of a cafe (by the foreign key), calculate the average score and save it to the cafe or you trigger a method of the cafe model to do that. So you can sort your cafes easily.
Answer: Let use db query, it is more efficient. (assume Cafe's table name is cafes)
Cafe.joins("LEFT OUTER JOIN (SELECT cafe_id, AVG(score) AS avg_score
                             FROM posts
                             GROUP BY cafe_id
                            ) AS temp
            ON cafes.id = temp.cafe_id
          ").order('temp.avg_score DESC NULLS LAST')

Ideally, we calculate the average score in a temporary table first then join with Cafe via cafe_id. After that, we can easily use order with avg_score.
Because we are using LEFT OUTER JOIN, the avg_score of cafe which doesn't have any post will be NULL, so we use NULLS LAST to ensure that cafe will be in the end.

how to sort ruby array by model action?


Pilha não funciona corretamente no Codeblocks

Question: Esse código abaixo compila tanto no Codeblocks quanto no Visual Studio, só que a saída é diferente no Codeblocks. Pelo VS eu não excluo nada do código abaixo, é só rodar e pronto, agora no Codeblocks eu tirei essas duas bibliotecas:
#include "stdafx.h"
#include "windows.h"

e adicionei essas:
#include <stdio.h>
#include <stdlib.h>

mudei o scanf_s para scanf
e compilei, compila normalmente, só que a saída tá errada, isso no Codeblocks. No VS é tranquilo funciona normalmente.
Queria saber o que há de errado pelo Codeblocks, quero rodar com saída perfeita no Codeblocks.
// pilha.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "windows.h"

#define TAM_PILHA 2
#define NUM_ENTRA 5

void empilha(int *pilha, int *topo, int valor)
{
if (*topo <= TAM_PILHA)
{
    pilha[*topo] = valor;
    (*topo)++;
}
else
{
    printf("Pilha Cheia\n");
}
}

int desempilha(int *pilha, int *topo)
{
if (*topo > 0)
{
    (*topo)--;
    return pilha[*topo];
}
else
{
    printf("Pilha Vazia\n");
}
}

int main()
{
int pilha_par[TAM_PILHA], pilha_impar[TAM_PILHA], topo_par = 0, topo_impar = 0;
int i = 0, num_do_usuario = 0;
for (i = 0; i < NUM_ENTRA; i++)
{
    printf("\nEntre com um numero: ");
    scanf_s("%d", &num_do_usuario);

    if ((num_do_usuario % 2) == 0)
    {
        empilha(pilha_par, &topo_par, num_do_usuario);
    }
    else
    {
        empilha(pilha_impar, &topo_impar, num_do_usuario);
    }

}

printf("\n\nNumeros pares sao: ");
while (topo_par > 0)
{
    printf("%d ", desempilha(pilha_par, &topo_par));
}

printf("\n\nNumeros impares sao: ");
while (topo_impar > 0)
{
    printf("%d ", desempilha(pilha_impar, &topo_impar));
}

printf("\n\n");

system("pause");
return 0;
}

Errado:

Outro cenário de erro:
Comment: E o que deu errado?
Answer: Você está fazendo o empilhamento errado.
Suas pilhas tem tamanho TAM_PILHA, logo a verificação na hora de empilhar deve ser:
if (*topo < TAM_PILHA)

ao invés de
if (*topo <= TAM_PILHA)

Eu copiei teu código, compilei e executei no Windows 10. Segue as entradas e saídas:
Entradas

10, 10, 15, 15, 15

Saída

Numeros pares sao: 10 15
Numeros impares sao: 15 15 15

Já em outro teste foi lido apenas 4 valores. Ou seja, o programa não mostrava resultados esperados e nem tinha o comportamento desejado. Novamente no Windows 10.
Por outro lado, no Ubuntu 16.04 as entradas e o resultado foram:
Entradas

10, 10, 15, 15, 15

Saída

Numeros pares sao: 10 10
Numeros impares sao: 15 15 15

O resultado, por mais que pareça correto, continua errado. Pois a TAM_PILHA vale 2, ou seja, a pilha deveria guardar somente 2 elementos.
Fazendo a alteração listadas lá em cima o programa executa como o esperado e produz os resultados corretos.
Ps1: Usei os cabeçalhos stdlib.h e stdio.h.
Ps2: Compilei com GCC e executei no cmd windows. Em ambos os códigos(original e alterado).
Ps3: Compilei com G++ e executei no bash do Ubuntu.
Comment: Como assim lendo o último vetor? Se você definiu a pilha com tamanho 2, então ela deve ser capaz de guardar 2 elementos. Se você está lendo 5 entradas, não vai caber todas as entradas nas 2 pilhas. Acabei de rodar seu código em um Ubuntu 16.04 e rodou certo. O único problema é que o teu código guarda na posição pilha[2]. Esta posição não existe na pilha, porém a linguagem C te permite fazer isso. Na verdade seu código precisa de apenas 1 alteração, no caso a primeira que eu citei.
Comment: De acordo com este print o funcionamento está OK. Tudo ocorreu como o esperado. A pilha par contém apenas números pares e a pilha ímpar contém apenas números ímpares. E por fim, não foi possível empilhar mais números na pilha ímpar, pois esta já estava cheia(2 elementos).
Comment: Exatamente, eles não deveriam estar sendo impressos. Isso acontece pois a pilha tem o tamanho definido pela constante TAM_PILHA. Caso TAM_PILHA valha 2, então a pilha poderá empilhar no máximo 2 elementos. Caso valha 3, então a pilha poderá empilhar no máximo 3 elementos. No seu exemplo, provavelmente ela está valendo 2. Então ao tentar inserir um terceiro elemento haverá um erro de " pilha cheia". Ou seja, quando acontecer o processo de desempilhamento, este número não estará na pilha e consequentemente não será desempilhado.
Comment: Olha eu fiz isso que vc disse e não surtiu de primeira o efeito esperado, pelo menos aqui no CB. Não está lendo o último vetor.
Comment: me mande uma mensagem que mostro no team view
Comment: Poste alguns prints para ficar mais claro. Talvez estamos falando de problemas distintos.
Comment: tudo bem ja postei aí
Comment: Não tem como isso está certo isso, o número 3 e 5 não estão sendo impressos, e olho outro cenário que postei aí.
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/55436/discussion-between-thiago-ferreira-and-carlos-givisiez).


Sending sms when device shutting down

Question: I want to make a broadcast receiver that sends a simple sms to some phone number when the device is shutting down.
Here is my code:
public class ShutDownReceiver extends BroadcastReceiver {

SmsManager sms = SmsManager.getDefault();

@Override
public void onReceive(Context context, Intent intent) {

    Log.i("Log","Device shutting down NOW!");

                        //An actual phone number here
    sms.sendTextMessage("0670#######", null, "This is a text for sms", null, null);

       }

}
So far the results:
I can clearly see the log message when i turn off the device.
So the BroadcastReceiver working well on shut down, but NO sms sending, NO Exceptions.
I tryed this sms sending method with a simple button click, with absolute success.
So, i know that the sms sending method is correct, i know that the shutdown receiver is correct, BUT for some reason it is not sending the sms.
Any ideas about this?
(I work with real devices, not emulators.)
Comment: I am trying to achieve the same it is not possible because related system services have been disabled. If anyone able to achieve this please let me know.
Answer: I'm using ....
SmsManager.getDefault().sendTextMessage(number, null, smsText, null, null);

... and that works pretty well as long as

the phone number is valid
the message text isn't too long
the telephony service is available (have you tried another event to ensure that the service isn't closed before you receive the shutdown?)
android.permission.SEND_SMS is granted

Hope this helps ... cheers!
Comment: What I was thinking of, is: when your device is shutting down - could it be that at the point of time the ShutdownReceiver fires you can't send messages anymore because related system services have been disabled? Well, I have no idea ... that was just a guess
Comment: err.. What do you mean by number 3? I can send the sms elsewhere, but cannot send at shutdown.. I still got the log message about "shutting down".
Comment: Yea this is the first thing i could imagine too, it would be nice if someone could point me straight to this.

Sending sms when device shutting down


Teste unitário de uma pesquisa SQL no Junit

Question: Preciso de uma ajuda para fazer o teste unitário no Junit.
Como faço o @Test do método abaixo:
<code>public static StringBuilder findSQLPA() {
    StringBuilder sql = new StringBuilder();
    sql.append(" select  fi1.co_carteira as carteira, ");
    sql.append("  fi1.nu_cpf_cnpj as cpf_cnpj, ");
    sql.append(" fi1.co_fundo_siart as siart, ");
    sql.append(" fi1.no_fundo as fundo,   ");
    sql.append(" fi1.no_cotista as cotista, ");
    sql.append(" fi1.nu_operacao_conta as op, ");
    sql.append(" fi1.nu_conta as conta,  ");
    sql.append(" fi1.dt_mvtco_antiga as dt_antiga, ");
    sql.append(" fi1.dt_mvtco_recente as dt_recente, ");
    sql.append(" fi1.pc_taxa_administracao as taxa, ");
    sql.append(" fd.no_tipo_macro_fundo as tipo_fundo, ");
    sql.append(" fi1.vr_saldo_bruto,    ");
    sql.append(" fi1.vr_saldo_liquido, ");
    sql.append(" fi1.vr_potencial_mes, ");
    sql.append(" fi1.vr_pontecial_ano, ");
    sql.append(" fi1.vr_potencial_12m , ");
    sql.append(" fi1.nu_unidade_dire as dire, ");
    sql.append(" fi1.nu_unidade_sr as sr,   ");
    sql.append(" fi1.nu_unidade as age  ");
    sql.append(" from cfism001.cfitb001_fundo_investimento fi1 ");
    sql.append(" inner join cfism001.cfitb007_resumo_cliente fi ");
    sql.append(" on fi.nu_cpf_cnpj = fi1.nu_cpf_cnpj  ");
    sql.append(" and fi.nu_unidade_dire = fi1.nu_unidade_dire ");
    sql.append(" and fi.nu_unidade_sr = fi1.nu_unidade_sr ");
    sql.append(" and fi.nu_unidade = fi1.nu_unidade ");
    sql.append(" and fi.dt_importacao = fi1.dt_importacao ");
    sql.append("   left join icosm001.icotbu24_unidade u ");
    sql.append(" on (fi1.nu_unidade = u.nu_unidade AND u.dt_fim is null AND u.ic_ultima_situacao = 'AT') ");
    sql.append(" left join  cfism001.cfitb002_tipo_macro_fundo fd     ");
    sql.append(" on (fi1.co_tipo_macro_fundo = fd.co_tipo_macro_fundo) ");
    sql.append(" where fi1.dt_importacao = :dt_importacao  and fi1.nu_unidade = :nu_unidade  @filtro ");
    return sql;
}
</code>
Answer: Testes que envolvem consulta ao banco de dados não são chamados de testes unitários. Estes tipos de testes são chamados de testes de integração, embora não necessariamente apenas os testes de integração testem o banco de dados (testes funcionais, por exemplo, também o fazem).
Testes de integração são complicados de se fazer sem a ajuda de algum framework, pois seu teste vai envolver a criação (ou uso) de um banco de dados para o teste, de uma conexão JDBC, preparar os dados a serem consultados, chamar o método da classe que faz a consulta, etc.
Usando um framework para este teste facilita muito. No Spring, por exemplo, um teste do seu SQL ficaria algo como:
<code>@RunWith(SpringRunner.class)
@SpringBootTest
class FundoInvestimentoRepositoryIT {

    @Autowired
    private FundoInvestimentoRepository repository; //o SQL seu estaria implementado dentro de um método do FundoInvestimentoRepository

    public void testarConsulta() {

        repository.inserir(new FundoInvestimento("1", "23456")); //valores fictícios para dar um INSERT no banco de dados e consultá-los

        FundoInvestimentoVO fundoVO = repository.consultar();
        assertEquals("23456", fundoVO.getConta());
    }

}
</code>
Comment: Conheço sim. O Mockito é um framework bem robusto usado largamente pelo framework do Spring para testes de integração, inclusive. Mas ele sozinho, para o teste que quer fazer, é só uma ferramenta auxiliar. O "grosso" de um teste de integração é um framework como o Spring que faz. Aqui explica um pouco sobre os vários tipos de testes de integração e como o Mockito aparece no meio deles: https://www.baeldung.com/spring-boot-testing
Comment: primeiramene obrigado pelo retorno. Vejo que o pessoal comenta do framework Mockito. Você conhece?


Atiyah Bundles over Elliptic Curves

Question: I am reading the paper "Vector Bundles over Elliptic Curves" by Atiyah. I get a problem in understanding the "uniqueness" of the Atiyah bundles.
Let me fix the notation first: $X$ is an elliptic over an algebraic closed field. $\mathcal{E}(r,0)$ is the set of all indecomposable holomorphic vector bundles over $X$, which have rank $r$ and degree $0$
As is stated in Lemma 16 (I am focusing on $d=0$ case):
"For any $E'\in\mathcal{E}(r',0)$ with $\Gamma(E')\neq 0$, there exists $E\in\mathcal{E}(r,0)$, unique up to isomorphism, given by the extension
$$0\rightarrow I_1\rightarrow E\rightarrow E'\rightarrow 0,$$
where $I_1$ is the trivial line bundle of $X$."
However, in the simplest case $r'=1$, any self extension of $I_1$ gives such a $E$ and since the space of isomorphism class of self extensions of $I_1$ is given by
$$H^1(X,Hom(I_1,I_1))=H^1(X,I_1)=H^{0,1}(X)=\mathbb{C}.$$
Hence every non-trivial element in $H^1(X,Hom(I_1,I_1))$ would correspond an indecomposable self extension of $I_1$ with degree $0$ and therefore such $E$ can't be unique.
I think I must get something wrong but I don't see that. It would be my pleasure if somebody can point out what I get wrong. Thank you very much!
Comment: I guess his English could have been less ambiguous here. Very nice paper still.
Answer: The solution to your paradox is that two extensions  $$0\rightarrow I_1\rightarrow E\rightarrow I_1\rightarrow 0 \;\;(\mathcal E)\;\;\operatorname {and}\quad0 \rightarrow I_1\rightarrow E'\rightarrow I_1\rightarrow 0  \;\;(\mathcal E')$$ can be non isomorphic as extensions ($\mathcal E\not \simeq \mathcal E'$) and yet have middle vector bundles which are isomorphic as vector bundles: $E\simeq E'$.
For example if, for some $\lambda \in \mathbb C^*$, $(\mathcal E')=\lambda\cdot(\mathcal E)\in H^1(X,Hom(I_1,I_1))=\mathbb{C}$ we will certainly have $E\simeq E'$ as vector bundles.
This explains why there is up to isomorphism only one non-trivial rank two  vector bundle which is an extension of the trivial line bundle by itself.
Comment: Ah ha! Let's see if I get your answer correctly. You are saying that because $H^1(X,Hom(I_1,I_1))$ is parametrizing EXTENSIONS, not just the bundle itself. And in the above case, there are only one direction to do extension, so as bundles, they are all the same.
Comment: Exactly, Marco!

Atiyah Bundles over Elliptic Curves


Não consigo fazer meu resultado aparecer, aparece apenas NaN na caixa IMC.(HTML/JavaScript)

Question: Sempre aparece NaN na caixa que deveria sair o resultado, não consegui algo que me ajudasse na internet.

       Cálculo do IMC !

    <form class="form-horizontal">
        <fieldset>

       <legend>Caculadora de IMC</legend>

          Altura

          <input id="altura" name = "altura"
                type="text"
                placeholder="#,## m"
                class="form-control input-md">

          Peso

                <input id="peso"
                     name="peso"
                     type="text"
                     placeholder="###,## kg"
                     class="form-control input-md">

                     <type = "button" class="btn btn-primary"
                         id = "resultadoIMC"
                         onclick = "calcularIMC()">Calcular IMC</button>

             IMC

                     <input id="imc1"
                     type = "text"
                     class="form-control input-md">

        </fieldset>
        </form>

Answer: Faça um parseFloat pra que ele converta a string que está sendo capturada no campo de altura em um valor de número flutuante:

var altura = parseFloat(document.getElementById("altura").value);
Comment: Valeu amigo, uma coisa bobinha que nem passou pela cabeça deu certo !
Answer: Olá,
Por mais que você preencha seus campos <input> com apenas números, eles ainda aceitam letras e outros caracteres, portanto o valor capturado é uma string.
Você deve utilizar a função parseFloat() quando atribui estes valores às variáveis. Veja:
calcularIMC = function (){
    var peso = parseFloat(document.getElementById("peso").value);
    var altura = parseFloat(document.getElementById("altura").value);
    var imc = (peso/(Math.pow(altura,2)));
    document.getElementById("imc1").value = eval(imc);
}

Além disto, para que o javascript capture o float corretamente, o número deve conter ponto, e não vírgula. Ex: Altura 1.88.
Para tratar isto você pode utilizar o método replace(). Desta forma:
var altura = document.getElementById("altura").value;
altura = altura.replace(",", ".");
altura = parseFloat(altura);

Comment: Obrigado pelas dicas, irei usar !


How to use properties in functions

Question: Please see the code below

function tehran() {
    // some code
}

tehran.tower = "Milad";

how i can print 'tower' properties?
This is possible?
Comment: Would you mind elaborating a bit on what you mean by "use 'tower' properties"?
Comment: Does using `console.log` not work?
Comment: @jps functions are also objects and can have properties. So, this is *valid code*. Whether it makes sense is another matter - there is an extremely narrow set of use-cases where you'd really want this.
Comment: For example, I want to print it
Comment: @VLAZ thanks - removed my comment to avoid confusion.
Answer: functions are just callable objects, with a special meaning for this which is not self-referencing like an object method.
However, you can always refer to the function itself:
function tehran() {
  console.log(tehran.tower); // "Miland"
}

tehran.tower = "Milad";

tehran();

How to use properties in functions


Find the conditional probability density function of $X$ given $Y=y$

Question: Let $X$ and $Y$ be two random variables with joint density function:  $f_{XY}(x,y) = \begin{cases} {5x^2y}&-1\leq x\leq1, 0<y\leq|x| \\{0}&\text{otherwise} \end{cases}$
Find $f_{X|Y}(x|y)$ the conditional probability density function of $X$ given $Y =
y$. Sketch the graph of $f_{X|Y}(x|.5)$
The graph part isn't the confusing issue as I feel once I get to it, I will be able to solve it. My issue is finding the proper $f_{X|Y}(x|y)$. I thought I would do $f_y(y)=\int_{-1}^{1}5x^2ydx$ and I get $10y\over3$ then I plug that into the formula to get $5x^2y\over{10y\over3}$ $= {3x^2\over2}$ However, the answer is ${3x^2\over{2(1-y^3)}}$ What am I doing wrong? I feel like it has to do with my limits of integration but I don't see how it isn't $-1$ to $1$.
Comment: Your computation of $f_Y$ is wrong, actually, $$f_Y(y)=\int_{|x|>y}f_{X,Y}(x,y)dx=\int_{-1}^{-y}\cdots dx+\int_y^1\cdots dx$$
Comment: This becomes more or less direct as soon as one writes down $f_{X,Y}$ as a true function defined on $\mathbb R^2$, that is, $$f_{X,Y}(x,y)=5x^2y\mathbf 1_{0<y\leqslant|x|<1}$$ then the usual formula $$f_Y(y)=\int_\mathbb Rf_{X,Y}(x,y)dx$$ defines a true function $f_Y$ on $\mathbb R$ and yields what I wrote in my first comment if $|y|<1$ and $0$ otherwise.
Comment: *Typo: ...and yields what I wrote in my first comment if $0<y<1$ and $0$ otherwise.
Comment: @Did would you mind elaborating on why this is the case? For all the other problems, including some sample SOA problems, I did it the same way as I did in my attempt up above and got the correct answers. Is it due to this one involving $|x|$?
Comment: The conditional density "answer" ${3x^2\over{2(1-y^3)}}$ that you gave in the question is not right either unless you put in various constraints on the values that $x$ and $y$ take on.
Answer: First, sketch the support of $(X,Y)$, which is $$(-1 \le X \le 1) \cap (0 < Y \le |X|).$$  This describes a "bow-tie" shaped region in the Cartesian coordinate plane, consisting of two right triangles with vertices $$\{(0,0), (1,0), (1,1)\}, \quad \{(0,0), (-1,0), (-1,1)\}.$$  The symmetry of this region is clear, and the line of symmetry is the $y$-axis.

The plot below visualizes the joint density in three-dimensional space:

For a fixed $Y = y$, the permissible values of $X$ comprise the union of two intervals; that is to say, $$(X \mid Y = y) \in [-1, -y] \cup [y, 1].$$  So, the interval of integration for the marginal density of $Y$ is not $[-1,1]$ but the interval above:  $$f_Y(y) = \int_{x=-1}^{-y} 5x^2 y \, dx + \int_{x=y}^1 5x^2 y \, dx.$$

The above animation plots $X$ for specific values of $Y = y$ for $y \in (0,1]$.  The conditional density $f_{X\mid Y}(x \mid y)$ is proportional to this plot in such a way that the area under the curve is made equal to $1$.  In other words, the function $f_{X \mid Y}$ is simply a scaled version of this animation such that the area under the curve remains $1$ regardless of the choice of $y$:

Compare this with the previous animation.
Another way to reason about this is to observe that the support requires that $|X| \ge Y$:  hence, on the interval $X \in [-y,y]$, $f_{X,Y}(x,y) = 0$, thus writing $$f_Y(y) = \int_{x=-1}^1 f_{X,Y}(x,y) \, dx = \int_{x=-1}^1 5x^2 y \, dx$$ fails to reflect that the joint density is not $5x^2 y$ when $-y \le x \le y$.  We can correct for this by the suitable use of indicator functions; for example, we could have instead written the joint density as $$f_{X,Y}(x,y) = 5x^2 y \;\mathbb 1(|x| \ge y), \quad (x,y) \in [-1,1] \times [0,1].$$  This reminds us that integration in the rectangular region $[-1,1] \times [0,1]$ comes with an extra condition for the integrand to be positive:  $$f_Y(y) = \int_{x=-1}^1 5x^2 y \; \mathbb 1(|x| \ge y) \, dx = \int_{x=-1}^{-y} 5x^2 y \, dx + \int_{x=y}^1 5x^2 y \, dx.$$  We could go overboard and write the whole density as $$f_{X,Y}(x,y) = 5x^2 y \; \mathbb 1 (0 < y \le |x| \le 1), \quad (x,y) \in \mathbb R^2$$ but this isn't really necessary as we already intuitively grasp that the convex boundary of the support is rectangular, leading to a natural choice of the lower and upper limits of integration except when dealing with the nonconvex part.


ACL list - SELF

Question: OS - Windows Server 2008 R2 Standard
What do you mean by SELF in DNS Zone Security Setting. ( Access Control List )
Please see the print-screen below for more info.
Answer: The Standard SID for Principal Self or Self is S-1-5-10
A placeholder in an ACE on a user, group, or computer object in Active Directory. When you grant permissions to Principal Self, you grant them to the security principal represented by the object. During an access check, the operating system replaces the SID for Principal Self with the SID for the security principal represented by the object.
In Short, in DNS Security Properties, it is probably Computer Object.
For more Detail - http://technet.microsoft.com/en-us/library/cc978401.aspx

ACL list - SELF


Cannot create simplenews content

Question: I have simplenews module installed on drupal 7.50

When accessing #overlay=node/add/simplenews
I get a NOT FOUND, so I cannot create any newsletter content. Tried to flush cache but didn't work. Any ideas?
Comment: You are getting "page not found" or "access denied"
Answer: I have tested on Drupal vanilla installation 7.50 and simplenews version 7.x-1.1 stable release, the link works perfect to add simplenews nodes.
I would recommend you
<code> -  Re install simplenews module
 -  Check if you see simplenews content type under structure>>content types
 -  Check if you see any error in your error logs.
 -  Check if you are using dev version of simplenews module
</code>
Comment: Thanks, reinstall worked... don't know why it didn't in first place.

Cannot create simplenews content