How to copy a pdf file with the amount of copies in the database as the value using C#?

Question: I need to get the amount of copies from my local database and use that value to make copies of the pdf file.
<code>         public Boolean getAmountOfCopies()
         {
             string connectionString = null;
             MySqlConnection cnn;
             connectionString = "databaseInformation";
             cnn = new MySqlConnection(connectionString);
             try
             {
                 cnn.Open();
                 Console.WriteLine("Connection Open");
                 const string sql = "SELECT numberofcopies FROM orders";
                 MySqlCommand cmd = new MySqlCommand(sql, cnn);
                 MySqlDataReader rdr = cmd.ExecuteReader();

                 while (rdr.Read())
                 {
                     if (rdr[0] == null)
                     {
                         Console.WriteLine("There is no value, it is null.");
                         return false;
                     }
                     else
                     {
                         Console.WriteLine(rdr[0]);
                         var ImageFiles = Directory.EnumerateFiles(Directory.GetCurrentDirectory()).Where(f => f.EndsWith(".jpg") || f.EndsWith(".JPG") || f.EndsWith(".jpeg") || f.EndsWith(".jfif"));
                         List<string> images = ImageFiles.ToList();
                         PdfDocument[] copyOfPDF = new PdfDocument[images.Count()];

                         // Code goes here to make the copy
                     }
                 }
                 cnn.Close();
                 Console.WriteLine("Connection Closed");
                 return true;
             }
             catch (Exception ex)
             {
                 Console.WriteLine(ex);
                 return false;
             }
         }
</code>
The rdr[0] is the value being taken from the database in numberofcopies column. I need to use that value to make the amount of copies based on that value.
Hopefully it is not too confusing, if you need clarification please let me know and i will provide further information.
Thank you.
Comment: Why not using `File.Copy` from `System.IO` namespace?
Comment: Just put `File.Copy` inside a `for` loop... keep in mind that you have to give different names to the copied files if they go in the same folder
Comment: You can use the value of the interger varible of the loop to create the name of the file with something like `string name = $"{base_name}_{i}.pfd";`
Comment: That's a good suggestion, I am not so good with C# inbuilt functions and the language itself. But I don't know how to apply File.Copy to my existing code.
Comment: Ok so File.Copy works, but how do i specifiy the amount of copies i want? For example, in the database if it says 2 copies then the code will have 2 copies in that specific folder.
Comment: So does that mean i need to make a 2 for loops? 1 for the changing for the name of the file so that it is like filename.pdf, filename1.pdf, filename2.pdf then also make a for loop for the File.Copy and get the amount for the select query value in the database?
Comment: Thank you for the help, I will try it and post the code when i get it to work <3
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/245078/discussion-between-kingskitz-and-marco-beninca).
Answer: Made it work by adding this.
<code>while (rdr.Read())
                 {
                     //Checks if the value is null
                     if (rdr[0] == null)
                     {
                         //If it is null execute the Console.WriteLine
                         Console.WriteLine("There is no value, it is null.");
                         return false;
                     }
                     else
                     {
                         //Converting object to int
                         int numberOfCopies = Convert.ToInt32(rdr[0]);
                         //Source directory for the PDF
                         string sourceDir = @"C:/Orders/0931617841_13_05_22/";
                         //Source directory for the new folder directory
                         string backupDir = @"C:/Orders/AmountOfCopies";

                         //If not null
                         try
                         {
                             //Gets the file composite.pdf inside the 'sourceDir' variable, which is instantiated above
                             string[] pdfList = Directory.GetFiles(sourceDir, "*.pdf");

                             // Copy pdf file.
                             foreach (string f in pdfList)
                             {
                                 //For loop to change the file name using 'i'
                                 for (int i = 0; i < numberOfCopies; i++)
                                 {
                                     string oldPath = @"C:/Orders/0931617841_13_05_22/composite.pdf";
                                     string newpath = @"C:/Orders/AmountOfCopies/";
                                     string newFileName = "composite" + i;
                                     FileInfo f1 = new FileInfo(oldPath);
                                     if(f1.Exists)
                                     {
                                         if(!Directory.Exists(newpath))
                                         {
                                             Directory.CreateDirectory(newpath);
                                         }
                                         f1.CopyTo(string.Format("{0}{1}{2}", newpath, newFileName, f1.Extension));
                                     }
                                 }
                             }
                         }
                        //If no directory as that name is found execute exception
                         catch (DirectoryNotFoundException dirNotFound)
                         {
                             Console.WriteLine(dirNotFound.Message);
                         }
                     }
                 }
</code>


Is it valid to reduce noise in the test data from noisy experiments by averaging over multiple runs?

Question: I have data from a biological (fMRI) experiment that was previously evaluated with a different model in a machine learning fashion, using a training and a validation set in a cross-validation routine for finding regularization parameters and a test set for the final evaluation. The data is used to predict the brain activity of single voxels in time, based on a set of stimulus features for each time point.
The experimenters have made sure to acquire a relatively long training data set for getting a good regularized regression model in the end. However the experimenters had also decided to record the much shorter test data set multiple times (at several time points during the experiment) and evaluate on an average between all runs. I can understand this decision since BOLD data from fMRI experiments is very prone to noise, e.g. from subjects not paying attention, adapting too much or getting drowsy throughout the experiment, i.e. the test set recording can easily be corrupted by random influences.
My question: To what extend can this decision - recording the test data set multiple times and using its average for evaluation - be criticized from a machine learning perspective? I would like to stick to their routine for comparability, but always stumble over this question.
What I notice during my own model training is a model performance increase in the test set (which is no big surprise to me since the noise is gone) in comparison to the training set performance. This is almost consistent, however there are cases when the model only works on the training dataset and not on the test set at all (i.e.: I think it is possible to still spot overfitting).
Comment: So the training data is raw data and the test data has been averaged across multiple runs? Seems backwards.
Comment: @Wayne Would help if you could elaborate on "backwards".
Comment: The training data represents the data you have before deploying your model, and the test data represents data you will get after it's deployed. In general, real-world data will be noisier than your training data -- which you can work on in more detail, get additional information, etc. You're testing on "cleaner" -- more smoothed, actually -- data than you trained on, which seems unusual. (I'd also be interested in whether the averaged data is validation or test data, or both.)
Answer: I think that the experimenters' decision fits into general resampling statistical strategy. Having said that, I'm not sure what specific aspects, if any, might be used to criticize this approach from the machine learning perspective.
In regard to reducing noisy data, while I'm not sure how applicable it is in your subject domain, you might want to check my hopefully relevant answer. Moreover, I think that it might make sense to use clustering to detect and eliminate noisy data by applying bootstrapping technique. Please see my answer on using bootstrapping for clustering.


What does the new full stop / period mean in the RHEL6 ls output?

Question: We have scripts looking at the output of ls -l output for permission information that have been failing recently on RHEL v6 systems which appear to be showing an extra . at the end of the permission entry that didn't used to  be there before:
[root@rhel6vm ~]# ls -l
total 44
-rw-------. 1 root root  1399 Aug 17 15:01 anaconda-ks.cfg
-rw-r--r--. 1 root root 25485 Aug 17 15:01 install.log
-rw-r--r--. 1 root root  7253 Aug 17 14:59 install.log.syslog
[root@rhel6vm ~]#
          ^
          | up there

What does the full stop signify? And what else can appear in it's place?
Comment: `We have scripts looking at the output of ls`, that is generally a [bad idea](http://mywiki.wooledge.org/ParsingLs).  Parsing ls is a bad idea.  You would be better off looking at the output of stat or some other tool for this purpose.
Answer: info ls shows:
  Following the file mode bits is a single character that specifies
 whether an alternate access method such as an access control list
 applies to the file.  When the character following the file mode
 bits is a space, there is no alternate access method.  When it is
 a printing character, then there is such a method.

 GNU `ls' uses a `.' character to indicate a file with an SELinux
 security context, but no other alternate access method.

 A file with any other combination of alternate access methods is
 marked with a `+' character.

Comment: aha - had looked at `man ls' but didn't think of `info ls' - thanks
Answer: GNU ls uses a . character to indicate a file with an SELinux security context, but no other alternate access method.
A file with any other combination of alternate access methods is marked with a + character.


dagger2 components - design pattern to not have so many inject calls in one interface

Question: I am searching for a way or design pattern i can use so that dagger2 components to not have so many inject calls.  Lets have a look at what i mean on a enterprise level:
Singleton
          @Component(modules = {AppModule.class, NetworkModule.class, RepositoryModule.class})
          public interface AppComponent {

              void inject(UserDataRepository target);

              void inject(DoStandardLoginUsecase target);

              void inject(NetworkSessionManager target);

              void inject(SharedPrefRepo target);

              void inject(getSharedPrefUsecase target);

              ActivitySubComponent plus(ActivityModule activityModule);

              PresenterSubComponent plus(PresenterModule presenterModule, UseCaseModule useCaseModule);
}
//.. this list is going to be gigantic in a year. how can i minimize it or make the inject calls somewhere else or group them ?

I need a way to group the inject calls somewhere else before they get out of control.
Comment: Are `UserDataRepository`, `NetworkSessionManager`, etc extending Android Framework components? Why don't you let them be constructor injected?
Comment: Yes. If you use constructor injection you can get rid of all those `inject(...)` lines
Comment: Because i find it so hard to know what's being provided if i do that. You mean dont put the dependency in a module but rather just mark the constructor right?
Comment: hey thanks for the response. but if you take a look at the accepted answer of this post: https://stackoverflow.com/questions/32076244/dagger-2-injecting-parameters-of-constructor     the author is putting the method names inside the component interface ? specifically:  Singleton
@Component // no modules
public interface SingletonComponent {
    Thermosiphon thermosiphon();
    Heater heater();

    void inject(Something something);
}     he is doing this even though he is doing constructor injection ... i must be missing something ?
Comment: `Heater getHeater()` exposes a getter to manually get the object or expose it to dependent components, `void inject(Something something)` injects your objects, which you should do for framework components (only default constructors) but can avoid for your own code (use constructor injection instead). Your code seems to inject everything manually, and as pointed out, you could just switch to constructor injection
Answer: Remember that your Component is a list of entry points into your object graph, and that your objects can depend on each other without being listed on the Component. This is true regardless of whether you use constructor injection or module configuration. Consequently, your Component will likely only include an inject for your classes that Dagger can't or shouldn't instantiate itself, including your Application, Activities, Fragments, and other system services.
It's also true that Dagger will populate @Inject fields and call @Inject methods itself after calling the constructor:
public class UserDataRepository {
  @Inject public UserDataRepository() {}  /** So Dagger knows how to create one */

  @Inject FieldOne fieldOne;
  @Inject FieldTwo fieldTwo;

  @Inject void initialize(DepThree depThree, DepFour depFour) {
    // ...
  }

  // ...
}

Though I personally prefer constructor injection so I can set those fields to final, you may prefer keeping them mutable and @Inject-annotated; that doesn't mean you need to list them on your Component or construct them using a Module.


Reverse the sign of PCA

Question: I'm struggling on getting a good explanation for the unexpected signs of Principal Component for months. I tried to replicate a result and I got exactly the opposite signs for all components. While I searched through forums for an answer, I found this website I'm getting "jumpy" loadings in rollapply PCA in R. Can I fix it?
From what I have read from this website, I understand that we can reverse the sign  of components based on other criteria - e.g. EURO trend - as what have been mentioned by @amoeba. I'm wondering if there is a book or academic literature that says that we can flip the sign in this way (i.e. based on external factor)? I need a strong support for my research paper if I flip the signs of all components in this way. Hence, I would greatly appreciate if someone can recommend me some books that talk about this issue?
And also @amoeba mentioned that the signs are consistent in sliding PCA. Does it mean that we should have the same combination for each window (for example +a, +b, -c in first window & -a, -b, +c in second window)? So, if I think the signs in second window are correct, then I will flip the 1st window's vector and both vectors will have the same sign by then. What if they have different combination (e.g. +a, -b, -c in second window)? I think their correlation could have changed from time to time and hence we will have different combinations in different windows?
Comment: It's unclear what needs a "proof."  Since the sign of an eigenvector is arbitrary, you can use any procedure you like to set it.  Could you show us specifically how your question differs from the one you cite?
Comment: Regarding the sign being arbitrary see also http://stats.stackexchange.com/questions/88880. You don't need any "book or academic literature" allowing you to reverse the sign; you can simply reverse it as you like.
Comment: @whuber I have the same question with previous posts and I have better understanding now on the flipping sign. But, I would like to ask if there is any literature can be used as a support to justify why I flip the sign based on some external factor. Amoeba has just answered the question. Reg. my second question, I'm wondering if the signs of all components should be the same for every window? What if I have different combination of sign in every window (e.g. +a, +b, -c in my 1st window and -a, +b, +c in my 2nd window)?
Answer: Something that various people are pointing out is that the vectors $(1,1)$, $(2,2)$, or $(-1,-1)$ all represent the same line. When you find an eigenvector, what's uniquely determined is the line, not the actual vector.
An eigenvector for a matrix (linear transformation) $A$ is defined as any vector $\mathbf{v} \neq \mathbf{0}$ which satisfies:
$$A \mathbf{v} = \lambda \mathbf{v}$$
If $\mathbf{v}$ is an eigenvector, any scalar multiple $\hat{\mathbf{v}} = \alpha \mathbf{v}$ will also work ($\alpha \neq 0$):
\begin{align*}
A \mathbf{v} = \lambda \mathbf{v}\quad  & \Leftrightarrow \quad \alpha A \mathbf{v} = \alpha \lambda \mathbf{v} \\ & \Leftrightarrow  \quad A\hat{\mathbf{v}} = \lambda \hat{\mathbf{v}}
\end{align*}
Eg. Choose $\alpha = -1$. If $\mathbf{v}$ is an eigenvector, so is $-\mathbf{v}$.
Let's say your PCA algorithm guarantees you that $\|\mathbf{v}\| = 1$. You still have two possibilities because if you take the intersection of a line through the origin and the unit circle, you get two points.

In this example, whether you have $\mathbf{v} = (\frac{\sqrt{2}}{2},\frac{\sqrt{2}}{2})$ or $\mathbf{v} = (-\frac{\sqrt{2}}{2},-\frac{\sqrt{2}}{2})$, it really doesn't matter.
A fun example of flipping the sign on basis vectors: upside down map
Instead of a map where the y-axis measures how far north and the x-axis measures how far east, you could just as easily have a map where the y-axis measures how far south and the x-axis measures how far west.
Up and down would still be aligned with the magnetic axis.

Reverse the sign of PCA


how to expose oracle pl/sql api's as web services in oracle ebs 11.5.10?

Question: how to expose oracle pl/sql api's as web services in oracle ebs 11.5.10? i've read that in oracle ebs r12 there is soa gateway. unfortunately my client will be sticking with 11i version for a couple more years so i'm stuck with it.
does anyone have any suggestions or recommendations?
Comment: You say which version of EBS.  But when it comes to PL/SQL what matters is the version of the database.  Oracle 11g has pretty good support for native PL/SQL web services.
Comment: Hi. Thanks for the tip. But we are currently on Oracle 10g version.
Comment: @APC, can you provide a link if someone is on 11?
Answer: I'm not sure if this is available for your version of EBS but

The Oracle Integration Repository is a compilation of information
  about the numerous service endpoints exposed by the Oracle E-Business
  Suite of applications. It provides a complete catalog of Oracle
  E-Business Suite's business service interfaces. The tool lets users
  easily discover and deploy the appropriate business service interface
  for integration with any system, application, or business partner.
Answer: I think you can do it by following the steps below:
Use the tools like jDeveloper to expose the API as a web-service
and then register it in EBS to use it.


Blank page when rendering Bootstrap Component in React

Question: I am kind of new at Front-end development, and I encountered the following bug.
So, I was designing my own project - local store site, every component created by me, but eventually I came to the moment where I would like to use Carousel for displaying products etc, since I'm new and I just wanted to use clean Carousel designs I decided to use Boostrap for React (React-Boostrap). However, when I use it in my component, it renders my page completely blank, it even removes my Navbar component at the top.
I guess it is some Route issue which I could not identify by myself, so please kind developers, I need some help.
Here is the code:
The Carousel component, just copied and pasted it, and wrapped it in Container (yes I tried to remove the container too that's not the issue),
import React from 'react'
import { MainContainer } from '../styles/Products.style'
import Carousel from 'react-bootstrap/Carousel'

const Products = () => {
  return (
    <MainContainer>
      <Carousel>
    <Carousel.Item>

      <Carousel.Caption>

First slide label

Nulla vitae elit libero, a pharetra augue mollis interdum.

      </Carousel.Caption>
    </Carousel.Item>
    <Carousel.Item>

      <Carousel.Caption>

Second slide label

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

      </Carousel.Caption>
    </Carousel.Item>
    <Carousel.Item>

      <Carousel.Caption>

Third slide label

Praesent commodo cursus magna, vel scelerisque nisl consectetur.

      </Carousel.Caption>
    </Carousel.Item>
  </Carousel>
  </MainContainer>

  )
}

export default Products

This is the App.js :
import "./App.css";
import Navbar from "./components/Navbar";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Login from "./components/Login";
import Home from "./components/Home";
import Products from "./components/Products";

function App() {
  return (
    <Router>
      <Navbar />

      <Routes>
        <Route path="/" element={<Home/>}/>
        <Route path="/products" element={<Products/>}/>
        <Route path="/contact" />
        <Route path="/about" />
        <Route path="/signup" element={<Login/>} />
        <Route path="/logout" />

      </Routes>

    </Router>
  );
}

export default App;

Annd Im not sure if it helps but, pasting it just in case - package.json
{
  "dependencies": {
    "axios": "^0.27.2",
    "bootstrap": "^5.1.3",
    "react-bootstrap": "^2.4.0",
    "react-reveal": "^1.2.2",
    "react-router-dom": "^6.3.0" // added this manually, just to try it it didnt work
  }
}

Comment: Do you get any errors?
Comment: Hello, No I dont get errors, It is just pure white blank page.
Comment: Everything looks okay to me. I think the problem is in the `MainContainer` component. Kindly add it to the question.
Comment: Its not from the MainContainer, since I removed it, I tried with blank tag - ```<>```, with empty ``````, and also without anything else.
Comment: What route are you using when it happens?
Comment: You can see in the React Dev Tools (Extension in the Develover Tools in the Borwser) what components are in the Layout, this could be helpull in order to find what is happening
Answer: I have copy/pasted your code and when I go to "/products" I can see the slider. However I had to comment out MainContainer because I have no code for it. (But you have said MainContainer is not the issue anyway).
https://codesandbox.io/s/elastic-vaughan-6bjv3t
Comment: Yeah, I tried to remove it too, but the outcome was pretty much the same.
Comment: but you see my code is working? where is the difference?


Duplicates in a View with Taxonomy

Question: I created a view that has a global combined fields filter setup to search through node's title and a set of taxonomy terms. It works fine but only if I include a "Taxonomy term: Name" field.
This field currently causes each node to appear in the results for each term that is assigned to it. I checked Aggregation Settings for that field but only have these options:[]1
I also tried the Views Distinct module which worked but at a great performance cost. Is there either:

a way I can include terms in the global combine fields filter that I haven't thought of or
a way to prevent the duplicate results?

Thanks for your help
Answer: You can apply GROUP BY or DISTINCT by enabling views aggregation settings to remove duplicate records.

Go and edit your view
In Advanced » OTHER section by enabling Use aggregation: Yes
In FIELDS or FILTER CRITERIA section, select and apply Aggregation
settings for which fields you want to group by or distinct.
Answer: Put this code in your themes template.php file:
<code>function your-theme_views_pre_render(&$view) {
 $used_nids = array();
$new_view_result = array();

 if ($view->name == 'Name_of_your_view') {
foreach ($view->result as $row) {
    if (!in_array($row->nid, $used_nids)) {
      $new_view_result[] = $row;
      $used_nids[] = $row->nid;
    }
  }

$view->result = $new_view_result;
 }
}
</code>

Duplicates in a View with Taxonomy


Proving a set is a subset of a union with itself and another set

Question: Let A and B be sets. Show that
$$\space A \subseteq (A \cup B)$$
My proof is as follows, but I don't feel confident that what I've done is correct. Any input is much appreciated.
$$x \in A \cup B \equiv x \in A \wedge x \in B \equiv x \in A$$
Therefore, A is a subset of the union of A and B.
Comment: one major mistake I see in the proof is you have a logical AND where it should be an OR
Answer: Look closely at your argument: it implies that $x\in A\cup B$ if and only if $x\in A$, which is clearly not the case in general. For instance, if $A=\{0\}$ and $B=\{1\}$, then $1\in A\cup B$, but $1\notin A$.
You're starting in the wrong place. To show that $X\subseteq Y$, you need to show that every member of $X$ is a member of $Y$. To do this you don't start with an arbitrary member of $Y$: some of them may not be in $X$. You start with an arbitrary member of $X$ and try to show that it must belong to $Y$. Here you want to show that $A\subseteq A\cup B$, so you should be starting with an arbitrary member of $A$. And when you do that, the rest of the argument is trivial: if $x\in A$, then it's certainly true that $x\in A$ or $x\in B$, which is what it means to say that $x\in A\cup B$.
If you insist on doing the argument with formal logical expressions, what you want is $$x\in A\to(x\in A\lor x\in B)\leftrightarrow x\in A\cup B\;.$$
Answer: Hint: notice $$(x\in A\lor x\in B)\leftrightarrow x\in A\cup B\;$$ by using this logical statement $$p\Rightarrow p \lor q$$ we have  $$x\in A\Rightarrow (x\in A\lor x\in B).$$
Comment: How do we know $p\Rightarrow p \lor q$ is true. Is it an axiom or definition? Yes, it is intuitively true, but that makes it harder to ask "why is it true". My own guess at an answer would be that the truth depends on the definition of disjunction.
Answer: You're going in the wrong direction. Don't assume $x\in A\cup B$, assume $x\in A$: you want to show that each element in $A$ is also an element of $A\cup B$ (not vice versa). Also, $x\in A\cup B\iff x\in A\textrm{ OR (not and) }x\in B$.
Let $x\in A$, and note that $x\in A\cup B\implies x\in A$ or $x\in B$. But, as $x\in A$, $x\in A\cup B$. Therefore, each element of $A$ is an element of $A\cup B$, so that $A\subseteq A\cup B$.
However, you should note that your proof is the correct proof of $A\cap B\subseteq A$ if you replace your $A\cup B$ with $A\cap B$.
Answer: This sort of argument is best written out in plain language, with minimal use of symbols.
Suppose $x\in A$. That is, $x$ is an element of $A$. Then certainly $x$ is either an element of $A$ or an element of $B$ (or both). Thus $x$ is an element of $A\cup B$, ie. $x\in A\cup B$.
Since we have shown that any element of $A$ is an element of $A\cup B$, $A\subseteq A\cup B$.


Erro ao Consumir api no angular

Question: Boa Tarde
Estou consumindo uma api (pokemon),
Porém não funciona,
PokeListagemComponent.html:6 ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
Meu component :
import { HttpClient } from '@angular/common/http';
import { ApiService } from './../api.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-poke-listagem',
  templateUrl: './poke-listagem.component.html',
  styleUrls: ['./poke-listagem.component.css']
})

export class PokeListagemComponent implements OnInit {

  pokemon: Array<any>;

  constructor(private apiService: ApiService) { }

  ngOnInit() {
    this.listar();
  }

  listar() {
    this.apiService.listar()
      .subscribe(dados => this.pokemon = dados);
  }

}

Meu template :

  {{p.url}}  {{p.name}}

Serviço:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

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

  PokeUrl='http://pokeapi.salestock.net/api/v2/pokemon';
  constructor(private http: HttpClient) { }

  listar() { //lista os filmes
    return this.http.get<any[]>(`${this.PokeUrl}`);
  }

}

Answer: Tenta inicializar a variável
pokemon: Pokemon[]= []

ou
 pokemon: any[]= []

Answer: o retorno da api que está sendo usada retorna um objeto e o ngFor suporta apenas objetos inteiráveis como os arrays
Abaixo segue um exemplo do retorno da url http://pokeapi.salestock.net/api/v2/pokemon
{
    "count": 811,
    "previous": null,
    "results": [
        {
            "url": "http://pokeapi.salestock.net/api/v2/pokemon/1/",
            "name": "bulbasaur"
        },
       // ....
        {
            "url": "http://pokeapi.salestock.net/api/v2/pokemon/20/",
            "name": "raticate"
        }
    ],
    "next": "http://pokeapi.salestock.net/api/v2/pokemon/?offset=20"
}

nesse caso a função listar deve ser reescrita
listar() {
 this.apiService.listar()
  .subscribe(dados => this.pokemon = dados.results);
}

Answer: Por mais que o subscribe, seja uma espécie de retorno do seu Listar(), recomendo que nesse contexto não use o subscribe e sim diretamente o Observable com o pipe Async.
pokemon$: Observable<any>;

No seu método Listar, use:
listar() {
    this.pokemon$ = this.apiService.listar()
  }

No DOM, faça:

  {{p.url}}  {{p.name}}

É uma melhor prática.
Answer: O problema ocorre porque a variável pokemon é undefined durante a renderização do seu template. Repare que apesar de você acionar sua API para preencher esta variável, a conclusão da requisição leva um certo tempo. Antes de concluir a requisição, o template já foi renderizado e gerou o problema porque a variável ainda é undefined. Veja que é um processo assíncrono.
Para resolver o problema apenas inicialize sua variável ou aplique um *ngIf para verificar se a variável pokemon já foi preenchida:
// Inicialize sua variável com um Array vazio
pokemon = [];

ou:

        {{p.url}}  {{p.name}}

Erro ao Consumir api no angular


Why is jasmine unable to find my unit tests?

Question: my folder structure looks like this
folder structure
my jasmine.json file
{
    "spec_dir": "dist/tests",
    "spec_files": ["**/*[sS]pec.js"],
    "helpers": ["helpers/**/*.js"],
    "stopSpecOnExpectationFailure": false,
    "random": false
}

if i make a simple unit test
on index.ts
const myFunc = (num: number): number => {
  return num * num;
};

export default myFunc;

and on indexSpec.ts
import myFunc from '../index';

it('expect myFunc(5) to equal 25', () => {
  expect(myFunc(5)).toEqual(25);
});

i get this output

No specs found
Finished in 0.007 seconds
Incomplete: No specs found
Answer: That's because you specify that you want to test files with the .js extension but you are coding in a .ts
Comment: i've tried changing it to .ts and change the "spec_dir" in the json file to be "src/tests" but i get another error: SyntaxError: Cannot use import statement outside a module
Comment: I guess the new error is from your package.json or tsconfig, with the modification does your package .json have this field:     type: "module", ? Elle see on stack overflow this error (import outside of module) is an Roger topic with a lot of solutions
Comment: thank you it was as you said type : module in my package.json i changed this and modified the spec_dir so it points to the right directory (the build directory where files compile to js files instead of typescript) and it worked


Using drush @self alias returns nothing

Question: According to the documentation for drush (version 5.9) it has a built in alias called @self.
When I attempt to use the @self alias in a command such as:
drush site-alias @self

Nothing is returned. However, using aliases I've defined in my aliases.drushrc.php the commands work as expected.
Does anyone have any ideas as to what might be going on?
Answer: In order to use the @self alias, Drush must be able to detect and bootstrap your Drupal site based on the current working directory.  If your settings.php file is in the 'default' directory, then you may cd to your Drupal root directory, or any directory below it, and @self will work.  If your settings.php is in some other directory, then you must either cd to the directory that the settings.php file is in, or provide a --uri option to Drush.
You can also use @self without changing your working directory if you supply --root and --uri options to Drush.

Using drush @self alias returns nothing


Como guardar o valor dos índices desse JSON em variável?

Question: Eu tenho uma função no php que me retorna isso.
[{"id":81,"username":"usuarioteste23"}]

Como consigo salvar em uma variável esse ID e em outra variável esse Username?
Obrigado.
Comment: Isso tudo é uma string (json), não é?
Answer: Solução
Faça assim:
$dados = json_decode('[{"id":81,"username":"usuarioteste23"}]', true);

$id = $dados[0]['id'];

$username = $dados[0]['username'];

Explicação
O que sua função retorna é uma string php, contendo dados serializados em formato JSON.
O JSON é utilizado para você fazer intercâmbio de dados computacionais. Ele utiliza a notação de objetos do javascript (não é necessário javascript para lê-lo). Você pode lê-lo com facilidade em várias liguagens, como PHP, java ou python.
No PHP, a função que decodifica dados serializados em JSON é json_decode. Ela vai transformar um conjunto de dados de JSON para PHP (array, object, int, etc...).
No exemplo, eu etilizei $dados[0] porque seu json possui um objeto dentro de um array. Então, precisamos pegar o índice 0 para capturar o primeiro (e único) valor desse array, que por sua vez contém um objeto com as propriedades id e username.
Para ficar mais fácil de entender (tendo em vista que você sabe que o JSON é um tipo de notação semelhante aos tipos do javascript).
O array no json é repesentado por [].
O objeto no json é representado por {}
O returno de json_decode resultaria na seguinte declaração, se fosse feita em php.
$dados = array();

// Object converte para stdClass

$dados[0] = (object)array('id' => 81, 'username' => 'usuarioteste23');

Como pode perceber, usei um segundo argumento passado para o json_decode, que é o valor true, que serve para definir se vamos decodificar o json paraarrayoustdClass. Nesse caso trabalhei usando umarray`.
O retorno desse json_decode com o segundo argumento sendo true, seria algo parecido com essa declaração:
 $dados = array();

// Sem conversão para stdClass, usei um array simples

$dados[0] = array('id' => 81, 'username' => 'usuarioteste23');

Answer: Embora a resposta tenha já sido dada - e escolhida - eu acho válido postar outra solução que é bem elegante e que a linguagem traz nativamente (parece até ter sido construído para o seu caso):
$json = '[{"id":81,"username":"usuarioteste23"}]';
# agora você tem $id e $username
extract(array_pop(json_decode($json, true)));

Informações adicionais:
O código acima não é incorreto (como dito por alguém no comentário abaixo), mas ele gerará um WARNING (não erro) se Strict Standards está habilitado:
PHP Strict Standards:  Only variables should be passed by reference

Isso ocorre pois, por padrão, PHP tenta passar o argumento de array_pop|array_shift por referência e, neste caso, deveria ser uma varíavel, não um array construct.

Nota:
  Não há qualquer relação com má prática ou má ideia -  ao menos nesse
  caso - em usar a função built-in extract(), visto que o que se quer
  obter é uma variável $id e outra chamada $username. Se você
  estiver receoso quanto a colisão de nomes de variáveis, você mesmo até
  passar um prefixo para o terceiro parâmetro de extract().   O uso
  de extract() é popularmente usado em frameworks (como Laravel) e
  template engines.

Tendo dito isso, o código deveria ser melhor escrito dessa forma:
<?php

$data = json_decode('[{"id":81,"username":"usuarioteste23"}]', true);

extract(array_pop($data));

Comment: -1 Não estou comentando quando dou negativo, mas dessa vez vou abrir exceção. Array_pop só aceita variáveis (pois o argumento espera uma referência). Esse código geraria um erro. Além do que `extract` é uma péssima ideia, se o json retornar outros nomes que poderiam se transformar em variáveis inexperadas.
Comment: Não entendi pq tantos votos negativos, o warning é fácil de corrigir. +1
Comment: Os votos negativos me pareceram justos sim, mas eu discordo mais é de ficar comentando eles dentro da resposta. A resposta deve ser e unicamente sobre o problema da dúvida. Apenas deve corrigir o problema do código e usar o campo de comentários ou META. Participe do META, leia o que já foi debatido lá, aprenda como funciona a comunidade. Não interprete mal os downvotes eles não são arbitrários (apesar de existir vezes que tem pessoas que o usam de maneira errada). Vou editar a resposta é deixar apenas o que é interessante. Se sentir que precisa discutir isto vá para o META.
Comment: @WallaceMaxters não disse para deixar o código em uma linha e deixar o warning de boa, se tem algum deve ser tratado. Tem muita coisa no php que não tem razão ou não é coerente vide => http://pt.stackoverflow.com/q/24992/91 , acho engraçado isso, a documentação diz que algumas funções é obrigatório passar uma referência mas para algumas só gera o warning e funciona .... meio bizarro. Não estou falando para não tratar o warning :)
Comment: Considerarei tirar o negativo se você melhorar sua resposta. Por exemplo, pode-se adicionar o exemplo que no php5.4 você poderia fazer isso : `json_decode($json, true)[0]`.
Comment: Agora sobre a sua ultima edição, ninguem disse que `extract` é o problema em absoluto, talvez não tenha sido claro, mas o problema é sobrescrever variáveis existentes, talvez um closure resolvesse, faltou a explicação do porque usar `array_pop`. Você se prendeu em justificar o que é certo e errado, mas não explicou o código em si. Explique o que `array_pop` vai fazer de diferença, eu não sei quem deu os downvotes, mas é bem provavel que retirem ;) - fico aguardando.
Comment: Simplesmente use `current` no lugar de `array_pop` e eu tiro o negativo. E @rray,  talvez dependa da versão do php. Esse Warning não é lançado lá a toa, e talvez em alguma versão pode "evoluir" para um outro erro.
Comment: @WallaceMaxters sobre o "evoluir" que você falou, é interessante notar que alguns usam parenteses nessas funções(acho que a mais comum é o `explode()`) para não gerar o warning, porém no php7 mesmo com esses parenteses adicionais ocorre o warning, [documentação](http://php.net/manual/en/migration70.incompatible.php#migration70.incompatible.variable-handling.parentheses)


Players at certain position are all injured, what happens?

Question: What happens if all or the basic amount of necessary players on a NFL team are injured in the same game and cannot return to play? Do they take some other players that are able to play such necessary positions?
For instance, on the 2015-2016 roster of the New England Patriots, there are two quarterbacks, Brady and Garapollo. If both are injured is it possible that they can be replaced by Edelman, an ex-college quaterback turned wide receiver?
Answer: To a large extent, "positions" aren't defined in the NFL - there's nothing that says that only "a quarterback" can do stuff which a quarterback normally does. If the Patriots wanted Edelman to throw a pass, they can do that, whether that be for one play or the rest of the game. They could equally do this with a running back, a cornerback or any other player, and they can do it no matter if the "regular" quarterbacks are injured or not.
The only slight complication here is that players are assigned numbers based on their position, and certain numbers (50-79) are reserved for offensive linemen who are not eligible to catch a pass. However, any ineligible player can make themselves "eligible" for one play by reporting to the referee, so if a team really wanted to put an offensive lineman in at quarterback, they'd simply have to report in before every play (the quarterback is an eligible receiver, even if they're not normally going to catch a pass).


Take 2 digit after comma sql

Question: So, i have column with data type float. i want to take 2 digit after comma
example
0.622
i want the result is
0.62
i already tried some solution from stack overflow but still the result is 0.61.
sum(CASE WHEN a.TOTALBUDGET>bo.Bobot*2 then bo.Bobot*2 else  a.totalbudget end) as UW_Rank
sum(CASE WHEN a.TOTALBUDGET>bo.Bobot*2 then bo.Bobot*2 else  CAST(ROUND(a.totalbudget,2,1)AS NUMERIC(18,2)) end) as UW_Rank_Test

thanks
Comment: please edit your question and include the actual query that you have tried. Include any relevant samples data as well
Comment: How about some sample data ? Best is to create a [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example)
Comment: While asking a question, you need to provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example):
(1) DDL and sample data population, i.e. CREATE table(s) plus INSERT T-SQL statements.
(2) What you need to do, i.e. logic and your code attempt implementation of it in T-SQL.
(3) Desired output, based on the sample data in the #1 above.
(4) Your SQL Server version (SELECT @@version;).
All within the question, no images.
Comment: What you **see** is an artifact of the tool you use to display your resultset and the datatype of the column in question. Rounding can only be part of any solution - it is your tool that is responsible for the display. If you must do this in the query, you will need to also change the datatype as desired using CAST or CONVERT
Comment: please show the tried solution
Comment: https://stackoverflow.com/questions/20119282/how-to-display-two-digits-after-decimal-point-in-sql-server from here, and i have to sum first then take the 2 digit after comma
Comment: problem solved, it must be round first and then sum. thanks all for the advice really appreaciate
Answer: Did you tried round function.
declare @val float = '0.622'
SELECT ROUND(@val, 2);

Take 2 digit after comma sql


How to prove the double inequality

Question: Show that
$$\frac{-1}{x+1} \leq \int_{x}^{x+1} \frac{\sin{t}}{t} \, dt \leq \frac{1}{x}$$
Note that $\forall x >0$
Answer: Hints:

$-1 \le \sin t \le 1$ for all $t$
$\dfrac{1}{x+1} \le \dfrac 1t \le \dfrac 1x$ for all $t \in [x,x+1]$.
$\displaystyle \int_{x}^{x+1} \, dt = 1$.

How to prove the double inequality


regexes for parsing formatted numbers

Question: I am parsing documents which contain large amounts of formatted numbers, an example being:
 Frc consts  --     1.4362                 1.4362                 5.4100
 IR Inten    --     0.0000                 0.0000                 0.0000
 Atom AN      X      Y      Z        X      Y      Z        X      Y      Z
    1   6     0.00   0.00   0.00     0.00   0.00   0.00     0.00   0.00   0.00
    2   1     0.40  -0.20   0.23    -0.30  -0.18   0.36     0.06   0.42   0.26

These are separated lines all with a significant leading space and there may or may not be significant trailing whitespace). They consist of 72,72, 78, 78, and 78 characters. I can deduce the boundaries between fields. These are describable (using fortran format (nx = nspaces, an = n alphanum, in = integer in n columns, fm.n = float of m characters with n places after the decimal point) by:
 (1x,a14,1x,f10.4,13x,f10.4,13x,f10.4)
 (1x,a14,1x,f10.4,13x,f10.4,13x,f10.4)
 (1x,a4,a4,3(2x,3a7))
 (1x,2i4,3(2x,3f7.2))
 (1x,2i4,3(2x,3f7.2))

I have potentially several thousand different formats (which I can autogenerate or farm out) and am describing them by regular expressions describing the components. Thus if regf10_4 represents a regex for any string satisfying the f10.4 constraint I can create a regex of the form:
COMMENTS
      (\s
      .{14}
      \s
      regf10_4,
      \s{13}
      regf10_4,
      \s{13}
      regf10_4,
)

I would like to know whether there are regexes that satisfy re-use in this way. There is a wide variety in the way computers and humans create numbers that are compatible with, say f10.4. I believe the following are all legal input and/or output for fortran (I do not require suffixes of the form f or d as in 12.4f) [the formatting in SO should be read as no leading spaces for the first, one for the second, etc.]
-1234.5678
 1234.5678
            // missing number
 12345678.
 1.
 1.0000000
    1.0000
        1.
 0.
        0.
     .1234
    -.1234
    1E2
    1.E2
    1.E02
  -1.0E-02
**********  // number over/underflow

They have to be robust against the content of the neighbouring fields (e.g. only examine precisely 10 characters in a precise position. Thus the following are legal for (a1,f5.2,a1):
a-1.23b   // -1.23
- 1.23.   // 1.23
3 1.23-   // 1.23

I am using Java so need regex constructs compatible with Java 1.6 (e.g. not perl extensions)
Comment: +1 for trying to be as complete as possible but I fear by being this complete, you might have **obscured** what you are really after. I for one could construct a regex to get the number out of your provided examples but with all the fortran *stuff*, I doubt it would be what you want. What if you would just throw us a bunch of strings and what you'd expect as a result?
Comment: Thanks. I want to (a) test the line as containing the components I want and (b) extract the fields which I then parse using Java e.g.
parseDouble(group(i).trim())
and catch exceptions. The asterisks are dealt with as a special case
Comment: Will you have a format spec like `(1x,a4,a4,3(2x,3a7))
` for each line in advance?  Or do you have to deduce that as part of the parsing task?
Comment: I have all the formats required but do not know when they change from one to another (I have a framework for managing that). [I am also working on deducing the formats but I am using different methods for that such as dynamic programming]. Although in principle I could extract the fields and try tp parse them there are other fields (with more text) where regexes are the simplest way to do it
Answer: As I understand it, each line comprises one or more fixed-width fields, which may contain labels, spaces, or data of different kinds.  If you know the widths and types of the fields, extracting their data is a simple matter of substring(), trim() and (optionally) Whatever.parseWhatever().  Regexes can't make that job any easier--in fact, all they can do is make it a lot harder.
Scanner doesn't really help, either.  True, it has predefined regexes for various value types, and it does the conversions for you, but it still needs to be told which type to look for each time, and it needs the fields to be separated by a delimiter it can recognize.  Fixed-width data doesn't require delimiters, by definition.  You might be able to fake the delimiters by doing a lookahead for however many characters should be left in the line, but that's just another way of making the job harder than it needs to be.
It sounds like performance is going to be a major concern; even if you could make a regex solution work, it would probably be too slow.  Not because regexes are inherently slow, but because of the contortions you would have to go through to make them fit the problem.  I suggest you forget about regexes for this job.
Comment: +1 Given the *answering own question* below, I believe this set the OP on the right track.
Comment: Thank you. I agree that this is probably the best approach for the problem as stated. Unfortunately the more general problem is that there are some outputs which use whitespace separation instead of formatting and I was looking for a general solution. [Did you have ideas on the automatic extraction of formatting from a corpus of documents from the same source?]
Comment: I'd be looking for a flat-file parsing library if I were you, although there don't seem to be many of those out there (for Java, anyway).  But if you have to create your solution from scratch, don't base it on regexes.  As for the automatic extraction of formatting... maybe in Perl. :-/
Answer: You could start with this and go from there.
This regex matches all the numbers you've provided.
Unfortunatly, it also matches the 3 in 3 1.23-
// [-+]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][-+]?[0-9]+)?
//
// Match a single character present in the list "-+" «[-+]?»
//    Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
// Match the regular expression below «(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)»
//    Match either the regular expression below (attempting the next alternative only if this one fails) «[0-9]+(?:\.[0-9]*)?»
//       Match a single character in the range between "0" and "9" «[0-9]+»
//          Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
//       Match the regular expression below «(?:\.[0-9]*)?»
//          Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
//          Match the character "." literally «\.»
//          Match a single character in the range between "0" and "9" «[0-9]*»
//             Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
//    Or match regular expression number 2 below (the entire group fails if this one fails to match) «\.[0-9]+»
//       Match the character "." literally «\.»
//       Match a single character in the range between "0" and "9" «[0-9]+»
//          Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
// Match the regular expression below «(?:[eE][-+]?[0-9]+)?»
//    Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
//    Match a single character present in the list "eE" «[eE]»
//    Match a single character present in the list "-+" «[-+]?»
//       Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
//    Match a single character in the range between "0" and "9" «[0-9]+»
//       Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Pattern regex = Pattern.compile("[-+]?(?:[0-9]+(?:\\.[0-9]*)?|\\.[0-9]+)(?:[eE][-+]?[0-9]+)?");
Matcher matcher = regex.matcher(document);
while (matcher.find()) {
    // matched text: matcher.group()
    // match start: matcher.start()
    // match end: matcher.end()
}

Comment: Thank you - this is useful annotation of regex constructs. Unfortunately SO has truncated some of your code
Answer: It is only a partial answer but I was alerted to Scanner in Java 1.5 which can scan text and interpret numbers which gives a BNF for the numbers that can be scanned and interpreted by this Java utility. In principle I imagine the BNF could be used to construct a regex.

regexes for parsing formatted numbers


ItemUpdated List Item Comparison

Question: Is it possible to compare the properties listItemId with a field in a new list? I have an event receiver, I want to update a new list once an item in updated. I don't want to use GetItemById, I want to compare the first list auto generated ID with a field in the new list.

foreach(ListItem UpdateItem in destListItems) {
  if (properties.ListItem["ID"] == UpdateItem["NewId"]); {
    //Do something
  }
}

The script does not update the item in the destination list. Any suggestions?
Answer: Try this:
if (properties.ListItem["ID"].ToString() == UpdateItem["NewId"].ToString()); {
    UpdateItem["Field"]="123";
    UpdateItem.Update();
}

ItemUpdated List Item Comparison


What does it mean when I see a chord named Em7/5+

Question: Em7/5+      I know Em7 is a minor 7th chord, but what does the /5+ mean?  I thought that the slash would be followed by a root note other than the E, but I do not know what the 5+ indicates following the slash.  Thanks.
Comment: Welcome to the site Rick. Please check and see if the question above answers your question as it is almost the same.
Comment: Yes, thanks, that helps.  It seems there are many different ways of saying the same thing in musical notation, most of which has nothing to do with what I was taught in school.
Answer: This isn't standard notation.  But we can try to work out what someone might have meant by it.  Maybe the slash is an error, they just mean Em7+5.  That's Em7 with a raised 5th.  E, G, B# (Ok, call it C) D. Maybe they want the raised 5th to be the bass note, though it's hard to see why this wouldn't be written as C(add9).  What comes before and after it?  Are we doing the James Bond riff: Em, Em+, Em6, Em+ ? (Sounds a bit odd with the 7th in there though.)
The lesson here is that someone has either tried to be clever, or has been sloppy, and no-one knows what he means.  So don't do that!
Comment: @Rick: In this case it's a [line cliché](http://music.stackexchange.com/questions/24285/name-for-descending-semitones-under-a-repeating-musical-phrase/24295#24295) (referred to as James Bond riff in Laurence's answer).
Comment: It comes from "Cry Me A River" by Arthur Hamilton, from both the Susan Boyle and Julie London versions. I have seen in it a number of places, one is at http://www.pgmusic.com/forums/ubbthreads.php?ubb=showthreaded&Number=222358&site_id=1 Thank you.  I think I understand now, but it is sure confusing.  :(
Comment: Thank you.  I thought I knew quite a bit about music theory, but it appears that I have only scratched the surface just enough to reveal a whole other world.


Placing constraints on linear model coefficients

Question: I have this bit of data :
Y <- c(40.2304958024139,53.6587545658805,39.6709850206028,
       45.5769321619423, 54.2182653476916, 40.0439922084769)

X <- c(43, 50, 41.5, 48, 52, 42)

and want to get the average transformation from $X$ to $Y$. My obvious choice was a simple lm in R to get the coefficients and be on my merry way.
However, this is what pops out of the lm function:
> summary(lm(Y~X))

Call:
lm(formula = Y ~ X)

Residuals:
       1        2        3        4        5        6
-0.79894  2.32880  0.84880 -2.81002 -0.05469  0.48606

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  -22.245      8.881  -2.505  0.06643 .
X              1.472      0.192   7.666  0.00156 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 1.931 on 4 degrees of freedom
Multiple R-squared:  0.9363,    Adjusted R-squared:  0.9203
F-statistic: 58.76 on 1 and 4 DF,  p-value: 0.001557

Now, I'm aware these are probably the best parameters for this data, but since the whole aim of getting that transformation in the first place is to apply it to a set of larger $X$s, subtracting $22$ and then multiplying by $1.5$ will certainly not scale.
Is there a way I can constrain the parameters such that I get a reasonable intercept and slope ?
This data is reasonably close to $Y=X$, so I was expecting a slope nearer to $1$ and intercept closer to $0$.
Comment: You really need to tell us more about your data. At this moment you seem to be telling us that linear regression doesn't work for your data because linear model is not suitable for your data. It is unclear what is "ridiculous" about this intercept and what kind of intercept wouldn't be "ridiculous".
Comment: Ah, sorry. I mean that since this data is already very close to $Y=X$, having such parameters clearly seems wrong ! I'll edit my question.
Comment: Would a Bayesian approach, w/ a strong prior on $0$ & $1$, be acceptable?
Comment: Well, probably but it seems like way overkill for this...
Answer: Have you tried plotting this data?

If there was $Y=X$ relation, we would expect to see points lying along the line. I plotted your data with the $\beta_0=0$ and $\beta_1=1$ regression parameters, and as you can see, neither of the points lies on the line. You could try drawing several different lines, or curves, that would fit those points better. Even if there is strong linear relation between the points, then you have not enough data to predict it.
If you have some prior knowledge that suggests that the parameters should be close to $\beta_0=0$ and $\beta_1=1$, then this sounds like a clear case for using Bayesian linear regression.
Comment: Yes, I've actually been staring at that exact plot for the past half hour ! Thank you for the tip, I'll look into the Bayesian linear regression.


Sustain pedal information in recorded Midi?

Question: I realize this is a pretty model-specific question, but Reddit has amazed me before with its answers.
I have an old Yamaha DGX-620, that I'm using to do some composing. I've been using the song recording feature, and I'm able to save my songs as MIDI files to a USB drive. However, the sustain pedal completely ignored in the MIDI file: the song plays as if I hadn't used the pedal at all, with some notes much too short. Note that everything sounds fine when I play the songs back on the keyboard, it's just on the MIDI that it's missing.
I'm wondering, is there a setting I can change so that the sustain pedal information is included in the MIDI? Perhaps using the pedal to alter the note lengths, instead of storing it as separate information that doesn't end up in the MIDI?
Answer: After importing into Rosegarden, it revealed that the pedal information was, in fact, stored in the Midi, so the problem was the program I was using to play it (in this case, LMMS).


hook_node_info or node_type_save?

Question: I've created a custom module that creates 2 content types in it's .install file (with node_type_save). This works fine, but now i have trouble implanting the hook_xxxx system. As the content types are already defined there is little need hook_node_info to define them again in the .module file, and even if i wanted to this will not work.
Now i can get around this by using hook_node_xxxx but i wonder if this is the right approach. It seems a bit dodgy to use the general hooks in a module which just defined those hooks.
Here is the code:
<?php

/**
 * Implements hook_install().
 */
function vakantie_install() {

    $t = get_t();
    $content_types = array(
        'name1' => 'vakantie_blok',
        'name2' => 'vakantie_pagina',
    );

    $types = array(
        array(
            'type' => $content_types['name1'],
            'name' => $t('Vakantie Blok'),
            'base' => 'node_content',
            'description' => $t('Maak een Vakantie Blok item.'),
            'custom' => 0,
            'modified' => 1,
            'locked' => 0,
        ),
        array(
            'type' => $content_types['name2'],
            'name' => $t('Vakantie Pagina'),
            'base' => 'node_content',
            'description' => $t('Maak een Vakantie Pagina item.'),
            'custom' => 0,
            'modified' => 1,
            'locked' => 0,
        ),
    );

    foreach ($types as $type) {
        $type = node_type_set_defaults($type);
        node_type_save($type);
        node_add_body_field($type, $t('Inhoud'));
    }

    foreach ($content_types as $type) {
        // add persistent variables that control settings
        variable_set('additional_settings__active_tab_' . $type, 'edit-menu');
        // 0 = disabled, 1 = optional, 2 = required
        variable_set('node_preview_' . $type, 1);
        // array(0 => 'status', 1 => 'promote', 2 => 'sticky', 3 => 'revision') remove to uncheck
        variable_set('node_options_' . $type, array());
        // 1 = Display author and date information, 0 = none
        variable_set('node_submitted_' . $type, 0);
        variable_set('menu_options_' . $type, array());
        variable_set('menu_parent_' . $type, 'main-menu:0');
    }
}

/**
 * Implements hook_uninstall().
 */
function vakantie_uninstall() {

    $content_types = array(
        'name1' => 'vakantie_blok',
        'name2' => 'vakantie_pagina',
    );

    // gather all job nodes created and delete them
    $sql = 'SELECT nid FROM {node} n WHERE n.type = :type1 OR n.type = :type2';
    $result = db_query($sql, array(':type1' => $content_types['name1'], ':type2' => $content_types['name2']));
    $nids = array();
    foreach ($result as $row) {
        $nids[] = $row->nid;
    }
    node_delete_multiple($nids);

    // remove persistant variables that control settings
    foreach ($content_types as $type) {
        variable_del('additional_settings__active_tab_' . $type);
        variable_del('node_preview_' . $type);
        variable_del('node_options_' . $type);
        variable_del('node_submitted_' . $type);
        variable_del('menu_options_' . $type);
        variable_del('menu_parent_' . $type);
    }

    // delete our content type
    node_type_delete($content_types['name1']);
    node_type_delete($content_types['name2']);
}

Here the .module:
<?php

function vakantie_node_view($node, $view_mode, $langcode) {
    if($node->type == 'vakantie_blok') {

        $extra_field = 'test_extra';

        $node->content['test'] = array(
            '#markup' => $extra_field,
            '#weight' => 1,
        );

        $node->content['test2'] = array(
            '#markup' => $extra_field,
            '#weight' => -1,
        );
    }
}

Answer: I would suggest doing as a Drupal module does: the Blog module. That is the correct code to use for a module that defines its own content type.

In the installation file, the code the Blog module uses is the following.
function blog_install() {
  // Ensure the blog node type is available.
  node_types_rebuild();
  $types = node_type_get_types();
  node_add_body_field($types['blog']);
}

In the module file, it implements the content type hooks, which are:

hook_form()
hook_node_info()
hook_view()

Another Drupal core module that implements its own content type is the Forum module. Differently from the Blog module, the Forum module adds a field to the nodes of its content type. The code it uses to set its content type is similar, though. (See forum_enable().)
  // Ensure the forum node type is available.
  node_types_rebuild();
  $types = node_type_get_types();
  node_add_body_field($types['forum']);

Notice that Drupal core modules don't remove the content type they define, when they are uninstalled; eventually, they remove any field they attached to their content type. (See forum_uninstall().)
As side note, the string passed to t() contains English words, not in other languages.
Comment: Thanks for the info, i'll rebuild it to use hook_node_info.

Still i wonder why node_type_save exists though, seemed like a nice solution since it only gets loaded during module install.
Comment: `node_type_save()` is normally used from the installation profile to install its default content types, which is what [standard_install()](http://api.drupal.org/api/drupal/profiles%21standard%21standard.install/function/standard_install/7) does. It is also used from [node_type_form_submit()](http://api.drupal.org/api/drupal/modules%21node%21content_types.inc/function/node_type_form_submit/7), but never from a module defining a content type.

hook_node_info or node_type_save?


TypeError when mocking request with jest

Question: I'm relatively new to node and am having issues trying to mock request using jest.
If my file to be tested has require('request'), and I try to run npm test, I get this error:
FAIL  __tests__/sum-test.js (0.291s)
● sum › it adds 1 + 2 to equal 3
  - TypeError: The super constructor to `inherits` must have a prototype.
        at Object.exports.inherits (util.js:756:11)
        at Object.<anonymous> (node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/private-key.js:44:6)
        at Object.<anonymous> (node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/utils.js:16:18)

Here's my package.json, if that helps:
{
  "name": "jesttest",
  "version": "1.0.0",
  "scripts": {
    "test": "jest"
  },
  "devDependencies": {
    "jest-cli": "^12.0.2"
  },
  "dependencies": {
    "request": "^2.72.0"
  }
}

Anyone know why this might be happening?
Answer: add jest.unmock('request') in your test file.
Jest will mock a fake require object when you require something in your file.In this situation, request is not the real request.So tell jext not mock request.
Comment: This worked for me. @Manu if this worked for you, please accept this as the answer.


Calculating Confidence Intervals when proportion is skewed

Question: I have 15,000 address strings which I have written a piece of code which assigns them to broad geographic region e.g. American address assigned to North America. I would like to check the accuracy of my code. However I must manually check the strings. To do this I've taken a sample (SRS). I set a margin of error of 5%, a CI of 95% and a response distribution of 50%. Therefore, I assumed that I would assign the correct region half the time.
The issue here is that I am much more accurate then I anticipated. Of my sample of 375,372 (99%) were assigned to the correct location. This means I am unable to calculate lower and upper confidence limits.
Is there any other types of formula I could use when your response distribution is skewed to a highly positive outcome? Or is the only remedy to simply increase my sample size?
Comment: I think you will find this question has been answered here before. For instance this answer https://stats.stackexchange.com/questions/82720/confidence-interval-around-binomial-estimate-of-0-or-1/82724#82724
Comment: You absolutely *can* get confidence limits (using normal approximation) when the sample proportion is very high. It's just not good. I think you are improperly standardizing the result of your manually checked sample: summarize uncertainty in that one using exact binomial intervals.
Answer: A quick answer based on the links (and corresponding references) in Comments: Use a Bayesian
probability interval (based on a uniform prior) to serve as a frequentist confidence interval (CI).
If you have $X = 3$ successes in $n = 275$ trials, then your 95% CI
can be found in R as qbeta(c(.025, .975), x + 1, n - x + 1):
x = 3;  n = 275
qbeta(c(.025,.975), x+1, n-x+1)
[1] 0.003962534 0.031435106

So you might use $(0.004,\,0.031)$ as your 95% CI.
Notes: (a) The Jeffrey's interval mentioned in references
uses 0.5 where I have used 1. That is
 x = 3;  n = 275
 qbeta(c(.025,.975), x+.5, n-x+.5)
 [1] 0.003081784 0.028823996

Most of the time, the two intervals are almost the same.
In my experience, using the uniform prior instead of the Jeffreys prior
happens to give slightly more consistent coverage probabilities in some cases of proportions very near 0 or 1. Plots of coverage probabilities for $n = 275$ are shown below:

(b) If you're using software other than R, qbeta is the an
inverse CDF function (quantile function) for a beta random variable.
Most commercial programs can be used to get the same result (even if not as compactly as R). For example, using Minitab we get:
MTB > invcdf .025;
SUBC> beta 4 273.

Inverse Cumulative Distribution Function
Beta with first shape parameter = 4 and second = 273
P( X ≤ x )          x
     0.025  0.0039625

MTB > invcdf .975;
SUBC> beta 4 273.

Inverse Cumulative Distribution Function
Beta with first shape parameter = 4 and second = 273
P( X ≤ x )          x
     0.975  0.0314351


Qual plugin jquery permite selecionar dias e eventos de cada dia em uma timeline horizontal?

Question: Eu tenho eventos que guardo no banco de dados e quero criar uma timeline que mostre os eventos do dia por ordem de acontecimento e permita o usuário avançar ou retroceder o dia e selecionar os eventos. Conforme ele seleciona um evento, coisas diferentes são mostradas na tela.
Eu fiz um esboço de exemplo, é relativamente simples, mas na internet, pelo menos até agora, só encontrei timelines com outras funcionalidades. Talvez timeline não seja o melhor termo para descrever, mas não consigo um melhor agora.
Segue o esboço:
Quando o usuário clicar na seta à esquerda (<), diminui o dia e são carregados os eventos do dia anterior ao que estava (no caso, 20/03/2014). Ao clicar na seta à direita (>), avança o dia e carrega-se os eventos do dia posterior (no caso, 22/03/2014). Quando o usuário clica em um evento, seleciona ele e mostra coisas sobre ele na tela, além do evento mudar de cor na timeline.
Se não houver algum plugin na internet, por onde posso começar a estudar para desenvolver isto? Alguma sugestão?
Comment: Você irá achar algo se procurar por Calendário jQuery ou Scheduler.
Answer: Acredito que a solução está mesmo em usar algum plugin. Acho que uma variante de lightbox pode resolver bem o seu problema.
Em todo caso, se você quiser implementar a solução, montei um código bem básico que pode servir de base para você.
Implementei no jsFiddle, aqui: http://jsfiddle.net/2Sthd/5/
Basicamente, se você clicar em "anterior" ou "próximo", é disparado um evento que move o "menu". Ao clicar em um dos eventos, a "caixinha" atual é escondida, e uma outra é mostrada, correspondente ao novo item.
HTML:

    Anterior

Evento 1

Evento 2

Evento 3

Evento 4

Evento 5

Evento 6

Evento 7

Evento 8

    Próximo

            Evento 1

            Blabla bla bla

            Evento 2

            Bleble ble

            Evento 3

            Bli bli bli

            Evento 4

            Blobblo blo

            Evento 5

            Blobblo blo

            Evento 6

            Blobblo blo

            Evento 7

            Blobblo blo

            Evento 8

            Blobblo blo

CSS:
.event {
    width: 200px;
    height: 100px;
    background-color: gray;
    margin: 5px;
}

.event-list {
    list-style: none;
    margin: 0;
    padding: 0;
    width: 800px;
    margin-left: 0;
}

.event-list-container {
    width: 210px;
    overflow: hidden;
    background-color: yellow;
    height: 20px;
}

.event-list-item {
    margin-left: 5px;
    margin-right: 5px;
    cursor: pointer;
    width: 60px;
    float: left;
    display: block;
    background-color: gray;
    text-align: center;
}

.event-arrow {
    color: blue;
    cursor: pointer;
}

.event-selected {
    text-decoration: underline;
    color: green;
}

.event {
    display: none;
}

.event-current {
    display: block;
}

.event-title {
    font-size: 26px;
    font-weight: strong;
    margin-bottom: 5px;
    background-color: black;
    color: gray;
}

Javascript (com jQuery):
function showCurrentEvent(eventId) {
    $('.event-current').removeClass('event-current');
    $('.event[data-event-id=' + eventId + ']').addClass('event-current');

}

$(function() {
    $('.event-arrow-prev').on('click', function() {
        $('.event-list').css('margin-left', function (index, curValue) {
            var cur = parseInt(curValue, 10) + 70;

            if (cur < 0) {
                return cur + 'px';
            }
            else {
                return '0px';
            }
        });

        return false;
    });

    $('.event-arrow-next').on('click', function() {
        $('.event-list').css('margin-left', function (index, curValue) {
            var cur = parseInt(curValue, 10) - 70;

            if (cur >= -70*5) {
                return cur + 'px';
            }
            else {
                return (-70*5) + 'px';
            }
        });

        return false;
    });

    $('.event-list-item').on('click', function() {
        var currentEvent = $('.event-selected');
        currentEvent.removeClass('event-selected');

        var newEventId = $(this).data('event-id');

        $('.event-list-item[data-event-id=' + newEventId + ']').addClass('event-selected');

        showCurrentEvent(newEventId);

        return false;
    });
});

Comment: Olá Michael. Obrigado, está perto do que eu preciso. Só que eu gostaria que ao clicar no anterior e próximo, trocasse a lista de eventos e os eventos só pudessem ser selecionados com o clique em cima. Como proceder para essas alterações? O que sugere? Obrigado.
Comment: Oi! Editei a resposta, acho que é isso. Seria bom fazer mais algumas validações (ex: descobrir onde parar o anterior/próximo). Posso fazer isso mais tarde, mas é fácil. Só precisa de um cálculo baseado na quantidade de itens e largura de cada item.
Comment: Pronto, fiz a validação do máximo/mínimo também.
Comment: Michael, acha que consegue postar o código no JS Bin ou no CSS Deck? De qualquer maneira, já me ajudou bastante, obrigado.
Comment: Aqui está: http://jsbin.com/xuqejupo/1/
Answer: Existem diversos Plugins de uma olhada em:
timeline.knightlab.com
codecanyon.net/item/jquery-flat-event-calendar-responsive-timeline/6039142?ref=jqueryrain
codecanyon.net/item/dasky-timeline-slider/5071233?ref=jqueryrain
github.com/ozeetee/jqtimeline
codecanyon.net/item/jquery-tweet-feed-plugin/3485336
juanma-aguero.github.io/fancy-timeline
Ou procure por jquery timeline no google para achar diversos outros


Let X = {3^n | n > 0} and Y = {3n | n > 0}. Prove that X ⊆ Y.

Question: I know this should be a simple question to solve but I am stuck.
3^n = 3n
3 * 3n = 3n
How do I write this out further?
Comment: It looks like $X=Y$
Comment: Presumably you made a mistake.
Comment: What you mean under $3^x=3x$? In real numbers this have $2$ roots. In natural numbers only one $x=1$. Analogue question with second line: it holds only for $n=0$. What you mean?
Comment: As @uniquesolution indicates, it appears that $X=Y$ in the title of the question.  However, the body of the question seems to indicate that $X$ and $Y$ are meant to be different.  Can you please clarify this?  Can you also please provide some context for this question?  Where does it come from?  What are you studying? etc.
Answer: Let $x \in X \implies x = 3^n = 3\cdot 3^{n-1} = 3m \implies x \in Y \implies X \subseteq Y$
Comment: We are discouraging answers to problem statement questions when no effort is shown
Comment: It is not at all clear to me that the question you have answered is the question which was asked.  In the future, please seek clarification from the question author before making assumptions about what the question is.
Comment: Thank you for the answer. For some reason the formatting was lost when I asked the question. Disappointed how petty this community is.


When does the derivative of the logarithm equal the logarithm of the derivative?

Question: Not sure how to show proof of work, but I have several pages of notes on my bathroom floor right now. All I get is horribly complicated nonlinear DEs. Is there a magic substitution that makes differentiation and logarithm commute?
What I'm asking for is solutions to:
$$\dfrac d {dx} \ln( f(x) ) = \ln\left( \dfrac d {dx} f(x) \right )$$
Comment: You can differentiate one more time to get rid of log and obtain non-linear ODE
Comment: If you write it as $y'/y=\ln(y')$, it seems plausible that the $W$ function will be involved if you want to solve for $y'$ (since $y'$ occurs both "free" and "inside the logarithm"). Once you get the ODE on the form $y'=g(y)$, it can be solved (in principle) using separation of variables: $\int \frac{dy}{g(y)} = \int dx$, etc.
Comment: It probably doesn't have a nice solution. Mathematica gives something in terms of an inverse function of something involving the [Lambert $W$ function](https://en.wikipedia.org/wiki/Lambert_W_function).
Comment: Thanks for the edit @bjcolby15
Comment: I think substitution $g(x)=f(x) e^{f(x)}$ makes more sense if Lambert W is present.
Comment: ChatGPT is worse than useless for exact science. It is good enough to produce something that looks coherent, but the actual contents is just idiotic rambling.
Comment: Yes, and in 20 years we will have unlimited fusion power, seriously. What is the metric for "outperform"? The internet is a heap of garbage, most of which you will never see, but a search engine will have this as input. AI promises to, at least, extract some kind of topical information. But it can not reason about it, the current state-of-the-art is word associations (ok, with sentence structure, association of phrases), it is not comprehension and "common-sense checks". So in the end it remains GIGO.
Comment: Thanks! I don't have access to Mathematica, so that's a huge help. Sorry for bothering you guys
Comment: @Vasili You don't need another differentiation to get there, just a substitution. And yes, that one is currently sitting on my bathroom floor. :/
Comment: The Lambert W does make sense to me. I already tried substitutions like g(x) = f(x) ln( f(x) ) and the like
Comment: @Vasili But it's the inverse, remember
Comment: For the record, I did ask Chat GPT and it gave me an answer with 0 information. https://i.imgur.com/xe4UD7u.png
Comment: Again, thanks for the edit! Not sure how to "at" editors, the obvious method was a hard fail the last time. But you know who you are, you absolute legends! :)
Comment: @EmanuelLandeholm  lol you're welcome.
Comment: @LutzLehmann I think we´re fast approaching the point where Chat GPT outperforms Google Search. Still a long ways to go...
Comment: I set the bar pretty low. Google Search has deteriorated in quality the last decade. I mean really deteriorated. And I'd argue that it's not just a case of GIGO. There are big economic incentives for polluting search results. Just my tin foil take.

ChatGPT is not swallowing the web like wholesale. There are filters.
Answer: Introducing the parameter $\tau=f'_x$,
\begin{align}
f=\frac{\tau}{\log(\tau)}\quad\rightarrow\quad \mathrm df=\frac{\mathrm d\tau}{\log(\tau)}-\frac{\mathrm d\tau}{log(\tau)^2}
\end{align}
substituting for $\mathrm df$ we have
\begin{align}
\frac{\mathrm dx}{\mathrm d\tau}=\frac{1}{\tau\log(\tau)}-\frac{1}{\tau\log(\tau)^2}.
\end{align}
upon integration we find a nice parametric solution
\begin{align}
f(\tau)=\frac{\tau}{\log(\tau)},\quad x(\tau)=\log(\log(\tau))+\frac{1}{\log(\tau)}+C.
\end{align}
Comment: I'm going to be accepting this answer partially on faith, because I haven't yet found the time to do my homework.  I guess I wish stackexchange would allow you to outsource accepts. Anyway, thanks!
Answer: Your condition is equivalent to the ODE
$$\frac{y'}{y}=\ln(y')\Rightarrow -\frac{1}{y}=\frac{1}{y'}\ln(\frac{1}{y'})$$
knowing that the Lambert W function obeys
$$W(ae^a)=a\Rightarrow W(\ln(a)e^{\ln(a)})=\ln(a)\Rightarrow W(a\ln(a))=\ln(a) $$
we have
$$W(-\frac{1}{y})=W(\frac{1}{y'}\ln(\frac{1}{y'}))=\ln(\frac{1}{y'})\Rightarrow$$
$$\frac{1}{y'}=\exp(W(-\frac{1}{y}))$$
separating variables we get
$$\int dt=\int \exp(W(-\frac{1}{y}))dy.$$
Note also that $W(x)e^{W(x)}=x$ implies $e^{W(x)}=\frac{x}{W(x)}$, so
$$\int \exp(W(-\frac{1}{y}))dy=\int -\frac{1}{yW(-\frac{1}{y})}dy$$
substituting $W(-\frac{1}{y})=u \Rightarrow -\frac{1}{y}=ue^u \Rightarrow \frac{1}{y^2}dy=(1+u)e^udu$ we get
$$\int -\frac{1}{yW(-\frac{1}{y})}dy=\int -\frac{y}{y^2W(-\frac{1}{y})}dy =
\int \frac{1}{u^2e^u}(1+u)e^udu$$
$$\int \frac{1}{u^2}(1+u)du= \ln(u)-\frac{1}{u}=\ln(|W(-\frac{1}{y})|)-\frac{1}{W(-\frac{1}{y})} $$
so the solution becomes
$$t+C = \ln(|W(-\frac{1}{y})|)-\frac{1}{W(-\frac{1}{y})} $$
Comment: Just before "substituting", $W(1/y)$ should be $W(-1/y)$, and this affects the rest of the computation.
Comment: @HansLundmark you're right, already edited.
Comment: I think you ought to get $x+C = \ln|W(-1/y)|-1/W(-1/y)$. (Plotting this, it seems to agree with what Eli Bartlett's answer gives for $1 < \tau < e$. That answer also produces another branch for $\tau > e$.)
Comment: Thank you both for your valuable feedback!
Comment: After the edit, I kind of want to accept this answer too!
Answer: I know this is a late answer, but I thought it would be nice to see some graphs!
The ODE is
$$
(\ln(y))' = \ln(y')
,
$$
so if we want to stay within the world of real numbers, we need both $y$ and $y'$ to be positive.
We can rewrite the equation as
$$
\frac{y'}{y} = \ln(y')
\iff
y = \frac{y'}{\ln(y')}
.
$$
Consider the function $g(s) = \frac{s}{\ln(s)}$, $s>0$.
The figure below shows its graph, which can be found using simple calculus; it decreases for $1<s<e$ down to the local minimum $g(e)=e$, and then it increases to $\infty$.

This means that the equation $y = g(y') = \frac{y'}{\ln(y')}$ has two positive solutions for $y'$ for each given value of $y \in (e,\infty)$; one solution in the interval $y' \in (1,e)$
and the other one in the interval $y' \in (e,\infty)$.
These two choices give rise to two corresponding ODEs $y'=h_1(y)$ and $y'=h_2(y)$, whose solutions $y(x)$ are both solutions to the original ODE.
One of these solutions has a relatively gentle slope (always between $1$ and $e$) and the other one has a steeper slope
(always greater than $e$), and both lie in the region $y(x)>e$:

Since the ODE is autonomous, any translate of these curves in the $x$ direction is of course also a solution;
this corresponds to different choices of the constant $C$ in the formulas below.
The plot shows the case $C=0$.
The maximal open interval of existence in this case is $x \in (1,\infty)$,
although the two functions $y(x)$ both extend continuously to the interval $x \in [1,\infty)$ with $y(1)=e$ and with the one-sided derivative $y'_+(1)=e$.
The parametric solution formula found by Eli Barlett,
$$
\bigl( x(t), y(t) \bigr) = \left( \ln(\ln(t)) + \frac{1}{\ln t} + C, \frac{t}{\ln t} \right)
,
$$
produces the red curve for $1 < t \le e$
and the blue curve for $t \ge e$.
(Recall that the parameter $t$ was nothing but the slope $y' = \tfrac{dy}{dx} = \tfrac{dy/dt}{dx/dt}$ at the point $(x(t),y(t))$.)
And the implicit solution formula (giving the inverse function $x=x(y)$)
found by Diego Santos,
$$
x =
\ln\bigl| W \bigl( -\tfrac{1}{y} \bigr) \bigr| - \frac{1}{W \bigl( -\tfrac{1}{y} \bigr)}
+ C
,\qquad
y \ge e
,
$$
gives the red curve when $W = W_0$ is the principal branch of the Lambert W-function,
which is increasing and maps the interval $[-1/e,0)$ to the interval $[-1,0)$,
and gives the blue curve when $W = W_{-1}$ is the other real-valued branch,
which is decreasing and maps the interval $[-1/e,0)$ to the interval $(-\infty,-1]$.
Comment: Very illuminating +1
Comment: Thanks for the feedback!


How to calculate statistical significance of a difference between two groups?

Question: I have two groups A and B. Each group involves some number of users. For example, let's imagine that the group A has 2000 unique users on Monday, while the group B has 2002 users on the same day.
For each group I measure the number of clicks that users make on a web site. For example, let's say that the users of group A made (totally) 400 clicks (the same user can make more than one click), while the users of group B made 450 clicks on the same page.
Then for each group I calculate the performance metric (in %) as follows: 100 * number of clicks / unique number of users.
<code>PerfA  PerfB    NumUsersA   NumUsersB
20%    22%      2000        2002
21%    20%      2001        1999
</code>
For each pair of values PerfA and PerfB, I want to calculate the statistical significance of a difference.
Which statistical test should I use?
If the Python/Scala library can be suggested, I would be very happy.
I found some examples of how the statistical significance is measured in Excel, but I am now sure about the statistical test (formula) that it refers to:
<code>=NORM.S.DIST(ABS(PerfA*100-PerfB*100)/ABS(SQRT(((PerfA*100*(100-PerfB*100)/NumUsersA)+(PerfB*100*(100-Perf*100)/NumUsersB)))),1)
</code>
Comment: Is this e.g. 20 users with a bad experience out of 2000? Or is this 20 bad events happening to a total of 2000 users (i.e. potentially more than one event per users)? Depending on this assuming e.g. a binomial or Poisson (or negative binomial) distribution would make more sense. Additionally, were people randomized to groups or did they self-select (or get assigned in some other non-random way - e.g. first 2000 users to log on versus the ones logging on later)? This would also make a huge difference (e.g. propensity scores might be needed).
Comment: @Björn: Many thanks Björn for your valuable feedback. Apparently, I had to be more clear in my question. I will add more details in a couple of minutes.
Comment: @Björn: Please check my update. I tried to be more concrete.
Comment: So one or more clicks per user possible? Random group assignment?
Comment: Do you have individual level click data? If so, you might consider a model predicting whether a user clicked anything/the number of clicks from group variables.
Comment: @RickyB: No, I only have aggregated data.
Comment: @Björn: Yes, one or more clicks per user are possible. Groups are assigned randomly, but only once. So, it means that users will belong to the same groups in different days.
Comment: How many trials did you have?
Answer: One logical approach would be to use a random effects Poisson model with a random user effect (reflecting that potentially results for the same user on different days might be correlated) and a fixed group effect (e.g. 0=group A and 1=group B or the other way around). The random effect could follow a normal distribution on the log-rate scale or a gamma distribution on the rate scale, whichever you can find a package for. A keyword you could google here is GLMM. You would be able to do this, as long as you have the data for each user and not just the overall numbers. If you only have the overall numbers, you might have to assume zero variability across people and use a Poisson model.
If you have a small number of days, you might want to consider a Bayesian approach, while with enough days a frequentist approach should work just fine (and presumably some standard package offers a likelihood ratio test). For the Bayesian approach, there are packages such as PyStan in Python (and similarly rstan in R).


How to alias field names in a Spring Batch Bean?

Question: From the documentation, I see that one can alias an entire Spring bean.
How can one alias the field names of a bean?
I have a CSV file that has column names A1, A2, A3...
The Spring Batch program expects X1, X2, X3...
I want to map A1->X1, A2->X2, A3->X3... without hardcoding.
Is there a way to do this?
Answer: The BeanWrapperFieldSetMapper is based on reflection and uses the Java Beans naming conventions to convert columns in the CSV file to fields in your domain objects. This mapper is a bit smart in some way as it allows fuzzy matching (see its javadoc).
However, if column names in the input file are completely different from field names in your domain object and you want the mapping to be dynamic,  you need to create a custom FieldSetMapper that loads the mapping meta-data from a properties file for example and maps columns to fields dynamically at runtime.
Comment: You first create a file that contains the mapping meta-data (`a1=x1\na2=x2\n...`). Then create a class that implements `FieldSetMapper` that reads that file and maps columns from the `FieldSet` to corresponding fields in your domain object based on the mapping defined in the meta-data file. Once that done, you set your custom implementation on the `FlatFileItemReader`. This allows you to dynamically change the mapping without recompiling your app.
Comment: Here is a sample: https://github.com/spring-projects/spring-batch/blob/main/spring-batch-samples/src/main/java/org/springframework/batch/sample/domain/order/internal/mapper/CustomerFieldSetMapper.java. You just need to add the dynamism of loading the mapping meta-data from an external file.
Comment: How would I specify "FieldSetMapper that loads the mapping meta-data from a properties file". Would the `FieldSetMapper` have its fields `autowired`?


Disable pre-populated fields in webform

Question: I have form created with Webform module, some fields are enabled for pre-population, so in some cases I use URL parameters to pre-populate them.
The thing is that I need to forbid users to change pre-populated fields (ether to disable them, or to hide them).
I checked field conditions in Webform configuration, but there's no option for this.
How it's possible to resolve this?
Comment: A person could change the query string so no matter Webform's implementation I would say this is impossible.
Answer: When you edit an element, under form display you should have a list of options:

Input hiding
disabled
read only
prepopulate

I believe disabled should achieve what you require.
However, as the comment mentioned, there is no way to prevent anyone from amending the query string as they seem fit.
If you need the 'query string' to be 'secure' then you should be looking at a different solution entirely, e.g. you could store it in the session.

Disable pre-populated fields in webform


Penalty Shot out

Question: What is the rule should the Goalkeeper save the penalty, (as in a case I experienced), the ref blows his whistle then the ball which went away from goal had some backspin on it and slowly proceeded to make its way into the net while the keeper was celebrating winning the shoot out with his team.  Objections from the opposing Manager resulted in the kick being taken again and this time they scored and we went from winning to losing the shot out.
 Anyone know what should have happened?
Comment: Derek - your answer is in the other question linked above. Now, this isn't just a case of the referee making a mistake - they have misapplied the Laws of the Game. Please have your club formally report this to the league or your local FA, as this is a serious error that should result in the result being changed and the referee receiving coaching.
Comment: Thanks Martin, happened a while back now, Pickfords save last night just reminded me and was curious as what would have happened had the ball reacted in the same way. Maybe should have appealed at the time as they were only 12 year olds. Life lesson I suspose, for the Keeper anyway.
Answer: IFAB Laws of the Game - Law 14 – The Penalty Kick:

The penalty kick is completed when the ball stops moving, goes out of play or
  the referee stops play for any offence.

The referee erred by blowing the whistle before the procedure outlined above was complete. The goal should have stood instead of being retaken.
Comment: This may be true for penalty kicks during the match, but for kicks from the penalty mark (i.e. a shootout as described in the question), [Law 10, Section 3](http://www.theifab.com/laws/determining-the-outcome-of-a-match-2018/chapters/kicks-from-the-penalty-mark-2018) is more applicable. "The kick is completed when the ball stops moving, goes out of play or the referee stops play for any offence; the kicker may not play the ball a second time" Note the extra restriction on the ball being touched a second time by the kicker.

Penalty Shot out


views_get_view in combination with i18nviews only translates part of header

Question: I'm using the following code to get a view and render it
<code>  $view = views_get_view('viewname');
  $view->set_display('page');

  $view->set_arguments(array($type));

  $view->pre_execute();
  $view->execute();

  return $view->render();
</code>
Works great but some fields of the exposed filters and the header are not getting translated. I'm using the i18nviews modules.
Any ideas?
Thanks
Answer: Using the following code triggers i18nviews correctly:
<code>$view = views_get_view('viewname');
$view->set_display('page', array($type));
</code>