Cannot load active record?

Question: I have a gem that I am trying to test some mixins in, these mixins would be used in a model to determine relationships and add helper functions, the issue I am having is that when I go to test these mixins in my gem I get: uninitialized constant ActiveRecord (NameError).
In my rails_helper.rb (rspec 3.1) I added the following:
ActiveRecord::Base.establish_connection(:adapter => 'sqlite3')
load(File.dirname(__FILE__) + "/schema.rb")

In my spec/models/user.rb I then added:
describe "Test the user model mixin" do

  class User < ActiveRecord::Base
     # This is what I am testing
    include CoreModels::Models::User
  end

  context "Fail to find a user" do
    it "should return nil on a user not existing" do
      User.find_by_first_name('sally').should == nil
    end
  end
end

When Run I get:
$ bin/rspec
/Users/Adam/Documents/Rails-Projects/core_models/spec/models/user_spec.rb:4:in `block in <top (required)>': uninitialized constant ActiveRecord (NameError)
    from /Users/Adam/Documents/Rails-Projects/core_models/.bundle/gems/gems/rspec-core-3.1.7/lib/rspec/core/example_group.rb:325:in `module_exec'
    from /Users/Adam/Documents/Rails-Projects/core_models/.bundle/gems/gems/rspec-core-3.1.7/lib/rspec/core/example_group.rb:325:in `subclass'
    from /Users/Adam/Documents/Rails-Projects/core_models/.bundle/gems/gems/rspec-core-3.1.7/lib/rspec/core/example_group.rb:219:in `block in define_example_group_method'
    from /Users/Adam/Documents/Rails-Projects/core_models/.bundle/gems/gems/rspec-core-3.1.7/lib/rspec/core/dsl.rb:41:in `block in expose_example_group_alias'
    from /Users/Adam/Documents/Rails-Projects/core_models/.bundle/gems/gems/rspec-core-3.1.7/lib/rspec/core/dsl.rb:79:in `block (2 levels) in expose_example_group_alias_globally'
    from /Users/Adam/Documents/Rails-Projects/core_models/spec/models/user_spec.rb:2:in `<top (required)>'
    from /Users/Adam/Documents/Rails-Projects/core_models/.bundle/gems/gems/rspec-core-3.1.7/lib/rspec/core/configuration.rb:1105:in `load'
    from /Users/Adam/Documents/Rails-Projects/core_models/.bundle/gems/gems/rspec-core-3.1.7/lib/rspec/core/configuration.rb:1105:in `block in load_spec_files'
    from /Users/Adam/Documents/Rails-Projects/core_models/.bundle/gems/gems/rspec-core-3.1.7/lib/rspec/core/configuration.rb:1105:in `each'
    from /Users/Adam/Documents/Rails-Projects/core_models/.bundle/gems/gems/rspec-core-3.1.7/lib/rspec/core/configuration.rb:1105:in `load_spec_files'
    from /Users/Adam/Documents/Rails-Projects/core_models/.bundle/gems/gems/rspec-core-3.1.7/lib/rspec/core/runner.rb:96:in `setup'
    from /Users/Adam/Documents/Rails-Projects/core_models/.bundle/gems/gems/rspec-core-3.1.7/lib/rspec/core/runner.rb:84:in `run'
    from /Users/Adam/Documents/Rails-Projects/core_models/.bundle/gems/gems/rspec-core-3.1.7/lib/rspec/core/runner.rb:69:in `run'
    from /Users/Adam/Documents/Rails-Projects/core_models/.bundle/gems/gems/rspec-core-3.1.7/lib/rspec/core/runner.rb:37:in `invoke'
    from /Users/Adam/Documents/Rails-Projects/core_models/.bundle/gems/gems/rspec-core-3.1.7/exe/rspec:4:in `<top (required)>'
    from bin/rspec:16:in `load'
    from bin/rspec:16:in `'

Do I need to require active record?
Answer: Make sure you're loading the Rails environment inside spec/rails_helper.rb:
ENV["RAILS_ENV"] ||= 'test'
require 'spec_helper'
require File.expand_path("../../config/environment", __FILE__) # LOADS Rails env
require 'rspec/rails'

If you want to see a clean spec/rails_helper.rb, use the provided generator to re-create the rails_helper file: rails generate rspec:install.

Cannot load active record?


Grails: text instead of varchar

Question: I need the MySQL column type for the String field in my Domain class to be TEXT or VARCHAR(3000), but nothing I try seems to work - it remains VARCHAR(255). I've tried
static mapping = {
   longString type: 'text'
}

and
static mapping = {
   longString sqlType: 'text'
}

and
static constraints = {
   longString (blank: true, nullable: true, maxSize: 3000)
}

and
static constraints = {
   longString (blank: true, nullable: true, size: 0..65535)
}

MySQL Server version 5.0.95, Grails 2.4.3.
I'm totally mystified and would appreciate any help..
Answer: You need to define the type of the column in the mapping block rather than constraints. Assuming the name of the property is longString, add this
static mapping = {
  longString type: 'text'
}

This will create a column with a MySQL type of longtext.
To verify that this works, try dropping your database, create a new (empty) database, restart the app and check the type of the column that is created. See this example for reference.
Comment: but that's exactly the code that was cited in the question.
Comment: you really hit the spot! I completely forgot about dbCreate = "update" line in my configuration file. I dropped the db, and it all works now! Handface. Maybe you could edit your answer, so I can accept it.
Comment: I had a feeling that's what was happening :) I've edited my answer to include the verification info.

Grails: text instead of varchar


How can I check if a node references a Drupal Commerce product?

Question: Is there a short function in Drupal Commerce API that returns TRUE (or something else) if a given node references a product?
Answer: There isn't a short function, though that's not a bad idea for a feature request. However, it's not that difficult using the Field Info API to determine if a given node contains a product reference field. One method would be using field_info_instances().
With this function and your node object, you can retrieve an array of all field instances on your node with the following code:
$instances = field_info_instances('node', $node->type);

You would then need to loop over the returned instances and use field_info_field($instance['field_name']) to load the field info array and see if the type of any given field is commerce_product_reference. If so, then you know the node can at least refer to a product... but that doesn't mean a reference is actually established.
For that you'd need to make sure the node contained data for that instance. That could be as simple as checking if (!empty($node->$instance_name)), but it'll depend on how you're actually building / using these reference fields.
One simpler way to find if a product reference instance is on the node is possible if you know your reference field's name. For that you can use field_read_instance() with the following code to return the info array of the instance or FALSE if it doesn't exist for the given node type:
$instance = field_read_instance('node', $field_name, $node->type);

Hope those help, and feel free to open an issue in the Commerce issue tracker for any related helper functions under the "Developer experience" component. I suggest you spend time getting to know the Field Info / CRUD APIs, as they'll be very helpful to you in your Drupal 7 development.
Comment: Has there been a function added since to provide this functionality? I see there's a filter in Views, but I'm having trouble finding a corresponding PHP method.


Causation implication

Question: I recently read an article about how you can increase longevity by sleeping less. This article, like many others I've read, references a statistical study and implies that causation was found between two events(sleeping less and living longer). Well I'm not a statistician, but I'm aware of the common fallacies about causation and I find it very hard to accept the information given in this article and other similar ones. Even further, I can almost never know from an article if the original study found causation or not, without taking the time and digging into it.
Although I'd really like to, I'm not going to go into any depth bringing examples of how the causation might be wrong in the given article, because I would most likely be preaching to the choir. Luckily though, to my relief, the original article in NY Times only talks about correlation and even has a disclaimer in the end that basically says that the study doesn't imply causation.
Also, I now read that, in accordance with my intuition, it is actually really hard to find and/or test for causation. Reading through the wiki page on the subject I saw two models which seemed to be the most common ones used to find actual links in causation: Granger causality test and convergent cross mapping. But I see, that both of these have some gaps in them.
Now, I have a few questions regarding all this.
Q1: Are there any models that can, with high accuracy, find actual causation in such widespread studies? If so what are the most common ones?
Q2: How often do these widespread studies actually test for causation? E.g. if I read somewhere that a very broad study implies that A causes B, do I have any reason whatsoever to believe that there's something more than correlation behind those claims.
Q3: Is there a good technique that can be used by a non-statistician to filter out good statistics from the bad ones in everyday life.
Comment: Regarding Q1: Are you only referring to observational studies? If not the easiest way to test for a causal effect is to conduct a experiment in which you e.g. apply food-restriction to one group of mice but not to another group and then test if the starving mice live longer.
Comment: Well I'm referring to observational ones, yes. I understand, that blind (or even double-blind) experiments are quite good at finding/testing for causality.
Answer: Starting with Q2: convincing readers that a causal effect has been found is often the overriding concern of research articles in social sciences, psychology and medicine. However this usually cannot be done through a simple test but by proposing a causal theory, presenting evidence consistent with the theory in the form of correlations and other statistical patterns, pre-empting alternative explanations, and presenting evidence that is not consistent with the alternative explanations.
(Q1) Regression analysis allowing the researcher to examine the conditional correlation between an explanatory variable and a dependent variable while controlling for other possible explanatory variables is still probably the most common method. This does not by itself demonstrate causation between the variables of interest, but helps to isolate and reject competing causal explanations. In particular, it is difficult to argue that there is a causal relationship when there is no correlation after controlling for other variables (although when the explanatory variables are strongly correlated with each other, even this can be questioned).
Some other common methods that try to improve on basic regression analysis for eliminating competing explanations of hypothesised causal effects include

'natural experiments', for instance where one region of a country has benefited from a new policy but another, otherwise similar, region has not
matching techniques such as propensity score matching, which try to control specifically for the fact that the 'treatment' group (e.g. people who sleep less) in an observational study may differ systematically from the 'control' group (people who sleep more) in ways that affect the outcome of interest (longevity)

(Q3) Arguably there is no simple technique for filtering out good statistics; it depends as much on knowledge of the field as knowledge of the statistical methods. Assuming an article  shows a correlation between two variables, consider what the alternative explanations for that correlation could be (e.g. an unobserved variable influencing both, or reverse causation) and whether the article at least tries to eliminate those alternative explanations. There will nearly always be some form of regression or matching analysis to control for other variables; if nothing like that is mentioned in the abstract then a causal conclusion is likely to be unsound (but such articles would rarely get published in academic journals).
Also consider the level of generality claimed for the causal effect. E.g. the claim that less sleep leads to more longevity in abstract terms sounds like it is suggesting a universal effect, applicable to humans in all places and times. To make a general claim like that plausible would depend on subject knowledge (e.g. prior evidence that the determinants of longevity are similar across countries) and a strong argument that the sample is representative (e.g. the article describes how they were selected and discusses how potential sample bias was avoided).
For me the most convincing evidence from observational studies is when a series of studies by different researchers, using different datasets and techniques, have consistently found evidence that does not contradict the proffered causal explanation, and progressively eliminated alternative explanations.
Answer: Q2: As far as I know there are 2 good ways to test for causality. It is done by the design of the study. Two designs work here:

In a situation where you can control ALL independent variables
(usually in experiments). This makes sure that A is causing B, and there is no C causing the effect (and also not the reverse effect; B causing A).
In longitudinal studies.

Q1: Rubin's Causal Model: http://en.wikipedia.org/wiki/Rubin_causal_model
Q3: There is no "trick" to seeing whether the statistics of one single article are good. I find the most important questions you should ask yourself:

Who did the research?
What is to be gained by the researcher with a favorable outcome?
Comment: You might find Winship and Morgan's [overview article](http://www.wjh.harvard.edu/~cwinship/cfa_papers/theestimationof.pdf) helpful.
Comment: On bullet 1: Controlling *all* independent variable can also be wrong. Simple example: B is caused by A and C, but A does not cause C.  Now, if you control for B and you'll be wrong about the causal impact of A on C (you'll think there is one).  Also, in experiments that randomise and control, it is the randomisation that warrants the causal inference; control 'just' makes the inference more precise.
Comment: Controlling all other independent variables, while randomizing the variable expected to have a causal relation?
Comment: Even then.  Try it: assume A and C are normalised test scores unrelated in the population: `dd <- data.frame(A=rnorm(100), C=rnorm(100)) # A is randomised and unrelated to C`. Now make B, say college admission, depend on them: `transform(dd, B=ifelse(A+C > 1, 1, 0)) ## score over 1 get in`. The correct causal inference is given by *not* conditioning on B: `summary(lm(C ~ A, data=dd)) # no effect`. Conditioning on B: `summary(lm(C ~ A + B, data=dd))` makes it look like A causes C to be go down, but it doesn't (they're unrelated by construction).  This is not specific to regression, btw.
Comment: You might be thinking 'but wait, that B really is a dependent variable', and you'd be right, in a sense -- this effect is closely related to the hazards of 'selecting on the dependent variable'. In this case it's just not *your* dependent variable (that would be C in the example.)  Nevertheless, if you didn't know A and C caused B, or more generally you didn't know that B had A and C somewhere way back in its causal chain, then you'd list it as an independent variable, condition on / control for it and things would go wrong, as they do above.
Comment: I think what I missed is that with an experiment, the dependent variable is causal since there is difference in time; dependent variable is measured afterwards and therefore cannot have caused the independent variable?

Causation implication


Repeated Measures ANOVA in R Trouble for LARGE Dataset

Question: I am struggling to determine if using a repeated measures ANOVA for my data is the best analysis, and unfortunately my adviser has not been much help.  I measured luminosity of various fungal isolates at 14, 23, and 32 days post inoculation.  Isolates were generated from five different parental sets: bright72, bright88, intermediate, dim95, and dim 102.  I've formatted the data for R as follows (long-format?):
subj    dpi    rlu_s  parent
1      14      235     bright72
2      14      4314    bright72
1      23      2350    bright72
2      23      24555   bright72
1      32      747647  bright72
2      32      373627  bright72
3      14      235     dim95
4      14      4314    dim95
3      23      2350    dim95
4      23      24555   dim95
3      32      747647  dim95
4      32      373627  dim95

etc. for a very large data set: 242 total isolates with measurements from the 3 days and my five parental groups
My adviser would like me to run a repeated measures ANOVA, but I'm not interested in a comparison of the luminescence change of a single isolate from 14-->23-->32dpi bc I know that at 14 dpi they are much more dim than at 23 or 32.  I'm more concerned with whether the bright72 are significantly brighter than the dim95, etc.  but have no idea how to approach this analysis as someone with a single biostatistics course down and limited coding knowledge.
I've tried:
lum_res = aov(formula = rlu_s~ dpi + Error(subj/dpi), data = lumrlu)
but this does not provide a Mauchly's Sphericity test.
I've also tried:
model=ezANOVA(lumrlu, rlu_s, subject, within=dpi, detailed = TRUE, return_aov=TRUE)

Which again does not provide Mauchly's (based on the extreme change in measurements from 14 to 32 dpi, I believe I will need to transform my data).
Any help in very simple terms would be greatly appreciated.  I have car, ez, and lsr already installed in R.
Comment: Can you explain what your variables are, what you are attempting to achieve with each of your models, and what your scientific question is? Some of these are hard to figure out based on what you've stated.
Comment: To reiterate: I suggest stepping back from the stats for a bit and figuring out what your scientific question is. We can advise you on the former but not the latter.
Comment: I'm starting to wonder if I need to use repeated measures at all...  My dependent variable is my luminescence measurement (rlu_s) and my independent variable should be the parental isolate treatment (bright, int, dim).  I have rlu_s time point measurements (14, 23, & 32 dpi) for ~250 different isolates (100 bright, 50 int, 100 dim).  I am trying to determine if isolates that were generated from bright parents are statistically brighter than those generated from intermediate and those generated from dim.  However, because of the time point measurements, things have become complex.
Comment: Isolates are independent of the treatment.  So isolate 1 may be from the bright treatment and measured at 14,23, and 32 dpi, but can not be included in the int, or dim treatments.  I'm so confused.  Every time I speak with my adviser it becomes more confusing
Comment: My scientific question is: will haploid isolates generated from a cross between isolates with a bright bioluminescent phenotype be statistically brighter than haploid isolates generated from a cross between isolates with dim bioluminescent phenotype?
Comment: Looking at the data, with no statistical analysis whatsoever, I can see that the frequency of bright isolates in the bright group is higher than the frequency of bright isolates in the dim group.  However, the parental phenotype does not impact the magnitude of those bright isolates, just the frequency.  I just have a massive data set with measurements collected from multiple time points, and don't know what to do with it
Comment: If you don't mind my asking: why measure at 3 time points if time is not in any way part of your scientific question? What I'm trying to get at is: do you have some implicit hypothesis about changes through time that I (and perhaps other readers) have not understood?
Comment: That's why I'm struggling so much with my adviser on this.  I just happened to monitor their growth from 14-32 days after they were inoculated to the plate.  I KNOW (does not require statistics) that isolates will not be as bright on day 14 as they are on day 32 because they are so much smaller and are focused on primary metabolic functions.  I suggested using only data from 32 dpi, but she is dead set on analyzing measurements from 14, 23, ad 32 dpi.
Comment: Unfortunately, you have a rather messy situation, I'm afraid. First off, your main variable of interest is *parental isolate treatment*, though it is not in your data frame up there. So the most basic version of this model would be **lm(luminescence ~ treatment)**
Comment: But you have to account for variance explainable by 1) parental sets (isolate nested within parental isolate) and 2) time. You have only 5 parental sets, with 2 being bright, 1 intermediate, and 2 dim. The low level of replication at this level makes it hard-to-impossible to deal with using a nested random effect (which would be my inclination). You also have temporal structure that you can account for, but again not so many time points that you can do much with it.
Comment: However, none of this points in the direction of a repeated measures ANOVA, to the best of my knowledge.
Answer: Turning my comments above into an answer:
Your situation is rather messy, I'm afraid. First off, your main variable of interest is parental isolate treatment, though it is not in your example data frame. The most basic version of this model would be lm(luminescence ~ treatment)
But you have to account for variance explainable by 1) parental sets (isolate nested within parental isolate) and 2) time. You have only 5 parental sets, with 2 being bright, 1 intermediate, and 2 dim. The low level of replication at this level makes it hard-to-impossible to deal with using a nested random effect (which would be my inclination). You also have temporal structure that you can account for, but again not so many time points that you can do much with it.
However, none of this points in the direction of a repeated measures ANOVA, to the best of my knowledge.


Inserting BigDecimal numbers into ArrayList in java

Question: How can I insert BigDecimal values into an ArrayList using java?
First i declare a bigdecimal number(here it is 0) as shown below.
and after that I need to insert this bigdecimal value 'unit' into an arraylist.My code snippet is shown below.
BigDecimal unit = new BigDecimal(0);
int x=0;
int y=10;

while(x<10){

    // Here i need to insert the `BigDecimal` value "unit" into an `ArrayList` for each iteration of this loop

    x++;
}

Comment: Give useful information about your problem!
Comment: Could you please be more specific on what your problem is?
Comment: Please add your code snippet for a better understanding.
Comment: Do you have anything that we can use to start with?
Comment: What is the problem in inserting? could you post some code to help us understand
Answer: Use List.add:
List<BigDecimal> list = new ArrayList<BigDecimal>();
BigDecimal totalQuantity = new BigDecimal(0);
list.add(totalQuantity);

Comment: @Bubletan: I might have missed something, but I didn't see anything in the question saying that we needed to add at a specific location.
Comment: You should use `List#add(int, E)`, which inserts at a specific position instead of just adding at the end.
Comment: @fzzfzzfzz Well, just thought as he didn't say it should be added at the end. Inserting in general means that you can add it anywhere you want.
Answer: System.out.println(80.6 + 379.6);
460.20000000000005

System.out.println(BigDecimal(80.6 + 379.6));
460.200000000000045474735088646411895751953125

There are multiple numbers where Java is doing this. Unable to fix and get the programs running correctly, making some of my mathematical programs fail.
Tried in multiple to see if it was a compiler issue.
There may be a bug?


How to configure blocks per node?

Question: I'd like to build a Drupal 7 module that generates a block which contains (along with some static HTML to be used as template for a JavaScript library) a node-specific value to be passed on to a web service. (The web service will return relevant data for the contents of the node.)
How should a block receive node-specific data? Module configuration seems to be global, and blocks cannot be configured individually.
Should I modify the main content-type of the node by adding this "node-specific data" as an extra field even if this value is only used in my module?
Answer: Use the Block API to add the blocks
i.e:

hook_block_info
hook_block_view

Use menu_get_object to get the node object for that page.
e.g:
<code>function mymodule_block_view($delta){
  $block = array();
  switch($delta){
    case 'my_delta':
     if ($node = menu_get_object('node') && $node->type == 'my_type') {
       $block['subject'] = t('Example block on %node', array('%node' => $node->title));
       $block['content'] = render(field_view_field('node', $node, 'body')); // for example
     }
    break;
  }
  return $block;
}
</code>

How to configure blocks per node?


Creating Pixel Art Maker Grid

Question: I'm trying to create a pixel art maker that the user can choose the grid size (or namely Canvas) to work on. However, my code isn't work - specifically there are table rows being created, but not actually showing. I've linked both my JavaSctipt and HTML code to help.
Here's my code:

let color = document.getElementById("colorPicker");
    let table = document.getElementById("pixelCanvas");
    let sizePicker = document.getElementById("sizePicker");

    let height = document.getElementById("inputHeight").value;
    let width = document.getElementById("inputWeight").value;
    makeGrid(height, width);

    sizePicker.addEventListener("click", (e) => {

      e.preventDefault();

      let height = document.getElementById("inputHeight").value;
      let width = document.getElementById("inputWeight").value;
      table.firstElementChild.remove();

      makeGrid(height, width);

    });

    function makeGrid(height, width){

     for(let i=0; i<= height; i++){
      let row = table.insertRow(i);
      for(let j=0; j<= width; j++){
       let cell = row.insertCell(j);
       cell.addEventListener("click", (e) => {
        cell.style.backgroundColor = color.value;
       })
      }
     }

    }

<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Pixel Art Maker</title>
        <link rel="stylesheet" href="style.css">
        <link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">

Pixel Art Maker

Choose Grid Size:

       <form id="sizePicker">
        Grid Height:
        <input type="number" id="inputHeight" name="height" min="1" value="1">
        Grid Width:
        <input type="number" id="inputWeight" name="width" min="1" value="1">
        <input type="submit">
       </form>

Pick A Color:

       <input type="color" id="colorPicker">

Canvas

Comment: I'd say it almost perfectly works. The table is created, cells are filled. The probably issue with cellspacing, so it is hard to target 1px with a click.
Meanwhile, you probably should try to use `mousemove` and fill with color after `mousedown` was triggered, because click won't work like this, you'll need to click each 1px cell to fill it with color.
Comment: that's because of `i <= height` and `j <= width`. Should be strictly `<`.
Comment: It would be useful to have also the HTML code. You could try to create a working snippet.
Comment: Just edited in the HTML
Comment: Nothing is appearing on the canvas though. I see the table rows being created, but the canvas shows blank.
Comment: They are created, but they have no content, no borders, no background color... so you see nothing. Try to add a little bit of CSS like: `tr {
  height: 50px;
  background: red;
}

td {
  width: 50px;
}`
Comment: So you filling them with a color on `click`, so they are empty initially.
Comment: To remove gaps you need to add `cellspacing=0` to `table` tag for sure.
Comment: That works! Thank you!
Comment: @extempl - Will you make the answer out of this talk?
Comment: I am still not sure what was the problem, and what is fixed the problem. cellspacing removing gaps, but it doesn't looks like this is was the initial issue, your code is fully working.
Comment: What's weird now, is the grid already starts at a 2x2.
Comment: Or you start on 1 instead of 0. But what *extempl* advise you is more the standard convention. And, @extempl, I think the main issue was that the OP expected a table being drawn, but with the default style nothing gets shown on the screen. The `cellspacing` to remove the gaps is kinda optional, I actually like it with them :)
Comment: Got it! I appreciate the help a ton!
Comment: Any idea why the grid itself isn't adjusting to center when I do text-align: center to tr/td?
Comment: Do you mean aligning the table horizontally? I added `table { margin: auto }` to the answer. `text-align: center` does not work for `blocks`
Comment: Yes! That's it. I'm still learning!
Answer:

let color = document.getElementById("colorPicker");
let table = document.getElementById("pixelCanvas");
let sizePicker = document.getElementById("sizePicker");

let height = document.getElementById("inputHeight").value;
let width = document.getElementById("inputWeight").value;
makeGrid(height, width);

sizePicker.addEventListener("click", (e) => {

  e.preventDefault();

  let height = document.getElementById("inputHeight").value;
  let width = document.getElementById("inputWeight").value;
  table.firstElementChild.remove();

  makeGrid(height, width);

});

function makeGrid(height, width) {

  for (let i = 0; i < height; i++) {
    let row = table.insertRow(i);
    for (let j = 0; j < width; j++) {
      let cell = row.insertCell(j);
      cell.addEventListener("click", (e) => {
        cell.style.backgroundColor = color.value;
      })
    }
  }

}
table {
  margin: auto
}

tr:nth-child(even) td:nth-child(even),
tr:nth-child(odd) td:nth-child(odd) {
  background-color: #eee;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Pixel Art Maker</title>
  <link rel="stylesheet" href="style.css">
  <link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">

Pixel Art Maker

Choose Grid Size:

  <form id="sizePicker">
    Grid Height:
    <input type="number" id="inputHeight" name="height" min="1" value="1"> Grid Width:
    <input type="number" id="inputWeight" name="width" min="1" value="1">
    <input type="submit">
  </form>

Pick A Color:

  <input type="color" id="colorPicker">

Canvas

Comment: why I am alive?
Answer: So, the code is working, the table is created, but you see nothing because there is no initial styling for cells. I've added basic styles to simulate checkmate.
Also, there was two issues - gaps between cells (fixed with cellspacing="0") and n+1 rows/cells fixed with strict < condition in both loops.
Result is below:

let color = document.getElementById("colorPicker");
let table = document.getElementById("pixelCanvas");
let sizePicker = document.getElementById("sizePicker");

let height = document.getElementById("inputHeight").value;
let width = document.getElementById("inputWeight").value;
makeGrid(height, width);

sizePicker.addEventListener("click", (e) => {

  e.preventDefault();

  let height = document.getElementById("inputHeight").value;
  let width = document.getElementById("inputWeight").value;
  table.firstElementChild.remove();

  makeGrid(height, width);

});

function makeGrid(height, width) {

  for (let i = 0; i < height; i++) {
    let row = table.insertRow(i);
    for (let j = 0; j < width; j++) {
      let cell = row.insertCell(j);
      cell.addEventListener("click", (e) => {
        cell.style.backgroundColor = color.value;
      })
    }
  }

}
table {
  margin: auto
}

tr:nth-child(even) td:nth-child(even),
tr:nth-child(odd) td:nth-child(odd) {
  background-color: #eee;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Pixel Art Maker</title>
  <link rel="stylesheet" href="style.css">
  <link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">

Pixel Art Maker

Choose Grid Size:

  <form id="sizePicker">
    Grid Height:
    <input type="number" id="inputHeight" name="height" min="1" value="1"> Grid Width:
    <input type="number" id="inputWeight" name="width" min="1" value="1">
    <input type="submit">
  </form>

Pick A Color:

  <input type="color" id="colorPicker">

Canvas

Also, you should try to fill cells on mousemove event, after mousedown was triggered and until mouseup, or, at least, make cells bigger, as clicking 1px cells is not really easy.
Meanwhile, it is good for training, but in further I'd recommend to go with canvas, as huge tables are not really good at performance and memory efficiency.

Creating Pixel Art Maker Grid


Alembic's server_default and Postgres

Question: I would like to run a migration using alembic from a sqlalchemy model to another.
The initial model looks like this:
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy_utils import UUIDType

class Foo(db.Model):
    __tablename__ = 'foo'
    id = db.Column(UUIDType(binary=True), primary_key=True)
    foo_field = db.Column(JSONB)

and I want to make foo_field not nullable:
class Foo(db.Model):
    __tablename__ = 'foo'
    id = db.Column(UUIDType(binary=True), primary_key=True)
    foo_field = db.Column(JSONB, nullable=False)

I want to run an alembic script to alter the column, but since some of my existing foo_field are null, I want to use server_default to apply a default value (an empty dict) when altering
op.alter_column('foo',
         'foo_field',
         existing_type=postgresql.JSONB(astext_type=sa.Text()),
         nullable=False,
         server_default="{}")

I tried different options to pass to this server_default, such as text("{}"), lambda: {}, {}, text("SELECT '{}'"). But it seems to be just ignored and all I get is an IntegrityError  when running the upgrade :
sqlalchemy.exc.IntegrityError: (psycopg2.IntegrityError) column "foo_field" contains null values [SQL: 'ALTER TABLE foo ALTER COLUMN foo_field SET NOT NULL'] (Background on this error at: http://sqlalche.me/e/gkpj)

Does a string representing an empty dict is considered as not-null? What should be passed to this server_default? Should I fraction the code in multiple steps to fill the default value before setting the field not nullable (not the prefered option, I have a bunch of columns that I want to apply this to)?
I am using postgres 10.5, I read that postgres 11 will kinda handle better this sort of operation, should I switch to it now?
Thanks in advance for help/advices
Comment: You can already add columns with `NOT NULL DEFAULT something` in pg10 and older. In pg11 you still **won't** be able to **alter** columns in such a way, so there is no point in switching.
Answer: If anyone comes here again, this is what I use
def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.execute("ALTER TABLE {table_name} ALTER COlUMN {column_name} set DEFAULT {new_default_value};")
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.execute("ALTER TABLE {table_name} ALTER COlUMN {column_name} set DEFAULT {old_default_value};")
    # ### end Alembic commands ###

Answer: you can use a Rewriter and do so yourself automatically.
override the ops.AlterColumnOp operation and return two operations first one being an update column operation with the server default value and the second one is the original op.
Comment: That's a good idea, although I think overriding this function would be a bit of a stretch. I decided not to make this column nullable, there was not real reason for it to be absolutely filled with an empty dictionary.

Alembic's server_default and Postgres


Collisions with four bullets

Question: This is a follow-up question of Colliding Bullets. I'm interested in a rigorous calculation of a specific aspect of the referred question.
We consider four bullets. Once per second a bullet is fired with uniformly random speed in $[0,1]$. If two bullets collide they both disappear.
Let's denote the bullets with $1,2,3$ and $4$ in order of their firing. So, bullet $1$ is fired one second before bullet $2$, etc. Let's denote the speed of bullet $j$ with $v_j, 1\leq j \leq 4$.
We focus on two arrangements:

With probability $\frac{1}{4!}=\frac{1}{24}$ we have
  \begin{align*}
1>v_3>v_4>v_2>v_1>0
\end{align*}
Here are two different scenarios to consider with two different outcomes. One scenario is the collision of $2$ with $1$ leaving two bullets $3$ and $4$ which won't collide, since $3$ is faster than $4$.
  \begin{align*}
3\ 4\ 2\ 1 \rightarrow 3\ 4
\end{align*}
  The other scenario is a collision of $3$ with $2$ and since $4$ is faster than $1$, they will also collide. We obtain
  \begin{align*}
3\ 4\ 2\ 1 \rightarrow 4\ 1\rightarrow \emptyset
\end{align*}
  So, we have two different scenarios, one with two bullets as outcome, while all bullets vanish in the other scenario.

A simulation of these scenarios results in a proportion of roughly
\begin{align*}
28:13
\end{align*}
in favor of a collision of bullet $2$ with bullet $1$, so that bullets $4$ and $3$ will escape to infinity.

A simulation of a similar arrangement with
  \begin{align*}
1>v_3>v_2>v_4>v_1>0
\end{align*}
  results in a proportion of roughly
  \begin{align*}
40:2
\end{align*}
  in favor of a collision of bullet $2$ with bullet $1$.

Question: I'm interested in a rigorous calculation of these proportions. So, an approach with probabilistic or combinatorial methods is highly appreciated. In case you know some numerical solutions, you are heartily invited to add it as comment.
Answer: For small enough versions of this problem, like the 4-bullet case that you're asking for here, you can get exact probabilities by writing down the equations on bullet speeds that give the outcome you're interested in, and then using Mathematica to integrate Boole[those equations] over $[0,1]^4$.
To distinguish combinatorial types of outcomes, the useful equation is that if the bullets fired at times $i$ and $j$ with $i<j$ have velocities $v_i<v_j$, then they will meet at time $\large\frac{j v_j - i v_i}{v_j-v_i}$, as long as they both survive that long.  That equation is not linear, which is why the probabilities are sadly not just volumes of polyhedra.
For the specific example you asked about:
<code>In[1]:= mt[i_,j_] := If[(-i + j)*(-v[i] + v[j]) <= 0,
                        Infinity,
                        (j*v[j] - i*v[i])/(v[j] - v[i])];

In[2]:= Simplify[Integrate[Boole[mt[2,1]<mt[2,3]],
                           {v[1],0,1},{v[2],v[1],1},{v[4],v[2],1},{v[3],v[4],1}]]
Out[2]= (3 - 4*Log[2])/8

In[3]:= Simplify[Integrate[Boole[mt[2,1]>mt[2,3]],
                           {v[1],0,1},{v[2],v[1],1},{v[4],v[2],1},{v[3],v[4],1}]]
Out[3]= (-2 + Log[8])/6

In[4]:= Simplify[%2 + %3]
Out[4]= 1/24

In[5]:= N[%2/%3]
Out[5]= 2.14697
</code>
For comparison, your empirical result $28$:$13$ is $2.15385$.
Comment: Nice answer. Thanks!
Comment: Unfortunately, anything along these lines for 6 bullets brings Mathematica to its knees (on my 24GB machine).
Comment: Thanks for this sobering information :-;

Collisions with four bullets


Change selected value from a DropDownList of Razor with JQuery

Question: I would like to modify the selected value of my dropdownlist without have to click on my dropdownlist.
I already tried this line with JQuery:
$('#select-nb-Persons-button').children(":first").text("3");

It printed well "3" for the dropdownlist but after, when I clicked on the dropdownlist, I noticed that it is always the first option tag that is selected and not the third option tag as I want. :
Code created by razor for the dropdownlist :

        1
        <select data-val="true" data-val-number="Le champ nbPersons doit être un nombre." data-val-required="Le champ nbPersons est requis." id="select-nb-Persons" name="nbPersons">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="5">5</option>
            <option value="6">6</option>
        </select>

Can you help me please ?
Thank you
Answer: You can use val() to set the selected item in a select. To select the item with a value of 3, try this:
$('#select-nb-Persons').val('3');

Answer: Try below code.
$('#select-nb-Persons-button').children('select').val('5');

DEMO here


What is Statistics?

Question: I suggest to pause for a moment, sit back and think about this philosophical question. What are we doing when we are doing statistics? How to embed statistics into the landscape of modern science and engineering? Does the name properly reflect the subject?
I am not looking for short twitter-like answers discussed here. I am more in the search for a detailed well-argued opinions in this spirit.
So, what is your personal opinion?
Comment: This appears to be a purely opinion-based question. Indeed you explicitly say it in your last sentence. That's one of the standard stackexchange reasons to place a post on hold.
Comment: I understand your interest (indeed I share it), but purely-personal-opinion questions are (by design of the founders) not suitable questions for our site, and they have become less acceptable as the site has evolved (you may find a few old threads that survive for historical reasons even though they'd close quickly now). You're free to pursue opinion on [chat](http://chat.stackexchange.com/rooms/18/ten-fold). Alternatively you might consider whether there's a version of your question more open to answers supportable by facts rather than personal opinion ... ctd
Comment: Well, I am interested exactly in personal opinions :) of experts such as, for example, you. Opinions, that you never see published, but may hear, for instance, in conversations during conference dinners :)  Should I remove the question?
Comment: ctd... (I suspect that's not possible without a very substantial shift however).  If you'd prefer it and you're able to delete, you're free to do so, though if it were me I would not, given someone contributed an answer. If they're happy, then there's no harm in it.
Comment: @Glen_b I was going to create a questing asking people to contribute examples of counter intuitive problems in probability and statistics. Just would like to double chek with you: would this be considered as an opinion-based question? ("counter intuitive" is somewhat subjective, but often people either agree or disagree on whether something is intuitive or not).
Comment: It's not so badly opinion-based, but it is likely to be *big-list* which can be problematic. It might survive; it's hard to judge with a question you haven't written yet
Comment: Thanks for a prompt response. I will think how to formulate the question properly.
Answer: To start with, let me describe my point of view.
What is Statistics?
Opinions vary. In fact, there is a continuous spectrum of attitudes toward statistics ranging from pure theoreticians, proving asymptotic efficiency and searching for most powerful tests, to wild practitioners, blindly reporting p-values and claiming statistical significance for scientifically insignificant results. Even among most prominent statisticians there is no consensus: some discuss the relative importance of the core goals of statistical inference, others comment of the differences between  "mathematical" and "algorithmic" cultures of statistical modeling, yet others argue that mathematicians should not even teach statistics. The absence of a unified view on the subject led to different approaches and philosophies: there is frequentist and Bayesian statistics, parametric and nonparametric, mathematical, computational, industrial, applied, etc. To complicate the matter, machine learning, a modern subfield of computer science, is bringing more and more new tools and ideas for data analysis.On top of that, data science, a fancy mixture of statistics and machine learning is becoming more and more popular.
I tend to view statistics as a branch of mathematical engineering  that studies ways of extracting reliable information from limited data for learning, prediction, and decision making in the presence of uncertainty. To the best of my knowledge, this view was first expressed by Cosma Shalizi.
Statistics is not mathematics per se because it is intimately related to real data. Mathematics is abstract, elegant, and can often be useful in applications; statistics is concrete, messy, and always useful. The difference between statistics and  mathematics is akin to the difference between a real man and the Vitruvian. As a corollary, the proofs are not of paramount importance in statistics. Their main role is to provide intuition and rationale behind the corresponding methods. On the other hand, statistics is not simply a toolbox that contains answers for all data related questions. Almost always, as in solving engineering problems, statistical analysis of new data requires adjustment of existing tools or even developing completely new methods. For example, recent years witnessed an explosion of network data for which most of the classical statistical methods and models are simply inappropriate.

What is Statistics?


throwing mechanics

Question: I am a newbie in playing darts. When I practised myself, I noticed that even if I stood with my feet parallel to the oche, the movement of my arm was not a straight line going out from my dominant eye towards the dartboard. When I propelled the darts, my elbow seemed to twist a bit at certain position. As a result, the dart often hit Single 6 or Single 11 when I aimed at the Bull.
To simplify what I have said:
The dart, my aiming eye, my throwing arm and my target were not always on the same vertical plane in a throw.
Is this normal? Anyone who can share his/her experiences in playing darts are greatly appreciated.
Answer: I throw darts fairly regularly. When you say that your feet were parallel to the oche, did you mean perpendicular? If you stand with your feet parallel, then you'll be facing the board straight on and it will be very hard to do this.
Here's my suggestion - place one foot (generally the same foot as your throwing hand, so right foot for a righty, left foot for a lefty) right up against the oche. Put most of your weight on that foot and place the other foot a little bit back (maybe 10-15 inches). Just use the toe of that foot to help maintain balance.
At this point, you'll have your body turned a bit - somewhat perpendicular to the oche. Turn your body a bit more so that your throwing shoulder is in front of your body. Bring your dart up in front of your face, and you'll find that it's much easier to keep the dart in line with your eye (as long as you don't move your upper arm too much when throwing).
Here's a site with pictures of the foot position and one view of the shoulder/upper arm:
http://www.nicedarts.com/dart_stance.html
Comment: Ya, my stance is more or less the same as the image shown on the page you suggested. Having my right feet in the front, parallel to the oche, and my body perpendicular to the oche. However, when you throw a dart, do your `shoulder`, `upper arm` and `lower arm` always remain on the same vertical plane?
Comment: It depends a bit on your stance, but yes mine generally do. The easiest way to accomplish this is to not move your upper arm (or at least, minimally). This will restrict how far back your upper arm comes, but it will also allow you to keep the dart in line with your eyes. I'd suggest practicing this without a dart - just assume the stance, raise your arm so your upper arm is close to parallel to the floor, and practice moving your lower arm in the throwing motion. Focus your gaze on your hand and make sure it's coming straight back towards your eye, then straight away from it.

throwing mechanics


T test for poisson distribution

Question: I have a sample ($n = 10$) from a Poisson distribution. It was said that the t test with 9 degrees of freedom cannot be used to test $H_0: \lambda = 5$ against $H_1: \lambda \ne 5$.
I know that a Poisson distribution can be approximated by a Normal one for "big" sample sizes. Since we have here $n=10$, is this the reason the t test can't be applied here?
Comment: I disagree with the premise of the question. An average of 10 Poisson rvs with $\lambda=5$ is normal to an excellent approximation. Same as for one rv with $\lambda=50$. So a t-test would be "valid" in that it would control the type I error rate correctly or close enough. But why would you want to do a t-test when using the Poisson distribution directly is both better and simpler?
Answer: Consider the sum $T =\sum_{i=1}^{10} X_i,$ where $X_i \stackrel{iid}{\sim} \mathsf{Pois}(\lambda = 5).$ Then $T \sim \mathsf{Pois}(\lambda_{10}=50),$
and $P(T \le 36) + P(T \ge 65) \approx 0.048.$ In R:
<code>ppois(36, 50)
[1] 0.02375891
1-ppois(64, 50)
[1] 0.02360321
</code>
Thus an exact test of $H_0: \lambda = 5$ vs. $H_a: \lambda \ne 5$ at about the 4.8% level is to reject $H_0$ for $T \le 36$ or $T \ge 65.$

The distribution $\mathsf{Pois}(50)$ is approximately $\mathsf{Norm}(\mu=50, \sigma-\sqrt{50}),$ so a normal approximation to the exact test is easy to find.
Student's t distribution with 9 degrees of freedom is not an appropriate null distribution for your test, and I see no reason to use it (or any other t distribution).
[Doing a one-sample t test on Poisson data would compound the inaccuracy by using the sample standard
deviation $S$ to approximate the known standard deviation of the null distribution.]
Answer: Maybe this is useful:
Making the comparison between using the t-test and the approach by BruceET:

<code># T-student:

B <- 100000

power_p <- numeric(8)

lower_t <- qt(0.025, 9)
upper_t <- qt(0.975, 9)

for(i in 1:8){
  for (j in 1:B){
    my_sample <- rpois(10, i)
    t_stat[j] <- (mean(my_sample) - 5) / (sd(my_sample)/sqrt(10))
  }

power_t[i] <-  mean(t_stat <= lower_t | t_stat >= upper_t)

}

#Poisson:

power_p <- numeric(8)

low_n <- qnorm(0.025, 50, sqrt(50))
up_n <- qnorm(0.975, 50, sqrt(50))

for(i in 1:8){
  for (j in 1:B){
    my_sample <- rpois(10, i)
    T_s[j] <- sum(my_sample)
  }

  power_p[i] <-  mean(T_s <= low_n | T_s >= up_n)

}
> power_p
[1] 1.00000 0.99960 0.88010 0.29759 0.05589 0.32168 0.77828 0.97092
> power_t
[1] 1.00000 0.99872 0.86741 0.32308 0.05239 0.18314 0.57013 0.87494
</code>
Can be seen what would be the problem of using a t-test in this case, the power of the t-test is lower.
Another option to get the confidence interval could be a simple monte carlo simulation.

T test for poisson distribution


SQLException: ORA-00257: archiver error. Connect internal only, until freed

Question: Tenha uma conexão com banco de dados Oracle que faz uma inserção simples na base.
O processo estava funcionando, porém agora esta apresentando o erro abaixo.
<code>2017-07-13 14:25:55.929 ERROR 12062 --- [nerContainer-21] c.z.h.p.HikariPool                       : monitorPool - Exception during pool initialization.

java.sql.SQLException: ORA-00257: archiver error. Connect internal only, until freed.

    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:447) ~[ojdbc6-188.8.131.52.jar!/:184.108.40.206.0]
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:389) ~[ojdbc6-220.127.116.11.jar!/:220.127.116.11.0]
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:382) ~[ojdbc6-220.127.116.11.jar!/:18.104.22.168.0]
    at oracle.jdbc.driver.T4CTTIoauthenticate.processError(T4CTTIoauthenticate.java:444) ~[ojdbc6-220.127.116.11.jar!/:22.214.171.124.0]
    at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:513) ~[ojdbc6-220.127.116.11.jar!/:188.8.131.52.0]
    at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:227) ~[ojdbc6-184.108.40.206.jar!/:188.8.131.52.0]
    at oracle.jdbc.driver.T4CTTIoauthenticate.doOSESSKEY(T4CTTIoauthenticate.java:407) ~[ojdbc6-126.96.36.199.jar!/:220.127.116.11.0]
    at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:416) ~[ojdbc6-184.108.40.206.jar!/:126.96.36.199.0]
    at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:553) ~[ojdbc6-126.96.36.199.jar!/:220.127.116.11.0]
    at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:254) ~[ojdbc6-126.96.36.199.jar!/:126.96.36.199.0]
    at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:32) ~[ojdbc6-126.96.36.199.jar!/:220.127.116.11.0]
    at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:528) ~[ojdbc6-126.96.36.199.jar!/:18.104.22.168.0]
    at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:95) ~[HikariCP-java7-2.4.11.jar!/:?]
    at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:101) ~[HikariCP-java7-2.4.11.jar!/:?]
    at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:341) ~[HikariCP-java7-2.4.11.jar!/:?]
    at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:193) ~[HikariCP-java7-2.4.11.jar!/:?]
    at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:428) [HikariCP-java7-2.4.11.jar!/:?]
    at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:499) [HikariCP-java7-2.4.11.jar!/:?]
    at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:112) [HikariCP-java7-2.4.11.jar!/:?]
    at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:97) [HikariCP-java7-2.4.11.jar!/:?]
</code>
Eu uso o Hikari como gerenciador de pool de conexão.
Aparentemente para ser um erro de espaço em disco do banco de dados.
Como faço para resolver tal problema?
Comment: Eu tinha visto esse link mas não me ficou claro como executar a solução.
Comment: Veja se isso ajuda: https://www.techonthenet.com/oracle/errors/ora00257.php
Answer: O problema era realmente espaço do ARCHIVE do oracle que estava cheio. E segundo o DBA quando esse espaço está muito cheio o Oracle começa a rejeitar as conexões ocasionando o erro.
Foi feita a limpeza dos ARCHIVES e o erro parou de ocorrer


Why is code coverage inadequate for my controller?

Question: I have below method in my controller. How can I test it? Annotation coverage is failing. Actually I am not able to define code for coverage in jest file.
What parameter I should add in my test file and pass to cover it?
 @Post('upload')
    @UseInterceptors(
        FileInterceptor('image', {
            storage: diskStorage({
                destination: './uploads',
                filename(_, file, callback) {
                    const randomName = Array(32)
                        .fill(null)
                        .map(() => Math.round(Math.random() * 16).toString(16))
                        .join('');
                    return callback(null, `${randomName}${extname(file.originalname)}`);
                },
            }),
        })
    )
    uploadFile(@UploadedFile() file) {
        return {
            url: `http://localhost:2300/api/inventory/uploads/${file.filename}`,
            originalFileName: `${file.originalname}`,
        };
    }

It is working perfectly. I wrote this jest test case for same.
   it('Single file upload', async () => {
            const response = await controller.uploadFile(mockFile);
            const fileService = new InventoryController(service);
            expect(response).toBeTruthy();
            expect(response).toStrictEqual(
            expect.objectContaining({
                        originalFileName: expect.any(String),
                        url: expect.any(String),
                    }),
            );
        });

This is successful but coverage is failing for this line.
 @UseInterceptors(
            FileInterceptor('image', {
                storage: diskStorage({
                    destination: './uploads',
                    filename(_, file, callback) {
                        const randomName = Array(32)
                            .fill(null)
                            .map(() => Math.round(Math.random() * 16).toString(16))
                            .join('');
                        return callback(null, `${randomName}${extname(file.originalname)}`);
                    },
                }),
            })
        )

Answer: What I would do here if code coverage is an absolute must on all lines with unit tests, is move the filename function to a separate file that exports the method so it can be tested directly.
During unit tests, enhancers aren't called, only created, so you won't get any coverage other than the initial "yeah, this decorator works" kind of coverage. For this inner callback, you'll need a separate function.
The other option, if code coverage isn't as important a metric, would be to test this in an e2e test. That way you know for certain this works as intended


Does anyone know how to go about writing a Flex precompiler, similar to the way MXML is done into your build process?

Question: This is a bit of a crazy question, but does anyone out there know how to go about writing an extra compile step into the flex compiler. The idea would be that the MXML compiler would knock out the MXML to AS3 code as it does, but we have an extra step between the AS3 code and the bytecode.
The reason why I ask, is that this would be a great step to handle things like metadata tags to make code changes. A common practice in a lot of frameworks is to have an [Inject] tag before a variable.  I.e. [Inject] public var user:IUser.
What would be really, really cool, is if the inject tag could be recognised, interpreted in some way, and then hardwired to a singleton, or whatever. For example, you could have a config file that defines IUser to be a User object. The compiler would interpret that, and replace the [Inject] public var user:IUser with public var user:IUser=UserConfig.instance.user;
This is jsut one of the many things that would be possible if I knew how to do this step. I was just wondering if someone would know even where to start about how to go about doing this.
Comment: Go to opensource.adobe.com get the full source code for the Flex Compiler and start stepping through code to figure out how it works.  I'm unclear the benefit to doing something like this; although it sounds like a fun technical challenge.
Answer: This is a broad question, but I can think of an answer for your specific case.
You would need to write code that accepts bytecode as input, and outputs bytecode:

Find the trait that has your [Injected] metadata.
Write some bytecode that calls UserConfig.instance.user
Inject this bytecode into the Class initializer for this class.

To integrate into your build process, you add a new Program builder (assuming you're using Flash Builder) that runs after Flex.
The other 2 ways would be:

Parse the ActionScript before Flex.
Create your own branch of the Flex compiler.
Comment: On a side note, you could probably skip the Singleton nonsense, and just make a global variable called `user`.
Answer: The compiler is open source, and there's lots of examples in the codebase the show how the compiler modifies the Abstract Syntax Tree (which is what the source code gets parsed to) at compile time.
I'd suggest taking a look at the [Embed] or [SkinPart] extensions. (I've discussed this before with links to examples here.)
Be warned though - this stuff is not for the faint of heart.  If you're new to compilers, and how they work, I highly recommend this book on ANTLR, which gives a thorough overview on the process of parsing Source Code to AST's and then how they are interpreted.


Finding significant independent variables for categorical dependent variable

Question: I have factor dependent variable and many independent variables(continuous & discrete).
This is about financial risk modelling. Whether a customer is likely to default the loan or not is the dependent variable and the principle, interest, high/low/medium income, etc are few out of many independent variables. I would like to see which hypothesis testing is best for this scenario.
My objective is to identify significant independent variables impacting the y.
I think multinomial logistic regression is good for such scenario but regression is modelling. I only want to understand which x's significantly impact the y. Suggesions will be appreciated.
Answer: Generating random data for R, where default is 1 when the customer defaults the loan, the interest rate is having an effect on that but not the level of income (3 levels, 1=low revenues like me, 2=medium revenues, 3=high revenues):
df<-data.frame(
  default=as.factor(c(rbinom(30,1,0.6),rbinom(30,1,0.4))),
  interestrate=c(rnorm(30,2,5),rnorm(30,5,5)),
  levelincome=as.factor(rbinom(60,3,0.5))
                 )

Building a glm of family "binomial"
model1<-glm(default~interestrate+levelincome,family="binomial",data=df)
summary(model1)

The summary command gives you p-values for each of the continuous variables and for the levels of the categorical variables. If you include more than one categorical variable, this may get hard to interpret and you will probably have to use pairwise comparisons with the function emmeans() from the package of the same name in R.
> summary(model1)

Call:
glm(formula = default ~ interestrate + levelincome, family = "binomial",
    data = df)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-1.9572  -0.9737   0.4031   0.9128   2.1725

Coefficients:
             Estimate Std. Error z value Pr(>|z|)
(Intercept)   1.84354    0.90072   2.047  0.04068 *
interestrate -0.19427    0.06354  -3.058  0.00223 **
levelincome1 -1.13407    0.92109  -1.231  0.21824
levelincome2 -0.80197    0.93582  -0.857  0.39146
levelincome3 -1.17280    1.20936  -0.970  0.33216
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 83.111  on 59  degrees of freedom
Residual deviance: 69.605  on 55  degrees of freedom
AIC: 79.605

Number of Fisher Scoring iterations: 3

Note that we indeed find an effect for the interest rate and none for the level of income, which does match the simulated data.
Comment: Please consider accepting the answer if this resolved your issue. You can use the + / - system on the top left of answers to indicate whether or not you found an answer useful.


React-aria | typescript error on input/ textfield

Question: I would like to work with react-aria. Unfortunately I don't get this far.
I followed the documentation (https://react-spectrum.adobe.com/react-aria/useTextField.html) but this Error pops up on the input Element. Hope somebody can help me.
Code
import { AriaTextFieldOptions, useTextField } from "@react-aria/textfield";

function TextField(props: AriaTextFieldOptions) {
  let ref = useRef<HTMLInputElement>(null);
  let { inputProps } = useTextField(props, ref);

  return (
    <>
      <input {...inputProps} ref={ref} />
    </>
  );
}

Error
Type '{ ref: RefObject<HTMLInputElement>; accept?: string | undefined; alt?: string | undefined; autoComplete?: string | undefined; autoFocus?: boolean | undefined; ... 281 more ...; onTransitionEndCapture?: TransitionEventHandler<...> | undefined; } | { ...; }' is not assignable to type 'DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>'.
  Type '{ ref: RefObject<HTMLInputElement>; autoComplete?: string | undefined; autoFocus?: boolean | undefined; cols?: number | undefined; dirName?: string | undefined; ... 263 more ...; onTransitionEndCapture?: TransitionEventHandler<...> | undefined; }' is not assignable to type 'DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>'.
    Type '{ ref: RefObject<HTMLInputElement>; autoComplete?: string | undefined; autoFocus?: boolean | undefined; cols?: number | undefined; dirName?: string | undefined; ... 263 more ...; onTransitionEndCapture?: TransitionEventHandler<...> | undefined; }' is not assignable to type 'InputHTMLAttributes<HTMLInputElement>'.
      Types of property 'onChange' are incompatible.
        Type 'ChangeEventHandler<HTMLTextAreaElement> | undefined' is not assignable to type 'ChangeEventHandler<HTMLInputElement> | undefined'.
          Type 'ChangeEventHandler<HTMLTextAreaElement>' is not assignable to type 'ChangeEventHandler<HTMLInputElement>'.
            Type 'HTMLTextAreaElement' is missing the following properties from type 'HTMLInputElement': accept, align, alt, capture, and 26 more.ts(2322)

Sandbox
https://codesandbox.io/s/hopeful-wood-zicxn?file=/src/App.tsx
Best regards
J.
Answer: Looks like TypeScript is having difficulty figuring out whether your HTML element is a textarea or an input, so let's give it a hand:
import { AriaTextFieldOptions, useTextField } from "@react-aria/textfield";

function TextField(props: AriaTextFieldOptions) {
  let ref = useRef<HTMLInputElement>(null);
  let { inputProps } = useTextField(props, ref);

  return (
    <>
      <input {...(inputProps as InputHTMLAttributes<HTMLInputElement>)} ref={ref} />
    </>
  );
}


Cocartesian squares in the category of abelian groups.

Question: Recently, I've been doing a recap of (basic) category theory and found an old exercise I seem to be unable to solve. The question is as follows.
Let $A, B$ be abelian groups, $A'<A$ and $B'<B$ subroups and $\phi:A\to B$ such that $\phi(A')\subseteq B'$. Let $\phi':A'\to B'$ and $\phi'':A/A'\to B/B'$ be the maps induced by $\phi$. Prove that the diagram
\begin{array}
AA' & \to & A \\
\downarrow{\phi'} & & \downarrow{\phi} \\
B' & \to & B
\end{array}
is a cocartisian square if and only if $\phi''$ is an isomorphism.
The exercise preceding this one looks like a dual statement which I did manage to prove (a similar square being cartesian iff $\phi'$ is an iso), yet just dualising the proof doesn't seem to work. That proof, however, suggests using the universal property of cocartesian squares for one of the implications ($\Rightarrow$), while using the explicit construction of pushouts in the category of abelian for the other one. The pushout of $A_1\overset{f_1}{\leftarrow} A_3 \overset{f_2}{\rightarrow} A_2$ in this category is given by $A_1\oplus A_2/\{(f_1(x),-f_2(x))\mid x\in A_3\}$.
Can anyone provide me with a proof, or give a sketch of proof that might point out which step I fail to see just yet?
Comment: @Andy "Cocartesian" does not name the pushout (i.e. the vertex of the colimit), but the diagram involving the pushout. So it is a name for the universal cocone with vertex the pushout. (This designation comes from french, probably from EGA/SGA.)
Comment: @rschwieb, it's another (weird) name for a pushout, which is the categorical dual of a pullback, which is also sometimes known as "fibered product".
Comment: @Andy Oh yes you're absolutely right. I assumed too fast that you were talking about the vertex. Sorry for the misunderstanding.
Comment: Wow, this is *basic*? :)
Comment: Well, it occured in the third or fourth week in a second-year course on category theory. Even though the course was far too difficult at the time, I assumed this would still make it basic category theory. I'm willing to take out the word 'basic' from the description, if you think that suits it better.
Comment: @rschwieb, how is it not basic? It is a question on a colimit in a specific category. Limits and colimits are very basic categorical notions.
Comment: @Andy Mainly it is because I've never heard of a Cartesian square, much less a cocartesian one :)
Comment: @Pece, good to know. Thanks. But it's a bit of a technicality, a colimit is a universal cocone; so a pushout is the whole diagram, and by abuse of notation we consider it to be just the (obvious) vertex, or am I wrong?
Comment: @Andy That makes more sense then :) Thanks for the terminology pointer.
Comment: Thanks for these remarks about the history of the name cocartesian! In the lecture notes the different names are used interchangeably without really pointing out which ones are used more generally and without reference to their origins.
Answer: Take $A' \to A \to A/A'$, the first map is the inclusion and the second is the quotient projection. Take then $B' \to B \to B/B'$, the maps as above. These are both exact sequences, which means $\operatorname{im}(\text{inclusion}) = \ker(\text{projection})$. You should notice that $(\phi', \phi, \phi'')$ is a morphism of exact sequences, which means that this triple makes the obvious diagram commute.
Now, you may check that the sequence $B' \to P \to \operatorname{coker}(i)$ is exact, if $P$ is the pushout of the inclusion $A' \subseteq A$ along $\phi'$ and $i$ is the standard inclusion of $B'$ into the direct sum you mention. If you put the two diagrams together (the one that describes the map $(\phi', \phi, \phi'')$ and the one with $(\phi', j, k)$, where $j\colon A \to P$ is the standard inclusion and $k\colon A/A' \to \operatorname{coker}(i)$), you notice that there is also a map form $B$ to $P$ because of the universal property of $P$. As you should know the universal map is an iso, so $B \cong P$. Then you notice that $\operatorname{coker}(i)$ is iso to $B/B'$, because the inclusions $B' \subseteq B$ and $B' \subseteq P$ differ by an iso. This means that your square is in fact a pushout.
This is a succession of iff-s, so your claim is proved. This should be so much easier if you write down the diagrams I mention, which I cannot do here, since it looks like mathjax does not support xypic, and I'm not familiar with any other way of writing commutative diagrams.
Clarification: I understand this is an exercise in category theory and I didn't use any strictly categorical methods, but you should notice that the category of abelian groups is an abelian category and this is actually done in utter generality in any abelian category if, instead of quotients you take cokernels.
EDIT: Here's the diagram I was talking about.
Comment: You can try [presheaf](http://presheaf.com/) for drawing diagrams (it's probably best to right click the rendered diagram, copy the link and upload the image into your answer).
Comment: @Martin, very nice thanks! I'll edit the question tomorrow morning, it's kind of late right now.
Comment: @Andy: I unfortunately hadn't been able to look at this before. Up to the point where you say 'so $B\cong P'$ I can follow you, but I fail to see why this iso holds. It is clear where the unique map $B\to P$ comes from. I'd, however, only expect it to be an iso if we already knew $B$ to be the pushout, which is what we're trying to prove. What is it that I'm still missing?
Comment: @Martin: thanks a lot! I had problems writing diagrams as well.
Comment: @HSN: the universal morphism is always an iso if all the right squares commute, because it means that the other object is also a (co)limit. Try to write it out in general: take a limiting (co)cone and another limiting (co)cone (this means that everything that needs to commute, does) you have two unique morphisms one from and one to; it should be easy to convice yourself that these are one the inverse of the other. This is the case in this situation: all the "right" squares commute.
Comment: Ah, of course. Thanks!


UISearchController searchbar disappear after clicked

Question: I have UISearchController in my application:
self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
[self.searchController setSearchResultsUpdater:self];
[self.searchController setDelegate:self];

if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"9.1")) {
    self.searchController.obscuresBackgroundDuringPresentation = NO;
}

self.searchController.searchBar.showsCancelButton = YES;

[self.searchBarView addSubview:self.searchController.searchBar];
self.searchController.searchBar.delegate = self;

The issue is that after i click the search bar it disappears from the screen:

Any idea how i can fix this problem?
Comment: instead of manually adding a subview.. try `navigationItem.searchController = searchController`
Answer: add these line of code in your controller
 self.searchController.hidesNavigationBarDuringPresentation = NO;
 self.searchController.dimsBackgroundDuringPresentation = NO;
 self.definesPresentationContext = YES;

hope it will solve your issue ... if not ... let me know in comments
Comment: I tried it but when i use it the searchvc not fill the screen after clicked
Comment: try it out now .


When is the Duckworth-Lewis method applied?

Question: I've read a minimal amount about this in some of the questions which have been posted already here and the posts which were linked. However, I'm still unsure if the Duckworth-Lewis method is applied in the following scenarios:

When the rain interrupts in the middle of the first innings of a 50 over match?
When the rain interrupts once the first innings is complete?
When the rain interrupts once the second team has batted a certain number of overs?
Answer: Yes, the Duckworth-Lewis method would be applied in all three scenarios. The only scenario in which a rain-shortened match does not have the Duckworth-Lewis method applied is if the match is shortened before the start of the first team's innings, as in that case both teams are equally aware of the number of overs they will face before starting their innings.


Given correlation of X and Y, and x, find y

Question: I have two time series X and Y and their correlation.
If I am given x at a particular time, how do I find out what y at that time should be?
Is it finding the expected value of y, E(Y|X=x)? If so, how do I do it?
Thanks
Answer: Asuming unit variance of both variables :
Y = corr*X + sqroot(1-corr^2)X
Hence to use the formula you need to use standardized X and Y
Comment: This formula cant be correct... This looks more like linear regression. Its similar but they aren't the same.
Comment: What is this formula called? I'd like to understand it before using it. Thanks
Comment: You are right, Wei Zeng: because correlation contains no information about the means, there's no way to predict $y$ at all.  If you had information about the means you could indeed regress $y$ on $x$--but the formula quoted here would be wrong (even after standardizing $x$ and $y$).  Refer to standard formulas for regression coefficients posted elsewhere on this site or in regression textbooks.


prevent an infinite loop in a production system(Js Code Test question)

Question: Please understand the following program:
function recur(n, cur) {
  if (!cur) {
    cur = 0;
  }
  if (n < 2) {
    throw new Error('Invalid input');
  }
  if (n === 2) {
    return 1 / n + cur;
  }
  return recur(n - 1, cur + 1 / (n * (n - 1)));
}

To prevent an infinite loop in a production system. Write a program doing the same
calculation without recursion. Please be reminded that a while loop is also considered
not good in a production system.
I don't quite understand what the original CODE is supposed to do  :(
Comment: @OskarGrosser I'm afraid it's not taken care of, that checks for `cur`, but we're talking about `n`.
Comment: correct me if i'm wrong, but your `recur` can't fall into infinite loop.
Comment: Assuming that your first argument (`n`) is a number, any `n < 2` will throw the error, and any `n > 2` will eventually get to 2, since the recursive function is called with `n - 1` as the first argument. Therefore, it terminates. So, is that your question (understanding why it terminates), or are you seeking help to rewrite it without recursion?
Comment: yes, i am seeking help to rewrite it without recursion :)
Comment: @GerardoFurtado `n = Infinity` is a special case, which would _not_ eventually get to 2 but result in an infinite loop.
Comment: @OskarGrosser I know that in JS typeof Infinity gives "number", but mathematically speaking Infinity is not a number... But yes, it should be *"Assuming that your first argument (n) is a number, but not `Infinity` or `NaN`"*, because despite the name `NaN` is also a number...
Comment: @GerardoFurtado Absolutely! I just thought since this is a _test_ question asking "to prevent an _infinite_ loop" that we should look at corner cases like Infinity. NaN is taken care of by: `if (!cur) cur = 0;`
Answer: here is your function without recursive.
function nonRecur(n, cur) {
    if (!cur) {
        cur = 0;
    }
    if (n < 2) {
        throw new Error('Invalid input');
    }
    for (; n > 1; --n){
        if (n === 2) {
            cur = 1 / n + cur;
            break;
        }
        cur = cur + 1 / (n * (n - 1));
    }
    return cur
}

Comment: Oic, you're great
Answer: you can try below code for the same
function recur(n, cur) {
 if (!cur) {
  cur = 0;
 }
 if (n < 2) {
  throw new Error('Invalid input');
 }
 for(var i = n; i > 2; i--){
    cur = cur+1/(i * (i -1));
 }
 return 1 / i + cur;
}

Answer: Python solution for this
# Cur default value is 0, if it is not pass.

def recurFunction(n,cur=0):
    if n < 2:
        # print("Error: Invalid input")
        return ValueError("Invalid input")

    # Decreasing the value of n by 1 till n become 2
    for i in range(n,1,-1):
        if i == 2:
            return 1/i+cur
        else:
            cur = cur+1/(i * (i -1))

Answer: In python, we can convert this recursion problem into iteration by following snippet.  . Also there is a website where you visually check the recursion process Visualise Recursion process. I hope you will find my solution perfect.


Renewal Process - Inventory problem

Question: This one is an example from the book A First Course in Stochastic Models by H.C. Tijms (Chapter 2: Renewal-Reward Processes).

Consider a periodic-review inventory system for which the demands for a single product in the successive weeks $t = 1, 2, \dots$ are independent random variables having a common continuous distribution. Let $X_i$ be the demand in the $ith$ week, $i=1, 2, \dots$. Then $1+N(u)$ is the number of weeks until depletion of the current stock $u$.

I try to understand why the number of weeks until depletion by:

Let $u$ be current stock, so $u$ should be a non-negative integer number.
The total number of this kind of product that have been delivered till week $n$ is $S_n = \sum_{i=1}^n X_i$.
Then $N(u)$ is the number of weeks until $S_n \leq u$.

I cannot derive the result $1 + N(u)$. Also, why does the demand $X_i$ have the continuous distribution since it receives discrete values (or do I misunderstand something there)?
Answer: A product such as oil may have a continuous demand, for example.
Since $N(u)=\sup\{n>0:S_n\leqslant u\}$ and $\mathbb P(S_n=u)=0$ (due to $S_n$ being a continuous random variable), here $N(u)$ is the week before depletion of stock, hence the $1+N(u)$.

Renewal Process - Inventory problem


Questions about 4 part chord

Question: Is this correct for a C major chord
I am kind of confused.
Answer: Assuming it's a standard stave, with G clef and F clef, then yes, because there are the three notes constituting C major - C, E and G. Order doesn't necessarily matter, that just changes the voicing, and how it's described - root, 1st, 2nd inversion. What are you actually confused about?
It must also be assumed that the line is in the key of G, making this C chord correct as the IV.
Comment: I agree the four notes C, G, E, C make a C chord.

Questions about 4 part chord


URLDecoder in android

Question: Please see this link.We will be able to send the data by the following code:
String data = URLEncoder.encode("name", "UTF-8")
                         + "=" + URLEncoder.encode(Name, "UTF-8");

            data += "&" + URLEncoder.encode("email", "UTF-8") + "="
                        + URLEncoder.encode(Email, "UTF-8");

            data += "&" + URLEncoder.encode("user", "UTF-8")
                        + "=" + URLEncoder.encode(Login, "UTF-8");

            data += "&" + URLEncoder.encode("pass", "UTF-8")
                        + "=" + URLEncoder.encode(Pass, "UTF-8");

and then when the php file tries to send the string variables using the echo command, How can I get the variable values in php separately in java variables?
As a visual description, I want such a thing:
//in java-> String name = echo "$name" //in php
//in java-> String pass = echo "$pass" //in php and etc.

in existing code in the link we can assign the all input strings only in the one variable java such as text = sb.toString();. I want assign for each echo $variable in php, one specific variable in java that as the result I can display each of them in arbitrary places in activity. Please explain me on based the link to prevent bewilderment. Thank you.
Comment: echo json_ecode string from php and parse it on android side
Answer: Do following in php:
echo "{";
echo "\"name\":\"$name\",\"pass\":\"$pass\"";
echo "}";

Use following in java code:
String response = ""; // response from php page.
    String name,pass;
    try
    {
        JSONObject obj = new JSONObject(response);
        name = obj.getString("name"); // value of $name
        pass = obj.getString("pass"); // value of $pass
    } catch (JSONException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Do read about JSON to have better understanding about it.

URLDecoder in android


Find the domain and range of $f\left(x\right)=\sec^{-1}\left(2x-x^{2}\right)$.

Question: As the title suggests, find the domain and range of $$f\left(x\right)=\sec^{-1}\left(2x-x^{2}\right)$$
I did find the domain to be either $x=1$ or $x\in\left(-\infty,1-\sqrt{2}\right]\cup\left[1+\sqrt{2},\infty\right)$. But finding the $\operatorname{arcsec}\left(\right)$ function is turning out to be really confusing. Could anyone help?
Answer: For domain just solve:
$f(x)\leq -1$  or  $f(x)\geq1$
For range:
$f(x)=0$ or $\frac{\pi}{2}<f(x)\leq \pi$
Answer: For the domain of $f(x)$; $2x-x^{2}\geq1$ . And also $2x-x^{2}\leq-1$ . So, you will get $x^{2}-2x+1\leq0$ and $x^{2}-2x-1\geq0$ . Now you will get 3 values of $x$ $i.e.$ $1-\sqrt{2},1,1+\sqrt{2}$ . Now $x^{2}-2x+1$ is never$<0$. It can be equal to $0$. So, the only possibility is $x^{2}-2x-1\geq0$ . So, your domain will be $(-\infty,1-\sqrt{2}]\cup[1+\sqrt{2},\infty)$ . And Range will be $(\frac{\pi}{2},\pi]$.


Proving $\left\vert\int_n^{n+1}s\int_n^xt^{-s-1}dt\,dx\right\vert<\vert sn^{-s-1}\vert$, for $n \in \mathbb{N}$, $x \in [n;n+1]$, $s\in \mathbb{C}$

Question: Let's get out of silence? I try to prove the Riemann hypothesis because I have the humble intuition that it is true, whatever you may think of this step, with my little skills. I have time, so...
I try several ways, one is to use the Dirichlet eta function: for $s\in \mathbb{C}, \Re(s)>0,  \displaystyle \eta(s) = \sum \limits_{n=1}^{\infty} \frac{(-1)^{n-1}}{n^s}$.
We have, for $s \in \mathbb{C}, 0<\Re(s)<1$, $\zeta(s) = 0 \Rightarrow \eta(s) = 0 \Rightarrow \Im(\eta(s))=0$. And:
$$\displaystyle 0=\Im(\eta(s))= \lim \limits_{N \rightarrow \infty} \sum \limits_{n=1}^{N} (-1)^{n} ~n^{-\Re(s)} \sin(\Im(s)\ln(n)) = \lim \limits_{N \rightarrow \infty} \sum \limits_{n=1}^{N} \cos(n\pi) ~n^{-a} \sin(b\ln(n)),$$
where $a = \Re(s), b = \Im(s)$.
I've read the following, and it may help me but I don't know how to prove it, for $n \in \mathbb{N}$, $ s\in \mathbb{C}$, $ 0<\Re(s)<1$ : $$\displaystyle \left\vert n^{-s} - \int_{n}^{n+1} x^{-s} \right\vert < \left\vert\int_n^{n+1} s \int_n^xt^{-s-1}dt\,dx\right\vert<| sn^{-s-1}|, $$ which implies that: $$ \displaystyle \left\vert \sum \limits_{n=1}^{N} n^{-s} - \int_{n}^{n+1} x^{-s} \right\vert < \sum \limits_{n=1}^{N} | sn^{-s-1}| $$
I thought I could use the idea of this inequality to study the sum $\displaystyle \sum \limits_{n=1}^{N} \cos(n\pi) ~n^{-a} \sin(b\ln(n))$, beginning by something like this: $$\displaystyle \left\vert \cos(n\pi) ~n^{-a} \sin(b\ln(n)) - \int_{n}^{n+1} \cos(\pi x) ~x^{-a} \sin(b\ln(x)) \right\vert < ~...$$
So, how to prove this simple double integral inequality?

For $n \in \mathbb{N}$, $x \in [n;n+1]$, $s\in \mathbb{C}$, $$\left\vert\int_n^{n+1}s\int_n^xt^{-s-1}dt\,dx\right\vert<  |  sn^{-s-1} |  $$

I've tried to say : $n \le t \le x \le n+1$, and to use the triangle inequality.
Comment: [Related](https://math.stackexchange.com/a/3341477/121671)
Comment: What have you tried?
Answer: This is a partial answer for a few cases in case it is helpful.
Case: $s = 0$. It's not true for $s=0$ because you have equality.
Case: $\text{Re}(s) > -1$ and $s\ne 0$. Using the triangle inequality for integrals, we have
$$\left\vert\int_n^{n+1}s\int_n^xt^{-s-1}dt\,dx\right\vert \le \int_n^{n+1} |s| \int_n^x \left\vert t^{-s-1}\right\vert dt\,dx < \int_n^{n+1} |s| \int_n^{n+1} \left\vert t^{-s-1}\right\vert dt\,dx $$
When $\text{Re}(s) > -1$, $f(t)=| t^{-s-1}|$ is a decreasing function, so its maximum in $[n,n+1]$ is $f(n) = |n^{-s-1}|$, which gives you the result.
Comment: Your second argument works if $\text{Re}(s) > -1$ and $s\neq 0$.
Comment: Yes, that's right. Edited!
Comment: Btw, try avoiding answering questions where the OP does not show any effort in solving the problem. Please also read the [meta announcement](https://math.meta.stackexchange.com/questions/33508/enforcement-of-quality-standards) regarding quality standards.


Finding the equation of a line that is tangent to.

Question: I have the following question & its answer but I do not understand how some parts were obtained - Q&A, Previous Q
Where does the $1+dy/dx (x-1)$ come from?
Comment: Please study [our guide to new askers](https://math.meta.stackexchange.com/q/9959/11619), and improve the question.
Answer: Hint: Assuming $y=y(x)$ then we get by the chain and product rule
$4x+2y(x)y'(x)+2y(x)+2xy'(x)=0$
Can you finish?
Comment: I've already worked that out to be $-2x+y/x+y$ that's where I apply the bottom bit and get $-(3/2)$ I don't get where the $(x-1)$ comes from.
Answer: ok so you don't have any problem with calculating $\frac{dy}{dx}$
you want to find the tangent at the curve at the point (1,1)
the equation of a line passing through the point (1,1) is given by
$$(y-1)=m(x-1)$$
where m is the slope of the line
now to calculate$$ m=slope=\frac{dy}{dx}\big|_{(1,1)}$$
$$ m=slope=-\frac{2x+y}{x+y}\big|_{(1,1)}$$
$$ m=slope=-\frac{2(1)+(1)}{(1)+(1)}=\frac{-3}{2}$$
thus equation of tangent $$(y-1)=-\frac{3}{2}(x-1)$$
                         $$y-1=-\frac{3}{2}x+\frac{3}{2}$$
$$y=-\frac{3}{2}x+\frac{5}{2}$$
Comment: That makes perfect sense, that's exactly what I was looking for, thank you.