Como transformar um JSON em uma tabela/lista paginada utilizando .Net Core MVC?

Question: Estou estudando acesso a API e estou utilizando a API do Github. Eu quero fazer uma tela na qual seja possível pesquisar por nome os repositórios que batem com o critério passado. Mas os resultados do Github são enormes, como eu posso fazer para paginar essa lista?
Agora estou com problema para ler o JSON retornado pela pesquisa. No código abaixo é a classe que acessa a API e baixa o JSON
public List<Repositorio> PesquisaRepo(string repoNome) {
        List<Repositorio> repositorios = new List<Repositorio>();
        string urlPesquisa = urlPesquisaRepo + repoNome;

        var client = new WebClient();
        client.Headers.Add("user-agent", this.userAgent);

        var resposta = client.DownloadString(urlPesquisa);

        var repoJSON = JArray.Parse(resposta);
}

Na linha var repoJSON = JArray.Parse(resposta); ocorre o seguinte erro:
Error reading JArray from JsonReader. Current JsonReader item is not an array

O JSON retornado é nesse formato:
    {
  "total_count": 18551,
  "incomplete_results": false,
  "items": [
    {
      "id": 76954504,
      "node_id": "MDEwOlJlcG9zaXRvcnk3Njk1NDUwNA==",
      "name": "react-tetris",
      "full_name": "chvin/react-tetris",
      "owner": {
        "login": "chvin",
        "id": 5383506,
        "node_id": "MDQ6VXNlcjUzODM1MDY=",
        "avatar_url": "https://avatars2.githubusercontent.com/u/5383506?v=4",
        "gravatar_id": "",
        "url": "https://api.github.com/users/chvin",
        "html_url": "https://github.com/chvin",
        "followers_url": "https://api.github.com/users/chvin/followers",
        "following_url": "https://api.github.com/users/chvin/following{/other_user}",
        "gists_url": "https://api.github.com/users/chvin/gists{/gist_id}",
        "starred_url": "https://api.github.com/users/chvin/starred{/owner}{/repo}",
        "subscriptions_url": "https://api.github.com/users/chvin/subscriptions",
        "organizations_url": "https://api.github.com/users/chvin/orgs",
        "repos_url": "https://api.github.com/users/chvin/repos",
        "events_url": "https://api.github.com/users/chvin/events{/privacy}",
        "received_events_url": "https://api.github.com/users/chvin/received_events",
        "type": "User",
        "site_admin": false

Como eu faço para acessar somente a tag "items"?
A URL que estou acessado é https://api.github.com/search/repositories?q=tetris
Comment: poste a parte do código onde está com difilcudade, assim podemos lhe ajudar.
Comment: @Marconi O compilador indica erro
Comment: Voce tem a classe do json ?
Comment: @MatheusMiranda A classe para criar objetos com esse JSON? Tenho uma classe chamada Repositorio que tem uns atributos que quero recuperar do JSON
Comment: @Marconi Tentei isso mesmo. Ele diz que "resposta" é uma string e não tem definições para acessar um método
Comment: @LeandroSouza, entendo veja a minha resposta.
Answer: Lembrando que eu copiei aqui e joguei para arquivo txt com codificação de unicode. O resultado do ReadAllText é o mesmo que DownloadString. Fiz teste apenas no local.
Segue código:
string json = File.ReadAllText(@"C:\json.txt", Encoding.Unicode);

RootObject result = JsonConvert.DeserializeObject<RootObject>(json);

var somente_tag_items = result.items;

Caso você queira pesquisar pelo Id (2548674), faça assim:
var items = result.items.Where(x => x.id == 2548674).ToList();

Segue as classes:
public class Owner
{
    public string login { get; set; }
    public int id { get; set; }
    public string node_id { get; set; }
    public string avatar_url { get; set; }
    public string gravatar_id { get; set; }
    public string url { get; set; }
    public string html_url { get; set; }
    public string followers_url { get; set; }
    public string following_url { get; set; }
    public string gists_url { get; set; }
    public string starred_url { get; set; }
    public string subscriptions_url { get; set; }
    public string organizations_url { get; set; }
    public string repos_url { get; set; }
    public string events_url { get; set; }
    public string received_events_url { get; set; }
    public string type { get; set; }
    public bool site_admin { get; set; }
}

public class License
{
    public string key { get; set; }
    public string name { get; set; }
    public string spdx_id { get; set; }
    public string url { get; set; }
    public string node_id { get; set; }
}

public class Item
{
    public int id { get; set; }
    public string node_id { get; set; }
    public string name { get; set; }
    public string full_name { get; set; }
    public Owner owner { get; set; }
    public bool @private { get; set; }
    public string html_url { get; set; }
    public string description { get; set; }
    public bool fork { get; set; }
    public string url { get; set; }
    public string forks_url { get; set; }
    public string keys_url { get; set; }
    public string collaborators_url { get; set; }
    public string teams_url { get; set; }
    public string hooks_url { get; set; }
    public string issue_events_url { get; set; }
    public string events_url { get; set; }
    public string assignees_url { get; set; }
    public string branches_url { get; set; }
    public string tags_url { get; set; }
    public string blobs_url { get; set; }
    public string git_tags_url { get; set; }
    public string git_refs_url { get; set; }
    public string trees_url { get; set; }
    public string statuses_url { get; set; }
    public string languages_url { get; set; }
    public string stargazers_url { get; set; }
    public string contributors_url { get; set; }
    public string subscribers_url { get; set; }
    public string subscription_url { get; set; }
    public string commits_url { get; set; }
    public string git_commits_url { get; set; }
    public string comments_url { get; set; }
    public string issue_comment_url { get; set; }
    public string contents_url { get; set; }
    public string compare_url { get; set; }
    public string merges_url { get; set; }
    public string archive_url { get; set; }
    public string downloads_url { get; set; }
    public string issues_url { get; set; }
    public string pulls_url { get; set; }
    public string milestones_url { get; set; }
    public string notifications_url { get; set; }
    public string labels_url { get; set; }
    public string releases_url { get; set; }
    public string deployments_url { get; set; }
    public DateTime created_at { get; set; }
    public DateTime updated_at { get; set; }
    public DateTime pushed_at { get; set; }
    public string git_url { get; set; }
    public string ssh_url { get; set; }
    public string clone_url { get; set; }
    public string svn_url { get; set; }
    public string homepage { get; set; }
    public int size { get; set; }
    public int stargazers_count { get; set; }
    public int watchers_count { get; set; }
    public string language { get; set; }
    public bool has_issues { get; set; }
    public bool has_projects { get; set; }
    public bool has_downloads { get; set; }
    public bool has_wiki { get; set; }
    public bool has_pages { get; set; }
    public int forks_count { get; set; }
    public object mirror_url { get; set; }
    public bool archived { get; set; }
    public int open_issues_count { get; set; }
    public License license { get; set; }
    public int forks { get; set; }
    public int open_issues { get; set; }
    public int watchers { get; set; }
    public string default_branch { get; set; }
    public double score { get; set; }
}

public class RootObject
{
    public int total_count { get; set; }
    public bool incomplete_results { get; set; }
    public List<Item> items { get; set; }
}

Comment: Funcionou! Obrigado!
Comment: De nada, estamos aqui pra isso.


Implicit functions and exponentials

Question: I am working with real numbers and trying to express u as function of x, given the equation:
$x^2-u\,e^u = 4$.
I am a bit lost because of the exponential part. I read something about the Lambert function, so I tried to use it and I have:
$W(u\,e^u) = W(-4+x^2) \implies
u = W(-4+x^2)$
Is that correct? If it is, how do i find the derivative with respect to x? Thanks anyone for the help.
Comment: https://math.stackexchange.com/questions/1473437/derivative-of-lambert-w-function
Comment: I corrected the math LaTeX expressions. Most notably, dollar signs were missing.
Answer: $$x^2-ue^u=4$$
$$ue^u=-4+x^2$$
$$u=W(-4+x^2)$$
The derivative of Lambert W is:
$$\frac{d}{dx}W(x)=\frac{W(x)}{x(1+W(x))},$$
the derivative of $-4+x^2$ is:
$$\frac{d}{dx}-4+x^2=2x.$$
Applying the quotient rule , we get
$$\frac{d}{dx}W(-4+x^2)=\frac{2xW(x^2-4)}{(x^2-4)(1+W(x^2-4))}.$$
We also could use the formula for implicit differentiation:
$$x^2-ue^u=4$$
$$x^2-ue^u-4=0$$
$$\frac{d}{dx}u(x)=-\frac{2x}{-e^u-ue^u}$$

Implicit functions and exponentials


Proof for relation between a function and its partial molar quantities

Question: A variable, $Y$, depends on $N$ independent variables, $n_1, n_2, n_3, ..., n_N$. This variable is extensive in the sense that:
$$Y(\lambda n_1,\lambda n_2,...,\lambda n_N)=\lambda Y(n_1,n_2,...,n_N) \tag{1}$$
where $n_j$ is the amount of component $j$. It can be proven that
$$Y=\Sigma_in_i\bar{Y}_i\tag{2}$$
where
$$\bar{Y}_i=(\frac{\partial{Y}}{\partial n_i})_{n_{j\neq i}} \tag{3}$$
In the proof showing (2) from (1), below is the first step:

We start by setting $v_i=\lambda n_i$, then differentiating (1) WRT $\lambda$ gives
$$\Sigma_{i=1}^{N}\frac{\partial{Y}}{\partial v_i}\cdot \frac{\partial{v_i}}{\partial \lambda}=\lambda Y(n_1,n_2,...,n_N) \tag{4}$$

I don't understand this step. Differentiating both sides of (1) WRT $\lambda$, we have
$$\frac{\partial}{\partial \lambda}Y(v_1,v_2,...v_N)=Y(n_1,n_2,...,n_N)+\lambda\frac{\partial{Y(n_1,n_2,...,n_N)}}{\partial{\lambda}}$$
And then sum over all $N$ components, shouldn't it be
$$\Sigma_{i=1}^{N}\frac{\partial{Y}}{\partial v_i}\cdot \frac{\partial{v_i}}{\partial \lambda}=NY(n_1,n_2,...,n_N)+N\lambda\frac{\partial{Y(n_1,n_2,...,n_N)}}{\partial{\lambda}}?$$
How do you get the RHS term in Eq(4)? I am just a lowly chemist, apologise if I asked something stupid.
Answer: One of the confusing things here is that you aren't giving a fixed name to the arguments of $Y$. Let's say the arguments of $Y$ are actually denoted by $x_i$ regardless of whether they are scaled or not.
Now differentiate (1) wrt $\lambda$. On the left side you initially get $\sum_{i=1}^n \frac{\partial Y}{\partial x_i}(\lambda n_1,\dots,\lambda n_N) \frac{\partial x_i}{\partial \lambda}$. Since $x_i=\lambda n_i$ here, you get $\sum_{i=1}^n n_i \frac{\partial Y}{\partial x_i}$.
On the other side, the derivative with respect to $\lambda$ is just $Y(n_1,\dots,n_N)$, because on that side $x_i$ is just $n_i$. So you have
$$\sum_{i=1}^n n_i \frac{\partial Y}{\partial x_i}(\lambda n_1,\dots,\lambda n_N) = Y(n_1,n_2,\dots,n_N).$$
The final step is to set $\lambda=1$ to get the desired result.
Comment: @TheLearner The multivariable chain rule. (Physically each term is the contribution to the change in $Y$ from changing each $n_i$, when the parameter describing the scale of the entire system is changing).
Comment: @TheLearner No. $Y$ doesn't depend explicitly on $\lambda$ at all anyway.
Comment: For the LHS, why does differentiating $Y$ give a summation?
Comment: It makes sense now! Final question, is the summation equal to $N\frac{\partial{Y}}{\partial{\lambda}}$?


Exception thrown at 0x011414CE in chars.exe: 0xC0000005: Access violation reading location 0x00000004

Question: So I'm wring a code for a program using C  that just performs basic linked list tasks like create the list, insert a node after a given current node, remove node , etc.
I am using visual studio 2015, so when I tried to test my insert-a-node-after function by debugging it and using visual studio watch to visualize my list and whether or not it was inserting nodes after the current node properly, I got the error:
Exception thrown at 0x011414CE in chars.exe: 0xC0000005: Access violation reading location 0x00000004.
Unhandled exception at 0x011414CE in chars.exe: 0xC0000005: Access violation reading location 0x00000004.
So here is my .h file with the struct and list declaration
#ifndef DLIST_H
#define DLIST_H

typedef struct DListNode_struct {
char *str;
int blankIndex;
int blankLength;
struct DListNode_struct *next;
struct DListNode_struct *prev;
} DListNode;

typedef struct DList_struct {
   int size;
   DListNode *head;
   DListNode *tail;
} DList;

void DListConstruct(DList* list);

void DListInsertAfter(DList* list, DListNode* currNode, DListNode* newNode);

#endif // DLIST_H

so here is my main function
#include <stdio.h>
#include <stdlib.h>
#include "dlist.h"

int main() {

DList* list = NULL;
DListNode* currNode = NULL;

DListNode* newNode1 = (DListNode*)malloc(sizeof(DListNode));

DListInsertAfter(list, currNode, newNode1);

return 0;
}

And here is my .c file where I have my insertafter function
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "dlist.h"

void DListConstruct(DList* list) {

list->head = NULL;
list->tail = NULL;
list->size = 0;

}

void DListInsertAfter(DList* list, DListNode* currNode, DListNode* newNode) {

DListNode* sucNode;

if (list->head == NULL) {
    list->head = newNode;
    list->tail = newNode;
}

else if (currNode == list->tail) {
    list->tail->next = newNode;
    newNode->prev = list->tail;
    list->tail = newNode;
}

else {
    sucNode = currNode->next;
    newNode->next = sucNode;
    newNode->prev = currNode;
    currNode->next = newNode;
    sucNode->prev = newNode;
}
}

I found some posts related to my question but all of them either do not target linked lists or are not in C.
So can anyone help me finding where the bug is?
Thanks in advance.
Comment: The debugger should tell you exactly which line of code is triggering the seg fault. Please provide that as a minimum. It's worth your time to learn to use the debugger more effectively.
Answer: You are passing NULL to DListInsertAfter as list and first check (list->head == NULL) fails as you access null pointer.
Answer: Dlist after is receiving a list which is NULL
So going list->head is the problem. Since it doesn't exist!
You need to allocate the list first.
#include <stdio.h>
#include <stdlib.h>
#include "dlist.h"

int main() {

DList* list = NULL;
DListNode* currNode = NULL;

DListNode* newNode1 = (DListNode*)malloc(sizeof(DListNode));

DList* list = (void*)malloc(sizeof(DList));

DListInsertAfter(list, currNode, newNode1);

return 0;
}

Comment: I think you tried to bold a line of code in Markdown; you can't do that, so it now looks like you're a bit trigger happy with the asterisks haha...
Comment: Ooops
I was in a rush to answer his question
But it seems some other people answered before I did :D
Answer: the arrow operator -> is syntactic sugar for dereference combined with struct member access. Therefore the line
if (list->head == NULL) {

is the same as
if ((*list).head == NULL) {

When you call DListInsertAfter() you pass in a pointer for the list parameter which is initialised to NULL. Therefore you are dereferencing a NULL pointer, which is probably causing your crash. You need at some point to allocate memory for your DList struct before you try to access it.


Converting Image Map to Drupal Content

Question: We have an old site that was are migrating to drupal. On the old site we have an image map: http://www.seguridadidl.org.pe/districts.html
Wondering if there is a more dynamic way of adding an image map such as this to drupal, rather than just adding the html in a node.
Does the "onMouseOver" work in Drupal?
Comment: what do you mean by "Does the "onMouseOver" work in Drupal"?
Comment: Couldn't see your imagemap - page looks broken: _"Página no encontrada La página "/districts.html" solicitada no se ha podido encontrar."_ - But the word _districts_ suggests this is a geographic map. If that's the case I would suggest you consider the many options for mapping in Drupal, here's a good module: https://drupal.org/project/ip_geoloc
Comment: Sorry, we moved the site. I should update this question and post our solution.
Comment: Now it is located here: /mapa/riesgos-y-recursos-preventivos-del-delito-lima-metropolitana-y-el-callao-2012
Answer: I think the Google Maps Tools module is the right solution. Just parse or migrate your data into it.

This project integrates the Google Maps API and Google Static Maps API. It makes possible to add addresses and/or coordinates (points) to nodes through CCK fields, display these geographical informations on node pages as text or interactive map or static map and use them on GeoRSS feeds. The project provides style plugins and row style plugins for views to build both interactive and static maps.
Answer: You can add the image map to any full  HTML enabled text area... so you could drop it into content, put it in an text area field, or put it in a block. You can also drop it in a template file....
Answer: An imagemap is just a set of coordinates that map a mouseover to an area in your map.
A quick google and I dont see any Drupal related imagemap modules. You could try to store coordinates as a field in your node. But, that sounds messy. An imagemap basically assumes a user has intimate knowledge of the image to properly build the coordinate sets.
onMouseOver is a Javascript event. HTML, CSS, the HTTP protocol, Javascript all work together to power the internet nowadays; so of course you can use Javascript code in a Drupal website. Drupal is simply a PHP CMS making use of all these things ... So long as the client browser supports it -- you're fine.
Comment: I have a related question:  http://drupal.stackexchange.com/questions/72313/using-js-maphilight-module-and-trying-to-trigger-a-hilight-from-an-external-ele
Comment: There is a jQuery maphilight module out there that we are using for this issue

Converting Image Map to Drupal Content


Mount partition on KVM guest and host at the same time

Question: Is there a way to mount a partition on the kvm host and one guest at the same time?
(on linux / ubuntu, no samba suggestions, please)
Answer: A normal filesystem will be corrupted if you mount it from multiple OS's at the same time. A cluster file system should work.
The easiest solution is probably to use NFS.
Comment: I think nowdays with SSHFS, well it's better. https://github.com/winfsp/sshfs-win


Spring JDBC MVC project gives 404

Question: I've been fighting with the Spring framework for few weeks now, and I got
a normal MVC page to show up, and I got JDBC to print onto the console.
But I can't seem to get these to work together...
I've been through countless tutorials at this point and every one of them
seem to have some type of error or problem.
I think I've finally managed to get together a pretty decent and working build, but nope, still getting only 404's.
I think the problem might be in the spring-servlet.xml file:
<context:component-scan base-package="src" />

And I'm not sure if you can even load project like that, but it's the only thing I can think of here.
I include all the other files too, though.
Console Errors
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:spring-mvc' did not find a matching property.

and
SEVERE: Servlet [spring] in web application [/spring-mvc] threw load() exception
java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1275)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1109)
    at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:520)
    at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:501)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:118)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1050)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:989)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4903)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5213)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1419)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>spring-mvc</groupId>
  <artifactId>spring-mvc</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.5.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.0.0</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <properties>
    <java.version>1.8</java.version>
    <spring.version>3.1.0.RELEASE</spring.version>
    <cglib.version>2.2.2</cglib.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>4.3.7.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.3.7.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.7.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc-portlet</artifactId>
      <version>4.3.7.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>
    <dependency>
      <groupId>org.gatein.common</groupId>
      <artifactId>common-logging</artifactId>
      <version>2.2.2.Final</version>
    </dependency>
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>2.8.1</version>
      <type>pom</type>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>6.0.5</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.3.7.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.3.7.RELEASE</version>
    </dependency>
  </dependencies>
</project>

spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context-3.0.xsd">

 <context:annotation-config />

 <context:component-scan base-package="controller" />

 <bean id="viewResolver"
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="/WEB-INF/jsp/" />
  <property name="suffix" value=".jsp" />
 </bean>

 <bean id="userDao" class="dao.UserDaoImpl" />
 <bean id="userService" class="services.UserServiceImpl" />

 <bean id="dataSource"
  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="com.mysql.jdbc.Driver" />
  <property name="url" value="jdbc:mysql://localhost:3306/userdb" />
  <property name="username" value="root" />
  <property name="password" value="38613861" />
 </bean>
</beans>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 id="WebApp_ID" version="2.5">
 <display-name>SpringJDBCTemplate</display-name>
 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>

 <servlet>
  <servlet-name>spring</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>spring</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>
</web-app>

homePageController
package controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import domain.*;
import services.*;

@Controller
public class HomePageController {

 @Autowired
 UserService userService;

 @RequestMapping("/register")
 public ModelAndView registerUser(@ModelAttribute User user) {

  List<String> genderList = new ArrayList<String>();
  genderList.add("male");
  genderList.add("female");

  List<String> cityList = new ArrayList<String>();
  cityList.add("delhi");
  cityList.add("gurgaon");
  cityList.add("meerut");
  cityList.add("noida");

  Map<String, List> map = new HashMap<String, List>();
  map.put("genderList", genderList);
  map.put("cityList", cityList);
  return new ModelAndView("register", "map", map);
 }

 @RequestMapping("/insert")
 public String inserData(@ModelAttribute User user) {
  if (user != null)
   userService.insertData(user);
  return "redirect:/getList";
 }

 @RequestMapping("/getList")
 public ModelAndView getUserLIst() {
  List<User> userList = userService.getUserList();
  return new ModelAndView("userList", "userList", userList);
 }

 @RequestMapping("/edit")
 public ModelAndView editUser(@RequestParam String id,
   @ModelAttribute User user) {

  user = userService.getUser(id);

  List<String> genderList = new ArrayList<String>();
  genderList.add("male");
  genderList.add("female");

  List<String> cityList = new ArrayList<String>();
  cityList.add("delhi");
  cityList.add("gurgaon");
  cityList.add("meerut");
  cityList.add("noida");

  Map<String, Object> map = new HashMap<String, Object>();
  map.put("genderList", genderList);
  map.put("cityList", cityList);
  map.put("user", user);

  return new ModelAndView("edit", "map", map);
 }

 @RequestMapping("/update")
 public String updateUser(@ModelAttribute User user) {
  userService.updateData(user);
  return "redirect:/getList";
 }

 @RequestMapping("/delete")
 public String deleteUser(@RequestParam String id) {
  System.out.println("id = " + id);
  userService.deleteData(id);
  return "redirect:/getList";
 }
}

Project tree
Project tree from Eclipse Neon2
Comment: This is a proper structure for an maven web project: https://conorpower.files.wordpress.com/2010/03/maven-project-structure.png and in webapp folder it should have WEB-INF and resources foder
Comment: Do you use the m2e maven/eclipse plugin? Is this project imported as a maven project? At least for me, Maven had everything come in under `src/main/java///` rather than just src. Also, any reason you're using xml config instead of java config?
Comment: how are you running your app?
Comment: @artemisian right click -> run as server (tomcat9) i also have separate linux server with tomcat9 which i use to deploy without eclipse, neither one works.
Comment: Can you post an image of the structure of the war file when you create it, run 'mvn package'. The war file can be opened by a file compressor/decompressor app as WinRar.
Comment: @S.Buda i have the plugin and this project was written by me from tutorial, not imported. I just didnt think the packages when i wrote it so now i dont know what to use but "src" No particular reason for xml other than trying to get any of these goddamn things to work atleast once...
Comment: @Clomez, don't worry will try to help you. As a side note, if you want to save some headaches you can try sometime spring-boot, it does a lot of auto-configuration for you and you can download working copies: https://spring.io/guides/gs/serving-web-content/
Comment: I suspect that your problem lies on a configuration you added on the build section of your POM, since maven project works with WEB-INF structure rather than WebContent. Remove the maven-war-plugin from your plugins and test again. Let me know.
Comment: Looked at your structure image now, and it seems odd to me since a war project in maven doesn't create this kind of structure. It seems it was a dynamic web project that was converted to a maven project. So you can do following test to see if it works: copy only POM.xml and src folder to a new folder create another workspace, and import it as a maven project, not eclipse nor web project
Comment: @JorgeCampos you are correct, it's a dynamic project converted to maven, i really have no clue how i should properly do this and i just cant find any clear explanation for it. How should i redo this project? Also i removed maven-war plugin but that didnt help
Comment: There seems to be tons of tutorial, all doing things little differently and i just cant get any of them to work. if anyone have any clear tutorial about getting mvc project to show mysql data with maven and eclipse on jsp page, that would be nice.
Comment: So, lets make it right then...
Comment: follow these steps: 1 - Create a folder a new folder anywher lets call it [mvnproject]; 2- Create the structure in the image in my previous comment **except** the target folder; 3- copy your pom.xml to the root of mvnproject folder; 4- go to your physical project structure in the folder src copy all folders `controller, dao, etc` to the new structure in mvnproject/src/main/java
Comment: 5 - copy the WEB-INF folder of your project into the mvnproject/src/main/webapp; 6 - remove the lib folder (you don't need it since maven will handle the dependencies)
Comment: 7 - in a new eclipse workspace, import a new project selecting a existing maven projects and select the mvnproject path. 8 - after import the project click on it and press ALT + F5 (pc keys) this will tel eclipse to update maven dependencies and that should do it
Comment: Next steps will be to configure a apache tomcat server to deploy your project into
Comment: This is the basic, and if you still have problems with it, try this tutorial https://www.mkyong.com/maven/how-to-create-a-web-application-project-with-maven/ this guy have the easiest tutorials to follow and he always add the project code at the end.
Comment: @JorgeCampos Thank you, very much. I will try that but it takes some time, i'll get back to you. but thank you.
Comment: @JorgeCampos well, it now looks like this, i thinks its right but still not working. http://imgur.com/a/zijjV
Comment: @Clomez Well, that looks more right to me, at the very least. And your frustration pretty sums up my experience getting spring to start. It's always a headache creating a new project but once things are running it works nicely.
Comment: Sorry for the delay.... It still not right. I know that because Eclipse should not show the package as `main.java.controller....` Maven ignores that folder and start right under the java folder as it was the src folder itself. Someting must be wrong on your project. Try cleaning everything, remove the project from eclipse, delete (physically) the folder .settings and the file .classpath and the file .project. Go on your folder project on the console and run `mvn clean eclipse:clean` then open all folders of if (like the image I showed to you) and paste it here so I can see what it is wrong
Comment: This is how a maven web project structure in eclipse should look like: http://imgur.com/dRHDo9u I'm using the package explorer view in eclipse
Comment: Well, i got it to work but i had to rebuild the whole thing, eitherway mega thanks to @JorgeCampos for your help, atleast i now understand better whats going on, cheers!
Comment: Great to hear that. Enjoy!
Answer: Not my answer but the one which solved the case, posting as answers since it's buried deep in comments.

Sorry for the delay.... It still not right. I know that because
  Eclipse should not show the package as main.java.controller.... Maven
  ignores that folder and start right under the java folder as it was
  the src folder itself. Something must be wrong on your project. Try
  cleaning everything, remove the project from eclipse, delete
  (physically) the folder .settings and the file .classpath and the file
  .project. Go on your folder project on the console and run mvn clean
  eclipse:clean then open all folders of if (like the image I showed to
  you) and paste it here so I can see what it is wrong

– Jorge Campos

Spring JDBC MVC project gives 404


How to trigger an event when node is saved?

Question: I am trying to execute a piece of code when a node is saved. I am using hook_node_update, but it's never triggered when updating a node. Here is my code:
function custom_node_update(Drupal Core Entity EntityInterface $node) {
 // Logs a notice
 \Drupal::logger('custom')->notice("entity was updated");
}

What is wrong with my code?
Answer: The parameter passed to code had syntax error.
The correct code will be
function custom_node_update(Drupal\Core\Entity\EntityInterface $node) {
  // Logs a notice
  \Drupal::logger('custom')->notice("entity was updated");
}

Comment: Should just do a `use Drupal\Core\Entity\EntityInterface` at the top of the file. Then just refer to it as `EntityInterface`.
Answer: First of all you should look at using hook_entity_update. Also, is that code in a module called "custom"? And is that module enabled? Last thing ... the parameter should look something like this \Drupal\Core\Entity\EntityInterface $entity.  You are missing slashes.


How to add event listener/ionChange on month change event in an ion-datetime object?

Question: When the user changes the month i need to re-render the highlightedDates: a query is called and retrieve all the dates of that month.
It works if the user use the top button to manually select a month and the year, but if he just click on the arrows: "<" ">" then the ionChange is not trigger.
<code>  <div class="calendar">
    <ion-datetime
      [(ngModel)]="selectedDate"
      presentation="date"
      locale="it-IT"
      [highlightedDates]="allAppointments"
      (ionChange)="createAppointmentList()"
    >
    </ion-datetime>
</code>
Basically i need an eventListener when the user click on the arrows of the calendar
Comment: You can find a workaround at https://github.com/ionic-team/ionic-framework/issues/25730#issuecomment-1213238159 it might need a bit of tweaking, but it's a workable solution and will get the job done.
Answer: Somewhat found a solution thanks to Misha Mashina comment
<code>  initMonthObserver(){
    const monthText = document.querySelector('ion-datetime')?.shadowRoot?.querySelector('.calendar-header')?.querySelector('ion-label');
    const elementToObserve = document.querySelector('ion-datetime')?.shadowRoot?.querySelector('.calendar-body')

    if (elementToObserve) {
      const observer = new MutationObserver((mutationsList, observer) => {

        this.monthString = monthText?.textContent;
        let parts = this.monthString.split(" ")
        let monthIndex = this.monthNames.indexOf(parts[0].toLowerCase())
        let monthNumber = monthIndex + 1
        let year = parts[1]

        if(this.monthString){
          this.monthToDate = new Date(year, monthNumber).toISOString()
          this.queryAppsPerMonth(this.monthToDate)
        }

      })
      const observerConfig = {
        childList: true,
        subtree: true,
      };
      observer.observe(elementToObserve, observerConfig)
    }
  }
</code>
Got the calendar element using:
<code> document.querySelector('ion-datetime')?.shadowRoot?.querySelector('.calendar-body')
</code>
Then MutationObserver to track mutation of that


Webapp behaves as expected when run from eclipse while when exported as war fails

Question: This has been driving me nuts.
So I have a (very simple vanilla servlet 3) web app. When I run it in eclipse all is fine. Among others I am able to register an account with Unicode (greek) username and then log in as site admin and visit the user's profile alright. When I export war to  $CATALINA_HOME\webapps, launch $CATALINA_HOME\bin\startup.bat, open the site in the browser, login as admin and try to visit the user profile the username etc display as blank.
The files in ...\apache-tomcat-7.0.32\conf and the ones in ...\eclipse_workspaces\javaEE\Servers\Tomcat v7.0 Server at localhost-config differ only in the line (in server.xml) :
<Context docBase="ted2012" path="/ted2012" reloadable="true"
source="org.eclipse.jst.jee.server:ted2012"/>

which is an eclipse thing.
The doGet method (slimmed) in the profile servlet :
protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    final String username = Helpers.decodeRequest(request
            .getParameter("user"));
    if (username != null) {
        User user = null;
        try {
            System.out
                    .println("ProfileController.doGet() user name DECODED : "
                            + username);
            user = userService.getUserWithUsername(username); // THIS FAILS
            System.out.println("ProfileController.doGet() user : " + user);
            request.setAttribute("userToShow", user);
        } catch (ServiceExDBFailure e) {
            log.debug("ProfileController::doGet", e);
            request.setAttribute("ErrorString", e.getMessage());
        }
        sc.getRequestDispatcher(OTHERPROFILE_JSP)
                .forward(request, response);
        return;
    } else {
        //does not apply
    }
}

The decode method is :
public static String decodeRequest(String parameter)
        throws UnsupportedEncodingException {
    if (parameter == null)
        return null;
    System.out.println("decode - request.getBytes(\"iso-8859-1\"):"
            + new String(parameter.getBytes("iso-8859-1")));
    System.out.println("decode - request.getBytes(\"iso-8859-1\") BYTES:"
            + parameter.getBytes("iso-8859-1"));
    for (byte iterable_element : parameter.getBytes("iso-8859-1")) {
        System.out.println(iterable_element);
    }
    System.out.println("decode - request.getBytes(\"UTF-8\"):"
            + new String(parameter.getBytes(CHARSET_FOR_URL_ENCODING))); // UTF-8
    return URLDecoder.decode(new String(parameter.getBytes("iso-8859-1")),
            CHARSET_FOR_URL_ENCODING);
}

While the db call is :
            statement = conn.prepareStatement(query);
            statement.setString(1, username);
            System.out.println("ελληναρα");
            System.out.println(statement);
            set = statement.executeQuery();
            if (set.next()) {
                User user = new User();
                // user.setId(set.getInt("ID"));
                user.setUsername(set.getString("username"));
                user.setName(set.getString("name"));
                user.setSurname(set.getString("surname"));
                user.setPassword(set.getString("password"));
                user.setEmail(set.getString("email"));
                user.setRole(RolesENUM.values()[set.getInt("role")]);
                return user; // if the set is empty null is returned
            }

Tomcat prints :
decode - request.getBytes("iso-8859-1"):╧à╧â╧ä╬╡╧?╬╣╬▒
decode - request.getBytes("iso-8859-1") BYTES:[B@529b9ed
-49
-123
-49
-125
-49
-124
-50
-75
-49
-127
-50
-71
-50
-79
decode - request.getBytes("UTF-8"):├?┬à├?┬â├?┬ä├Ä┬╡├?┬?├Ä┬╣├Ä┬▒
ProfileController.doGet() user name DECODED : ╧à╧â╧ä╬╡╧?╬╣╬▒
com.mysql.jdbc.JDBC4PreparedStatement@766d7940: SELECT * FROM users WHERE username='╧à╧â╧ä╬╡╧?╬╣╬▒'
????????
ProfileController.doGet() user : null

while Eclipse prints :
decode - request.getBytes("iso-8859-1"):υστερια
decode - request.getBytes("iso-8859-1") BYTES:[B@4b6a6bdf
-49
-123
-49
-125
-49
-124
-50
-75
-49
-127
-50
-71
-50
-79
decode - request.getBytes("UTF-8"):ÏÏÏεÏια
ProfileController.doGet() user name DECODED : υστερια
com.mysql.jdbc.JDBC4PreparedStatement@37d02427: SELECT * FROM users WHERE username='υστερια'
ελληναρα
ProfileController.doGet() user : com.ted.domain.User@63144ceb

I believe for some reason the query that gets to the db is something crazy - notice that where in eclipse prints ελληναρα in tomcat prints ???????? while the unicode username (υστερια) prints as ╧à╧â╧ä╬╡╧?╬╣╬▒ and not as ???????.
So the question is - what changes between the Eclipse deployment and the tomcat deployment ? Why the hell the DB returns null ? I have really really tried to debug this in vain
Help
EDIT : replacing the line  statement.setString(1, username); with statement.setString(1, "υστερια"); there is NO failure. So by the time this line is run the bytes are mangled up - notice though that the bytes are the same one by one
EDIT2 : Tomcat v7.0 Server at localhost Eclipse launch VM args (split for readability) :
-Dcatalina.base="C:\Dropbox\eclipse_workspaces\javaEE\.metadata\.plugins
\org.eclipse.wst.server.core\tmp1"
-Dcatalina.home="C:\_\apache-tomcat-7.0.32"
-Dwtp.deploy="C:\Dropbox\eclipse_workspaces\javaEE\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps"
-Djava.endorsed.dirs="C:\_\apache-tomcat-7.0.32\endorsed"

NB : the launch for the app is created dynamically
EDIT 2013.03.30 : this is now on github - and see my more general question here
Comment: What are you trying to do with those request decodings and encodings?
Comment: @JB Nizet : See : http://stackoverflow.com/a/12764128/281545. I am trying to avoid having to configure tomcat to have URIEncoding as UTF-8. Whatever I am trying to do is working when runing the app in eclipse while not running in tomcat.
Comment: When you receive a parameter, it's already a String, so Tomcat has already transformed the bytes into a String using its default encoding. It's too late.
Comment: @JB Nizet : the exact same code runs in eclipse fine (which launches the same install of Tomcat) - can you elaborate ?
Comment: Check how Eclipse starts Tomcat. But this decoding/encoding is wrong. It makes no sense. Read the first two answers in the thread you linked to. It explains it very well.
Comment: @JBNizet : It does make sense - please read it carefully. Instead of adding `URIEncoding="UTF-8"` in the `Context` I get the bytes in the default tomcat encoding and decode them my self. That's why I add the `request.getBytes(CHARSET_FOR_URL_ENCODING)) // UTF-8` call - to display the bytes are encoded in iso-8859-1. The subtle thing is that actually `getParameter()` does call `URLDecoder.decode()` - wiy\th default (`iso-8859-1`) charset. The advantage of how I do it is that it needs no xml edits. To be done properly I should query the server for its current encoding. Will edit with VM args
Comment: No, it doesn't make sense. Suppose the tomcat encoding is ASCII, and you send parameters encoded in UTF8, containing only bytes that make no sense in ASCII. This means that the String containing the parameter value would only contain question marks (or whatever character is used when decoding a byte that isn't valid for ASCII). And transforming these question marks to bytes and then re-decoding the bytes to a String using UTF8 won't magically find the original bytes. That's like reducing the size of a bitmap image and enlarging it afterwards: it's a lossy operation.
Comment: @JB Nizet: you may be very well right but notice I print the bytes and it is the same bytes in both tomcat and Eclipse. Then I call `URLDecoder.decode(new String(request.getBytes("iso-8859-1")), "UTF-8")` - it is passed the same bytes in (!?). The only part that may be fishy is `final String username = Helpers.decodeRequest(request.getParameter("user"));` where iso may be used (in getParameter("user")). Still one important part in the question is _why the hell does it run in eclipse and not in Tomcat (with identical config) ?_
Answer: This was finally answered here.
The gist of the answer is that I eclipse had as default encoding UTF-8 and Tomcat windows-1252 so when I call new String() without specifying the encoding those are used to tranlate the byte[] to chars. Doing
new String(parameter.getBytes("iso-8859-1"), "UTF-8");

solves the problem - it would not though if tomcat in
request.getParameter("user") // url decoding is performed by tomcat - using the
// URIEncoding from server.xml or by default ISO-8859

would not use by default ISO-8859 as another encoding (say ASCII) would probably (behavior undefined and not controllable before Java 7 nio) replace undecodable characters with ? so parameter String would be corrupted (see ISO-8859-1 encoding and binary data preservation).
So bravo to tomcat for performing the conversion by default with ISO-8859 in its request.getParameter() and boo to Java ee spec guys who do not even mention in the docs that getParameter will perform URL decoding, let alone letting us specify the encoding, overriding server.xml.


Dividir table em duas div

Question: Olá tenho quatro div com tamanho fixo 300px cada, e uma table dento da primeira  div, preciso que quando essa table supere o tamanho de 300px o restante do conteúdo vá para a segunda div e assim por diante.

#pg1{
  border: 1px solid black;
  height: 600px;
  width: 350px;
  float: left;
  top: 0px;
  position: relative;
}
#pg2{
  border: 1px solid black;
  height: 600px;
  width: 350px;
  float: right;
  top: 0px;
  position: relative;
}
#tbl{
  border: 1px solid black;
}

      01
      02
      03

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

        AA
        BB
        CC

Não estou de forma nenhuma conseguindo fazer isso e já garimpei a internet.
Comment: Paulo, eu fiz um teste aqui e pra mim funciona. Você chegou a perceber que as colunas da sua linha não atinge os `300px`? Tente colocar na primeira linha   `AAAAAAAAAAAAAAAAAAAAAAAAAAAA`
        `BBBBBBBBBBBBBBBBBBBBBBBBBBB`
        `CCCCCCCCCCCCCCCCCCCCCCCCCCC`, isso vai atingir até a 3 DIV.
Comment: Ok o que preciso é que quando a altura da table atingir os  300px o restante da table vai para outra div
Answer: Me surgiram algumas alternativas de solução para este problema, algumas são mais adequadas dependendo do contexto geral em que essa "divisão de tables" se encontra.
Uma alternativa seria verificar em algum evento, por exemplo, caso você vá incluir dados na table através de um click em um botão, então sempre que esse botão for acionado, após inserir o conteúdo na table, você faz a verificação se a altura da table ultrapassa o limite estabelecido em 300px, caso ultrapasse, você pode pegar o elemento adicionado, cloná-lo, removê-lo da table que excedeu a altura e adicionar na div mais próxima.
Segue um código de como fazer essa verificação na prática:
var table = $("#tbl");
  if(table.height() > 300){
     var ultimaLinha = $('#tbl tr:last');
     var clone = ultimaLinha.clone();
     ultimaLinha.remove();
     var tableProxima = table.parent().next("div");
     tableProxima.append(clone);
  }

Nota que no exemplo, eu clono uma tr mas isso pode facilmente ser aplicado para qualquer tipo de elemento.
A segunda alternativa seria mais apropriada par o caso de haver uma table preenchida, como o exemplo que você apresentou na pergunta, tendo em vista esse padrão de conteúdo
AA	BB	CC
, são necessárias 15 linhas para exceder o limite da altura (300px), logo, imagino algo como, dividir o número de linhas presentes na table ($('#tbl tr').length;) por 2 e verificar se o resultado é menor que 15, se for, deixa o número resultante como o número de linhas na table e o restante coloca na outra div, para fazer isso da pra usar a mesma lógica do código apresentado anteriormente, caso eu não tenha sido claro, fique à vontade  para questionar.

Dividir table em duas div


Como percorrer um array de objetos, somar propriedades específicas e unificar esses objetos onde tiver uma propriedade específica igual a outra?

Question: Tenho um array de objetos que tem essa estrutura abaixo:
listaProdutos =
[
      {nome:'Teclado',preco:28.00},
      {nome:'Mouse',preco:36.00},
      {nome:'Monitor',preco:500.00},
      {nome:'CPU',preco:800.00},
      {nome:'Teclado',preco:28.00},
      {nome:'Monitor',preco:500.00},
];

Minha intenção seria que fosse gerado um array de objetos com o resultado abaixo:
novoLista =
[
    {nome:'Teclado',preco:56.00},
    {nome:'Mouse',preco:36.00},
    {nome:'Monitor',preco:1000.00},
    {nome:'CPU',preco:800.00}
];

Você poderiam me ajudar com a melhor abordagem para essa situação ?
Comment: @GatodeSchrödinger depende de a partir de qual numero voce considera "muitos dados" ou "poucos dados". O legal dessas respostas é que são soluções distinas, com resultados de benchmark diferentes de acordo com a situacao. No bench. que o Luiz Felipe mostrou, a solucao dele é excelente para casos de muitos objetos no array (+1000), mas para caso mais simples, a solucao do Ricardo Pontual é a que melhor se adapta. Acho inclusive que deveriamos estudar um pouco mais sobre o `Map`. Pra mim essa foi a pergunta com as respostas mais interessantes do ano :D .
Comment: Estou mantendo um _benchmark_ com cada resposta desta pergunta. Para não ser injusto com nenhuma resposta, sugiro que o iminente utilizador de qualquer um dos códigos abaixo altere os valores padrão do número de elementos do _benchmark_ para espelhar as necessidades do projeto. A performance de cada solução varia significativamente de acordo com o número de itens únicos (`NAMES_COUNT`) e de elementos totais (`ITEMS_COUNT`). **[Aqui está o link.](https://jsbench.me/6xkkroain8/1)**
Comment: Veja qual seria a estrutura de tabela hash / tabela de espalhamento / _hash table_ no JS (conjunto de pares de chave/valor em que a chave não se repete)? Percorre o array e vai vendo se os nomes já existem como chaves da hash table, se já existirem você atualiza o valor da mesma (soma o que já estava com o do objeto), senão acrescenta o novo par.
Comment: Tabela hash é uma estrutura de dados essencial e ubíqua em computação, presente nas linguagens sob diversos nomes (dicionários, maps, hashmaps, etc), se não conhece recomendo que estude e entenda bem seu princípio de funcionamento, pois se aplica a uma diversidade de situações. Aqui no SOpt mesmo tem uma boa explicação: https://pt.stackoverflow.com/q/27827/357
Comment: @GatodeSchrödinger, com poucos dados a diferença é mínima e quase imperceptível, uma vez que (embora percentualmente a diferença seja visível) será tudo muito rápido. Em quantidades maiores, aí sim fará diferença. No seu caso, se a quantidade de dados for pequena, escolha o código que mais lhe agrada. Sem dúvidas todas as soluções postadas aqui são muito elegantes. :-)
Comment: @LuizFelipe fiz simulações com 3 cenários de testes, com 1000 itens, 100 e 10 e os resultados são completamente diferentes, seria interessante montar esses 3 cenários para termos um bom report ao final
Comment: @RicardoPontual, pois é, e também varia com ordens de grandeza maiores que `1e3`. Tente com `1e5` ou `1e6`, por exemplo. :P Por isso que sugeri que o utilizador testasse varias conforme a quantidade aproximada que trabalhará. Mas convenhamos que JS realmente não é linguagem para esse tipo de operação com _muitos_ itens, então essa minha ideia de _benchmark_ é meio _pointless_ em primeiro lugar...
Comment: Galera, muito obrigado por serem solícitos. Eu ainda sou leigo na questão de testar desempenho no benchmark . Essa pergunta é com base em um curso que estou fazer e fiquei com dúvidas. Como não queria fazer coisas esdrúxulas (que era como eu sabia fazer) eu preferi consultar aqui, para me agregar conhecimento. Mas sinceramente, na opinião de vocês. Quais das respostas teria um desempenho melhor com "poucos dados" e com "muitos dados" ? A diferença seria perceptível com "muitos dados" ? Pelo que vi lá, com visão de leigo, a do Ricardo Pontual foi a que me pareceu ter o melhor resultado.
Comment: Sim, @CmteCardeal, Mas a ideia é realmente essa. Pra mim pode ser "poucos dados", mas futuramente posso precisar da solução para "muitos dados". Ou outros usuários que entrem atrás de uma solução, possa variarem entre querer a resposta pra "muitos dados" e "poucos dados". A ideia é que a resposta realmente me atenda. Mas o espírito geral é que possa ajudar futuros usuários também, com necessidades iguais a minha, porém com quantidades de dados que possam variar de um pra outro.
Comment: eu confesso que gostei muito de todas as abordagens, e o teste deixa claro os pontos fortes e fracos de cada implementação em cenários diversos, isso faz muita diferença e deixa a pergunta muito mais rica com além de respostas, análises comparando cada uma delas :)
Comment: Por favor evitem longas discussões nos comentários; a conversa de vocês foi [movida para o chat](https://chat.stackexchange.com/rooms/119370/discussion-on-question-by-gato-de-schrodinger-como-percorrer-um-array-de-objetos)
Answer: Pode-se usar o método reduce() para iterar em cada elemento do array, remover os duplicados e somar. Por exemplo:

listaProdutos =
[
      {nome:'Teclado',preco:28.00},
      {nome:'Mouse',preco:36.00},
      {nome:'Monitor',preco:500.00},
      {nome:'CPU',preco:800.00},
      {nome:'Teclado',preco:28.00},
      {nome:'Monitor',preco:500.00},
];

const novoLista = listaProdutos.reduce((soma, cur) => {
  // guarda o nome atual e verifica se existe repetido
  let nome = cur.nome;
  let repetido = soma.find(elem => elem.nome === nome)
  // se for repetido soma, caso contrário adiciona o elemento ao novo array
  if (repetido) repetido.preco += cur.preco;
  else soma.push(cur);
  // retorna o elemento agrupado e somado
  return soma;
}, []);

console.log(novoLista);
Comment: A diferença é perceptível com uma amostra de dados um pouco maior, [veja](https://jsbench.me/6xkkroain8/1). Quanto maior o número de elementos, maior é a diferença. Em amostras pequenas, a diferença de velocidade é ínfima e faz pouca diferença.
Comment: obrigado @GatodeSchrödinger, os testes, que aliás o Luiz Felipe fez um ótimo trabalho de juntar e manter mostram que esse algoritmo que usei é o mais rápido com poucos elementos, eu fiz um teste com até 30 ele é o mais rápido, dai até 100 já fica na média, e com mais de 100 começa a cair a performace, sendo o mais lento com 1000 elementos para cima, deixo comentado aqui para quem ver essa ótima pergunta e quiser experimentar algum dos algoritmos :)
Comment: Legal! :) +1 Só acho válido observar que como `reduce` e  `find` têm complexidade O(n), este código tem complexidade quadrática, o que pode ser ruim em casos de grande quantidade de itens.
Comment: Galera, vou verificar amanhã de tarde. Hoje estou super exausto. Muito obrigado.
Comment: @LuizFelipe, por curiosidade criei um benchmark entre as duas soluções e o resultado é quase igual, sendo o reduce ligeiramente mais performático: https://jsben.ch/oQc4s
Comment: Esse reduce com o find dentro foi bem interessante.
Comment: Todas as respostas foram ótimas, me serviram e foram devidamente "upvotadas" por mim.  Porém essa aqui foi a que achei mais simples e a que eu pude entender melhor. Apesar de eu não saber se foi a mais performática. Obrigado a todos!
Comment: Nada. Eu que agradeço :)
Comment: Isso tá sendo muito útil pra mim. Se pudesse, dava +2. hahaha'
Answer: Você pode acumular cada nome único e ir somando o preco de cada objeto por nome correspondente. Uma vez que o mapa tenha sido completo, gera-se o novo array. Uma forma de manter os objetos a partir de uma chave única é utilizar a estrutura de dados Map do JavaScript.
Algo assim:

function sumByPropName(nameProp, sumProp, arr) {
  const map = new Map();

  for (const obj of arr) {
    // Chave que utilizaremos para o mapa. A `key` corresponde a cada "nome" único.
    const key = obj[nameProp];

    // Caso nenhum objeto já tiver sido registrado para a chave atual, devemos o
    // inserir pela primeira vez.
    if (!map.has(key)) {
      map.set(key, obj);

      // Podemos pular para a próxima iteração, já que o valor correspondente
      // já está incluído no `obj`.
      continue;
    }

    // Caos já tenha sido registrado, é só somar ao valor já armazenado.
    map.get(key)[sumProp] += obj[sumProp];
  }

  // Converter o mapa em array:
  return [...map.values()];
}

const original = [
  { nome: 'Teclado', preco: 28.0 },
  { nome: 'Mouse', preco: 36.0 },
  { nome: 'Monitor', preco: 500.0 },
  { nome: 'CPU', preco: 800.0 },
  { nome: 'Teclado', preco: 28.0 },
  { nome: 'Monitor', preco: 500.0 }
];

// Queremos identificar elementos únicos pela propriedade `nome` (1º arg.)
// O somatório corresponde à propriedade `preco` (2º arg.)
console.log(sumByPropName('nome', 'preco', original));

A complexidade da função acima seria algo como O(n + m), sendo n o número de elementos do array original e m o número de nomes únicos.

O n vem do for (que é indispensável neste tipo de situação).
O m (que muitas vezes é ínfimo e pode ser desconsiderado) vem da necessidade de se converter o mapa para array ao final da função.

Se Map não puder ser utilizado (foi introduzido no ECMAScript 2015), pode-se utilizar Object.create(null) como substituto.
Tentei já explicar direto pelo código, qualquer dúvida deixe nos comentários que tento editar para esclarecer.
Comment: Galera, vou verificar amanhã de tarde. Hoje estou super exausto. Muito obrigado.
Answer: Vou compartilhar a minha solução, sendo esta, ao meu ver, uma alternativa decente as outras respostas.
Código:

const listaProdutos = [
  { nome: 'Teclado', preco: 28.0 },
  { nome: 'Mouse', preco: 36.0 },
  { nome: 'Monitor', preco: 500.0 },
  { nome: 'CPU', preco: 800.0 },
  { nome: 'Teclado', preco: 28.0 },
  { nome: 'Monitor', preco: 500.0 },
];

const resObject = {};

listaProdutos.forEach((elem) => {
  const valorAnterior = resObject[elem.nome] || 0;

  resObject[elem.nome] = valorAnterior + elem.preco;
});

const novoLista = Object.keys(resObject).map((key) => {
  return { nome: key, preco: resObject[key] };
});

console.log(novoLista);

As explicações:

const resObject = {}; é um objeto temporário para salvar o valor de nome como uma key deste objeto, além de manter um valor acumulado de cada preco da lista de produtos.

forEach pra iterar sobre os elementos de lista.

valorAnterior recebe o valor já salvo no resObject de acordo com a chave (Teclado, Mouse, etc...). Se a chave não existir, adotamos o valor 0.

resObject[elem.nome] = valorAnterior + elem.preco; basicamente, adicionar uma chave ao objeto resObject com um valor inicial de acordo com elem.preco. Se a chave já existe, ela já tem um valor, então faremos uma soma.

Neste ponto, se você der um console.log, verá o objeto resObject com as chaves com o nome dos nomes de produtos da lista e os respectivos valores já somados.

const listaProdutos = [
  { nome: 'Teclado', preco: 28.0 },
  { nome: 'Mouse', preco: 36.0 },
  { nome: 'Monitor lcd', preco: 500.0 },
  { nome: 'CPU', preco: 800.0 },
  { nome: 'Teclado', preco: 28.0 },
  { nome: 'Monitor', preco: 500.0 },
];

const resObject = {};

listaProdutos.forEach((elem) => {
  const valorAnterior = resObject[elem.nome] || 0;

  resObject[elem.nome] = valorAnterior + elem.preco;
});

console.log(resObject)

A partir de agora, o que faremos é associar a chave do resObject para um objeto com a propriedade nome:
 return { nome: key, ...}

e o preco será o valor desta chave usando resObject[key]:
return { nome: key, preco: resObject[key] };

Adicionei um toFixed apenas pra ficar como deseja para novoLista:

const listaProdutos = [
  { nome: 'Teclado', preco: 28.0 },
  { nome: 'Mouse', preco: 36.0 },
  { nome: 'Monitor lcd', preco: 500.0 },
  { nome: 'CPU', preco: 800.0 },
  { nome: 'Teclado', preco: 28.0 },
  { nome: 'Monitor', preco: 500.0 },
];

const resObject = {};

listaProdutos.forEach((elem) => {
  const valorAnterior = resObject[elem.nome] || 0;

  resObject[elem.nome] = valorAnterior + elem.preco;
});

const novoLista = Object.keys(resObject).map((key) => {
  return { nome: key, preco: parseFloat(resObject[key]).toFixed(2) };
});

console.log(novoLista);
Comment: Legal! Coloquei no [benchmark](https://jsbench.me/6xkkroain8/1) para não ficar de fora. :-)
Comment: boa, acho que vai ficar muito boa essa pergunta, com várias soluções e benchmark :)
Comment: Obrigado, verificarei todas.
Answer: Ainda no tema Map é possível utilizar outra abordagem.
Faça duma instancia de Map um índice para os elementos do Array novoLista
que será populado inicialmente com uma cópia do primeiro objeto da lista listaProdutos cujo a propriedade nome ainda não tenha sido indexada.
Caso já haja um índice que seja a propriedade nome apenas some preço ao preço do elemento já indexado.

let listaProdutos =
[
      {nome:'Teclado',preco:28.00},
      {nome:'Mouse',preco:36.00},
      {nome:'Monitor',preco:500.00},
      {nome:'CPU',preco:800.00},
      {nome:'Teclado',preco:28.00},
      {nome:'Monitor',preco:500.00},
];

let novoLista = [];

let m = new Map();

//Para todos os elementos de listaProdutos...
for(let prod of listaProdutos){
  //Verifica se índice contiver a chave prod.nome...
  if (m.has(prod.nome)){
    //No item indexado por prod.nome no array novoLista incrementa o preço registrado com o novo preço.
    novoLista[m.get(prod.nome)].preco += prod.preco;
  } else {
    //Cria um índice nomeado pelo valor de prod.nome apontando para o mais novo elemento do array novoLista
    m.set(prod.nome, novoLista.push({nome:prod.nome,preco:prod.preco}) - 1);
  }
}

console.log(novoLista);

Créditos ao Luiz Felipe quem colocou o código acima na forma de uma função:

let listaProdutos =
[
  {nome:'Teclado',preco:28.00},
  {nome:'Mouse',preco:36.00},
  {nome:'Monitor',preco:500.00},
  {nome:'CPU',preco:800.00},
  {nome:'Teclado',preco:28.00},
  {nome:'Monitor',preco:500.00},
];

function somar(arr) {
  let novoLista = [];
  let m = new Map();
  for (let prod of arr) {
    if (m.has(prod.nome)) {
      novoLista[m.get(prod.nome)].preco += prod.preco;
    } else {
      m.set(prod.nome, novoLista.push({
        nome: prod.nome,
        preco: prod.preco
      }) - 1);
    }
  }
  return novoLista;
}

console.log(somar(listaProdutos))
Comment: Também coloquei no [benchmark](https://jsbench.me/6xkkroain8/1).
Comment: Obrigado, verificarei todas.
Comment: @LuizFelipe eu peguei o seu código benchmark. Espero que não haja problemas. Quando escrevi esta resposta estava muito cansado. Havia virado a noite brigando com codepoints unicode e foi quando achei uma [resposta aqui no site](https://pt.stackoverflow.com/a/396555/137387) que municiava para resolver o meu problema.
Answer:

const listaProdutos = [{
    nome: 'Teclado',
    preco: 28.00
  },
  {
    nome: 'Mouse',
    preco: 36.00
  },
  {
    nome: 'Monitor',
    preco: 500.00
  },
  {
    nome: 'CPU',
    preco: 800.00
  },
  {
    nome: 'Teclado',
    preco: 28.00
  },
  {
    nome: 'Monitor',
    preco: 500.00
  },
];

// Agrupe
const groups = listaProdutos.reduce((acc, current) => {
  if (!acc[current.nome]) {
    acc[current.nome] = { ...current
    }

    return acc
  }

  acc[current.nome].preco = acc[current.nome].preco + current.preco

  return acc
}, {})

// Extraia a lista
const newList = Object.values(groups)
console.log(newList)
Comment: Também coloquei no [benchmark](https://jsbench.me/6xkkroain8/1).
Comment: Pelo que pude ver, essa foi a mais rápida, certo ?
Comment: seria legal adicionar comentários ou na pergunta explicar como fez para agrupar
Comment: Eu vou escolher a resposta amanhã. Cara, o trabalho está me sugando de uma forma absurda. Por um acaso maravilhoso, todas as respostas me serviram. Fico até sem jeito de escolher uma. Se pudesse eu escolheria todas. Muito obrigado mesmo.


How do you represent f(x+h) and f(x−h) as a Taylor series using the taylor series formula?

Question: I know the answers are below, however i am not quite sure what to substitute as the "a" in the Taylor series formula.
$f(x+h)=f(x)+f′(x)⋅h+\frac 12f′′(x)\cdot h^2+\cdots+\frac 1{n!}f^{(n)}(x) \cdot h^n$
and
$f(x−h)=f(x)−f′(x)⋅h+\frac 12f′′(x)\cdot h^2+\cdots+ \frac 1{n!}f^{(n)}(x) \cdot (-h)^n$
Answer: I personally like to write the Taylor series as follows:
$$f(x)=f(a)+f'(a)\Delta x+\frac{f''(a)}{2!}(\Delta x)^{2}+\mathcal{O}(\Delta x)^{3}$$
Where $a$ is the point at which you are expanding about, and $\Delta x = x-a$. This usually helps me when trying to work out expansions around a point.
Here, for your first example, you have $a=x$ and $\Delta x = h$, for the second you have $a=x$ and $\Delta x = -h$. Therefore for your second example we get:
$$f(x-h)=f(x)-f'(x)(-h)+\frac{f''(x)}{2}(-h)^{2}+\mathcal{O}(h)^{3}$$
I hope this helps!!
Comment: Hi does the symbol O(h)3 represent all the polynomials of degree three and higher.
Comment: @Jed It's big O notation.  Definitely not polynomials higher than degree 3.


Confidence Interval from LOESS dissapears when using weights with geom_smooth command

Question: In R, using the ggplot2 package, I have these two lines:
ggplot(data, aes(x = x, y = Pinera)) +
    geom_point(shape = 1) +
    geom_smooth(method = loess, se = TRUE)

ggplot(data, aes(x = x, y = Pinera, weight = pesos)) +
    geom_point(shape = 1) +
    geom_smooth(method = loess, se = TRUE)

The first one gives me an unweighted smooth curve from my data with the shaded confidence interval, however when I add the weights, the confidence interval region disappears despite I stated se = TRUE.
This is my data
Comment: your data doesnt seem to have a pesos variable
Comment: I created locally in the code the pesos variable using x. I already figured out the problem: when created the "pesos", some weights were rounded to 0, which are not accepted in the model.

By imposing at least an epsilon for every weight it works just fine.
Answer: Question solved: loess cannot process weight vectors with zeros.


Migrate content from drupal8 to drupal8 programmatically with Node::load and Node::create

Question: Basicly I want to migrate content from one drupal8 instance to another. they are mostly identical with some small changes.
first step is to migrate the content type via drush gen module module and drupal-console drupal config:export:content:type
then i export the content type via script:
<?PHP
define('DRUPAL_DIR', __DIR__ . "/web");

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

require_once DRUPAL_DIR . '/core/includes/database.inc';
require_once DRUPAL_DIR . '/core/includes/schema.inc';
$autoloader = require_once DRUPAL_DIR . '/autoload.php';

$request = Request::createFromGlobals();

$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel->boot();
$kernel->prepareLegacyRequest($request);

use Drupal\node\Entity\Node;
use Drupal\Component\Serialization;
$serializer = \Drupal::service('serializer');

echo "Node Export Starting... \n\n";

// Nodes
$node_ids = \Drupal::entityQuery('node')->condition('type', 'content-type')->execute();
echo count($node_ids);
$single_nodes =  \Drupal\node\Entity\Node::loadMultiple($node_ids);
$data = $serializer->serialize($single_nodes, 'json');
file_put_contents('nodes.json', $data);

i serialize it and write it into a file.
on the new page I install the exported module to receive all fields for the content type + dependencies and so on.
if I try now to run my importer script i get serveral errors that the (exported) nodes can not be created.
 $json = json_decode(file_get_contents(__DIR__ . "/import/nodes.json"));
foreach ($json as $nid => $nodeImport) {
    $node = Node::create($nodeImport);
    $node->save();
}

Node::create() doesnt seems to accept whole exported/loaded NodeArrays nor casted arrays like (array)$nodeImport
Am I missing something?
Answer: You might consider using Migrate module for this task. For pulling entities from external database use Drupal 8 migration module.


The use of logarithmic form to facilitate comparison

Question: On a post from the internet I've found the following expression, which I'll like to understand and to apply it on my datas.

"Because of the size difference between the largest and the smallest
  metros, the data is expressed in logarithmic form so as to facilitate
  comparison."[source]
Answer: On normal scale the extreme points would be far from the other point and to fit them on the same curve would either require putting a break on the curve or making the difference in consecutive tick marks large enough to fit everything in.  But that would make it very difficult to discern differences between point in the center of the distribution.  Using a log scale eliminates this problem.


Deducement of First and second Borel-Cantelli Lemma

Question: Suppose that $\Omega$ is a set, $(\Omega, \mathscr{G})$ is a measure space, and $Z: \Omega \to \mathbb{R}$ is a given mapping. Then Z is  $\mathscr{G}$ measurable iff $$Z =\displaystyle\sum_{i=1}^\infty \lambda_i I_{A_i} \tag{1}$$ for some {$\lambda$} $\subset \mathbb{R}$ and  {$A_i$} $\subset \mathscr{G}$. From(1) deduce the First Borel-Cantelli Lemma: if $\displaystyle\sum_{i=1}^{\infty} P(A_i) < \infty $ then $P(\lim sup A_n) =0$
Solution:=  The "if" part follows directly from the observation that the mapping given by (1) is the pointwise limit as $n \to \infty $ of the $\mathscr{G}$  measurable mappings $\displaystyle\sum_{i=1}^n \lambda_i I_{A_i}.$
For the opposite direction, first suppose that  Z is nonnegative . Define $$\begin{align*} Z_1 := I_{Z \geq 1},\\ &  S_n :=\displaystyle\sum_{i=1}^n \displaystyle\frac{1}{i}Z_i, Z_{n+1} := I_{Z-\displaystyle\frac{1}{n+1}\geq S_n},  n\geq 1 \end{align*}$$
We claim that $Z = \lim S_n = \displaystyle\sum_{i=1}^\infty \displaystyle\frac{1}{i} Z_i $ (Note that $\lim S_n$ exists).
Using induction we first show that $S_n \leq Z, \forall n \in \mathbb{N}$ Clearly $S_1 = I_{Z \geq 1} \leq Z.$ Suppose that the claim holds for some $m \in \mathbb{N}$ and denote {$ Z -\displaystyle\frac{1}{m+1} \geq S_m$} by A. Then on A, we have $Z \geq \displaystyle\frac{1}{m+1} + S_m $ while, by the inductive hypothesis, on $A^c$ we have $Z \geq S_m$.Thus $Z \geq \displaystyle\frac{1}{m+1} I_A +S_m= S_{m+1}$ which completes the proof by induction.
It remains to show that $\lim S_n \geq Z$. Fix an arbitrary $\omega \in \Omega$. If $Z ( \omega) = \infty$, we  have $Z_n( \omega) = 1 \forall n \in \mathbb{N} $ and the result follows. If $Z(\omega) < \infty ,$ suppose that on the contrary $Z(\omega) -\lim S_n > 0 $ and find $ k \in \mathbb{N} $ such that $\displaystyle\frac{1}{k} < Z(\omega) -\lim S_n$. Then, since $ S_n \leq \lim S_n,$ we have $Z(\omega)-\displaystyle\frac{1}{n+1}\geq S_n(\omega), \forall n \geq k,$ and so $Z_n(\omega) =1 \forall n \geq k.$ But then $\lim S_n =\infty $ which is a contradiction.
In the general case we write $Z = Z^+ - Z^- $ and apply the above result to both parts (since$ Z^+ $ and $Z^-$ live on disjoint sets there is no additional convergence issues in merging the two series.)
The First Borel-Cantelli Lemma is essentially the statement that if $Z = \displaystyle\sum_{i=1}^\infty I_{A_i}$ is integrable, then $Z < \infty $ almost surely.
Would any member of math stack exchange explain this  solution to the given problem with all the details and how,where,when and for what purposes and in which situations this results can be used in the real world scenario?
For example, suppose I want to make risk assessment for flood insurance where I  as an insurer need to estimate the probability of a certain amount of rainfall occurring. In this situation, How can I use this result of First Borel-Cantelli Lemma?
Answer: The First Borel-Cantelli Lemma can be applied in risk assessment for flood insurance in the following way:
The lemma states that if you have an infinite sequence of events, and the sum of their probabilities is finite, then the probability that any of these events will occur infinitely often is zero.
In the context of flood insurance, consider each "event" as a flood occurring in a specific area. If the probability of a flood occurring in each year is independent of the previous years, and the sum of these probabilities over an infinite time horizon is finite, then according to the First Borel-Cantelli Lemma, the probability that floods will occur infinitely often in this area is zero.
This can help insurance companies in their risk assessment. If the conditions of the lemma are met, they can conclude that the risk of having to pay out for flood damage every year is zero. This can influence the pricing of their insurance policies and their decision on whether to offer insurance in that area.
However, it's important to note that in reality, events like floods are often not independent and their probabilities may not be easy to estimate accurately. Therefore, while the Borel-Cantelli Lemma provides a theoretical framework, its application in real-world scenarios like flood insurance should be done with caution and in conjunction with other risk assessment tools.
The problem is about measure theory, which is an area of mathematics concerned with measuring the "size" of subsets of a certain set. A measure is a function that assigns a non-negative number to each subset of a given set, satisfying some properties such as countable additivity. A measure space is a triple consisting of a set, a collection of subsets called a sigma-algebra, and a measure defined on that sigma-algebra. A mapping from a measure space to the real numbers is called measurable if it preserves the structure of the sigma-algebra, that is, if the inverse image of any measurable set is also measurable.
The problem asks to prove that a mapping Z is measurable if and only if it can be written as an infinite sum of indicator functions of measurable sets, where an indicator function is a function that takes the value 1 on a given set and 0 elsewhere. The problem also asks to deduce from this result the First Borel-Cantelli Lemma, which is a statement about the probability of the limit superior of a sequence of events, where the probability is a special kind of measure that assigns values between 0 and 1 to each event.
The solution proceeds as follows:

The "if" part of the problem is easy to show, because if Z can be written as an infinite sum of indicator functions of measurable sets, then for any measurable set B, the inverse image of B under Z is the union of the inverse images of B under each indicator function, and since the union of measurable sets is measurable, the inverse image of B under Z is also measurable.
The "only if" part of the problem is more involved, and it requires to consider two cases: when Z is non-negative and when Z is general. The idea is to construct a sequence of measurable functions that converges pointwise to Z, and then use the fact that the limit of measurable functions is measurable.
In the case when Z is non-negative, the solution defines a sequence of functions $Z_n$ as follows: $Z_1$ is the indicator function of the set where Z is greater than or equal to 1, and for n greater than 1, $Z_n$ is the indicator function of the set where Z minus $\frac{1}{n+1}$ is greater than or equal to the sum of the previous functions. The solution also defines another sequence of functions $S_n$ as the partial sums of the products of $Z_n$ and $\frac{1}{n}$. The solution claims that Z is equal to the limit of $S_n$, which is also equal to the infinite sum of the products of $Z_n$ and $\frac{1}{n}$.
To prove this claim, the solution first shows by induction that $S_n$ is less than or equal to Z for all n, and then shows that the limit of $S_n$ is greater than or equal to Z for all $\omega$ in the measure space. The latter part is done by contradiction, assuming that there exists an $\omega$ where $Z(\omega)$ minus the limit of $S_n$ is positive, and then finding a contradiction by showing that $Z_n(\omega)=1$  for all sufficiently large n, which implies that the limit of $S_n$ is infinite.
In the case when Z is general, the solution writes Z as the difference of two non-negative functions $Z^+$ and $Z^-$, and applies the previous case to each of them separately. Since $Z^+$ and $Z^-$ are zero on disjoint sets, there is no problem in adding their respective series to obtain the series for Z.
The First Borel-Cantelli Lemma is a consequence of the previous result, because if Z is the infinite sum of the indicator functions of a sequence of events $A_i$, and if the sum of the probabilities of $A_i$ is finite, then Z is integrable, that is, the measure of Z is finite. This implies that Z is finite almost surely, that is, except on a set of measure zero. But the set where Z is infinite is precisely the limit superior of the sequence of events $A_i$, that is, the set of points that belong to infinitely many $A_i$. Therefore, the probability of the limit superior of $A_i$ is zero, as the lemma states.


Loading a batteries dependent file into ocamltop -- the interfaces disagree

Question: Here is a simple ocaml file, just meant to get me to understand how to load a program that uses the Batteries library into the ocamltop.
batteryassault.ml
open Batteries

let main = print_string "hello, world ... powered on"

I compile this to bytecode with
ocamlfind ocamlc -package batteries -linkpkg batteryassault.ml

Resulting in batteryassault.cmo and batteryassault.cmi, and no errors nor warnings.  Then, I start the battery-powered ocamltop with
rlwrap ocamlfind batteries/ocaml

Finally, to load the file in ocamltop:
#load "batteryassault.cmo" ;;

And then we get an error.

The files batteryassault.cmo and /usr/lib/ocaml/batteries/batteries.cma
  disagree over interface Batteries

I think what could be going on is that Ubuntu installs batteries 2.2.1, but for some reason (installing merlin?) I have batteries 2.3.1 installed in my opam folder, and moreover, when starting the ocamltop with batteries as above, it indicates that ocamltop is using the 2.2.1 version.  Further, compiling with
ocamlfind ocamlc -package batteries -linkpkg batteryassault.ml -verbose

I find that ocamlc is definitely using the library in opam, i.e. the 2.3.1 version.
So my question is: what is the/is there a workaround?
Comment: Also, starting ocamltop with
rlwrap  ~/.opam/system/lib/batteries/ocaml
does not help either.
Answer: Usually I suggest to remove system OCaml installation at all. Otherwise you may have such errors.
You should ensure, that all your tools and libraries come from the same source, in this particular case from opam.
A usual error is to forget to call for
eval `opam config env`

at some point. You may recall later about this, and activate your opam, thus ending up, with parts of your application, or even opam stack built using opam with other parts built with system libraries. If you made such error, it will be hard to guess, when and what goes wrong.
But if you still don't want to remove system batteries, then you need to be very careful. For example, since ocamlfind batteries/ocaml results in loading old version of batteries, then you can try to use this trick, to make sure that batteries topleve is loaded from opam:
$ `opam config var batteries:lib`/ocaml

If the problem persists, that means that your system is really broken. Consider removing you opam stack and making carefully everything from scratch. E.g.,
 rm -rf ~/.opam
 opam init --comp=4.02.1
 eval `opam config env`
 opam install batteries


Views: Sort By Global Math Expression Result?

Question: I have created a global math expression field in views, and I want to sort the results by the results of the math expression.
In particular, I use Drealty to connect to a RETS server and download property listings.  My local database gets populated with prices and number of bedrooms for each listing.  I want to sort based on Cost per Bedroom.
Any Ideas?
Answer: You can't sort currently by just using views but i would recommend to store
the value in the database.
Therefore create a computed field: http://drupal.org/project/computed_field
and do the logic in there to store the value in the DB. Once you have done this views will be able to sort by that.
Answer: If you have table with aggregation module you can sort without needing to store in DB
Answer: I guess you can do it by creating a new module with hook_drealty_import_presave_alter or rules.  The problem is that you need to write the result of the math to the database so that you can sort or filter on it.


Construct an equilateral triangle given a line segment

Question: Given two vertices that make up a line segment (x1,y1) and (x2,y2), how can we find the third vertice that would make up an equilateral triangle? I'm looking to derive the third vertex algebraically, rather than drawing circles and whatnot.
Comment: Solve the equations involving the circles algebraically..?
Answer: First of all, you should know that there are two points that would make it an equilateral triangle. Also note that the third point is on a line perpendicular to the segment between the first two points. Call the first two points A and B. If you average their x and y values, you will get midpoint M, which is right between the first two points. Find the slope of the line segment AB, and use a negative reciprocal to find the perpendicular line that passes through point M. You should also know that the altitude of an equilateral triangle is $sqrt(3)$ times 1/2 its base. Then, find the two points C and D that are on the line containing M and perpendicular to AB that are $sqrt(3) * b/2$, where b is length AB.
Answer: By simple transformation, we can reasonably assume that the line lies on the x-axis with one end at (0, 0) and the other at (h, 0) where h is the length of the line segment.
The computation is included in the following diagram.

Edit: The image vertex is at (h/2, –√3h/6).


How does the forgetful functor from $\textsf{Man}$ to $\textsf{TopMan}$ factor under the ternary factorization system?

Question: Here, $\textsf{TopMan}$ refers to the category of topological manifolds (second-countable, Hausdorff, locally Euclidean topological spaces) with continuous maps for morphisms; and $\textsf{Man}$ refers to the category of smooth manifolds (topological manifolds equipped with a smooth atlas) with smooth maps for morphisms.
Clearly, $\textsf{TopMan}$ forms a full subcategory of $\textsf{Top}$.
More importantly, the following are true (please correct me if I'm wrong at any step):

Every smooth manifold has a unique underlying topological manifold and every smooth map of manifolds is continuous. Thus, the "forgetful" functor $F: \textsf{Man} \rightarrow \textsf{TopMan}$ is well-defined.
Not every topological manifold admits a smooth structure (due to Kervaire). Thus, $F$ is not essentially surjective.
$F$ is not full because of the much simpler reason that not all continuous maps (between smooth manifolds) are smooth.
A given topological manifold may admit more than one smooth structure (due to Milnor). Thus, $F$ is not injective-on-objects.
$F$ is indeed faithful, because given any two smooth manifolds $X$ and $Y$, then two distinct smooth maps between $f,g:M \to N$ cannot have the same image under $F$ (in fact, $f$ and $g$ are distinct iff they are distinct as set-functions.)

Given all this, how do I factorize $F$ in the 3-way factorization system [1] [2]? Since, $F$ is faithful, it only needs to be written as a composition of two functors: one that is fully faithful, and another that is essentially surjective and faithful.
While all this isn't particularly essential/important to the study of $\textsf{Man}$, I think that thinking of the forgetful functor in terms of its factors will help me get a feel for what exactly smooth manifolds and smooth maps are in terms of structure/property.
PS: I have been unsuccessful so far in locating online discussions on $\textsf{Man}$ and related categories (beyond the most basic stuff). Any links will be appreciated (or you can tell me why talking about this category as such is not very useful)!
[1] http://ncatlab.org/nlab/show/stuff,+structure,+property
[2] http://ncatlab.org/nlab/show/ternary+factorization+system
Answer: The ternary factorisation of a functor $F : \mathcal{C} \to \mathcal{D}$ can be constructed explicitly as follows:

Let $F[\mathcal{C}]$ be the category whose objects are those in $\mathcal{C}$ and whose morphisms $X \to Y$ are the morphisms $F X \to F Y$ in $\mathcal{D}$ that are in the image of $F : \mathcal{C} (X, Y) \to \mathcal{D} (F X, F Y)$.
Let $\mathcal{D}'$ be the category whose objects are those in $\mathcal{C}$ and whose morphisms $X \to Y$ are the morphisms $F X \to F Y$ in $\mathcal{D}$.
Then the functor $F : \mathcal{C} \to \mathcal{D}$ has an evident factorisation $\mathcal{C} \to F [\mathcal{C}] \to \mathcal{D}' \to \mathcal{D}$ where $\mathcal{C} \to F [\mathcal{C}]$ is bijective on objects and full, $F [\mathcal{C}] \to \mathcal{D}'$ is bijective on objects and faithful, and $\mathcal{D}' \to \mathcal{D}$ is fully faithful.

For your example where $F : \mathcal{C} \to \mathcal{D}$ is the forgetful functor $\mathbf{Man} \to \mathbf{TopMan}$, $F [\mathcal{C}] = \mathbf{Man}$ and $\mathcal{D}'$ is the category of smooth manifolds and continuous maps.
Note also that there are other ternary factorisation systems on $\mathbf{Cat}$. For instance, we can factor every functor as a bijective on objects full functor followed by a surjective on objects faithful functor followed by an injective on objects fully faithful functor.
Comment: The structure is already forgotten when we get to $\mathcal{D}'$. (Don't get confused by the "labelling" of the objects – as you say, it is the morphisms that are important.)
Comment: If you have two smooth structures on the same topological manifold, then you have isomorphic objects in $\mathcal{D}'$. Therefore they cannot be said to have different structures as objects in $\mathcal{D}'$.
Comment: Thank you; that was very clearly explained.

But, just to make sure, in your scheme, going from D' to D would forget both the "structure" (i.e. it strips the atlas) and the "property" (i.e it adds non-smoothable manifolds) in the same step - isn't it? (I've always been told category theory is about morphisms, not objects - so perhaps I've interpreted "structure" and "property" wrongly)
Comment: Wait, I'm confused. In $\mathcal{D'}$, are two non-diffeomorphic smooth manifolds (with the same underlying topological space) identified as one object or not?
If they are identified as one object, then $F[ \mathcal{C} ] \to \mathcal{D'}$ would be surjective on objects, not bijective on objects (refer answer); and as you say, structure is already forgotten.

If they aren't identified, of course, it is bijective on objects, but structure is not forgotten (for, how else would the two smooth structures be distinct?).
Comment: Ah! Because homeomorphisms are the isomorphisms in $\mathcal{D'}$. Got it. Thanks!


27 lines on a cubic surface - which proof is better?

Question: There is a famous fact that any smooth cubic surface has exactly 27 lines.
I am a undergraduate students who want to view some detailed proofs of this result. I know there are several different approaches to it. Can anyone recommend me a proof which is both beautiful and useful for my future math study?
Comment: Can you be more specific about what "better" means to you? For instance, are you looking for quick and snappy, or something more moderately-paced? Are there methods you'd like to favor or avoid?
Comment: Maybe you already did it. but a fun way to start is to check there is 27 lines on a particular cubic surface, for example the Fermat cubic $X^3+Y^3 + Z^3 + W^3=0$.
Comment: @KReiser Thanks for reminding me to be more specific...  I just want a proof contains some important ideas and results that can be used for further study of algebraic geometry, so I think it will not be too quick and dirty...
Comment: there is an answer here https://www.quora.com/In-Algebraic-Geometry-why-are-there-exactly-27-straight-lines-on-a-smooth-cubic-surface.
Answer: There is a question on MathOverflow for interesting results in algebraic geometry that's both enticing and accessible to undergrads, and among the answers this outline of a proof of the 27 line theorem is given.
In the comments, the author points to a more detailed presentation (page 222), which unfortunately is in Italian.
(The link provided in the MO answer is dead, but I have linked to a more recent version of the same text here.)
Another commenter points to a few other sources for some of the more technical results used in the proof.


Backbone passing a model to Router

Question: I'm developing an application for android using require js and Backbone. I have to pass a model taken from a collection via touchend event to the router. How can I do it?
define(["jquery", "underscore","backbone","handlebars", "views/CinemaView", "models/CineDati",  "text!templates/listacinema.html"],

function($,_,Backbone,Handlebars,CinemaView, CineDati, template){
  var ListaCinemaView = Backbone.View.extend({
    template: Handlebars.compile(template),
    events: {
        "touchend" : "Details"
    },
    initialize : function (){
        var self = this;
        $.ajax({
            url: 'http://www.cineworld.com/api/quickbook/cinemas',
            type: 'GET',
            data: {key: 'BwKR7b2D'},
            dataType: 'jsonp', // Setting this data type will add the callback parameter for you
            success: function (response, status) {
                // Check for errors from the server
                if (response.errors) {
                    $.each(response.errors, function() {
                        alert('An error occurred. Please Try Again');
                    });
                } else {

                    $.each(response.cinemas, function() {
                        var cinema = new CineDati();
                        cinema.set({ id : this.id, name : this.name , cinema_url : this.cinema_url, address: this.address, postcode : this.postcode , telephone : this.telephone });
                        self.model.add([cinema]);

                    });
                    self.render();
                }}
        });

    },

    events : {
        "#touchend" : Dettagli
    },

    render : function(){
        $(this.el).empty();

        $(this.el).html(template).append(
            _.each(this.model.models, function (cinema) {
              $("#lista").append(new CinemaView({
                          model: cinema
               }).render().el); }, this));

          return this;
    },

     Dettagli : function(){

        Backbone.history.navigate( this.model , {trigger: "true"});
    }

    });
    return ListaCinemaView;

});

Answer: You need to override the Backbone's navigate function as following:

var Router = Backbone.Router.extend({
    routeParams: {},
    routes: {
        "home": "onHomeRoute"
    },
    /*
     *Override navigate function
     *@param {String} route The route hash
     *@param {PlainObject} options The Options for navigate functions.
     *              You can send a extra property "params" to pass your parameter as following:
     *              {
     *               params: 'data'
     *              }
     **/
    navigate: function(route, options) {
        var routeOption = {
                trigger: true
            },
            params = (options && options.params) ? options.params : null;
        $.extend(routeOption, options);
        delete routeOption.params;

        //set the params for the route
        this.param(route, params);
        Backbone.Router.prototype.navigate(route, routeOption);
    },

    /*
     *Get or set parameters for a route fragment
     *@param {String} fragment Exact route hash. for example:
     *                   If you have route for 'profile/:id', then to get set param
     *                   you need to send the fragment 'profile/1' or 'profile/2'
     *@param {Any Type} params The parameter you to set for the route
     *@return param value for that parameter.
     **/
    param: function(fragment, params) {
        var matchedRoute;
        _.any(Backbone.history.handlers, function(handler) {
            if (handler.route.test(fragment)) {
                matchedRoute = handler.route;
            }
        });
        if (params !== undefined) {
            this.routeParams[fragment] = params;
        }

        return this.routeParams[fragment];
    },

    /*
     * Called when hash changes to home route
     **/
    onHomeRoute: function() {
        console.log("param =", this.param("home"));
    }

})

Here I have written a custom function "param" for doing the get/set of parameters you want to send.
Now to send a custom parameter you can send it like the following:

var router = new Router();
Backbone.history.start({});
router.navigate("home", {
    params: 'Your data'
});

To retrieve the data in get data inside the callback function you can write code like this:

this.param("home"); //this will return the parameter you set while calling navigate function or else will return null
Answer: Router.navigate() doesn't pass any data. It sets the url fragment and takes a couple options. See the docs here: http://backbonejs.org/#Router-navigate
My suggestion:

Use Router.navigate() to change the URL.
Use the Backbone.Events aggregator to trigger (or publish) your event and data.

So say you have a list of movies, and you have a view button. The view button publishes the model it wants shown and changes the URL fragment.
var vent = _.extend( {}, Backbone.Events ); // Create your app specific event aggregator

var ListaCinemaView = Backbone.View.extend({

    ...

    Dettagli : function(){
        vent.trigger('movie:show:request', this.model);

        Backbone.history.navigate( this.model.get('id') );
    }
}

Somewhere else in your app add a handler for movie:view:request.
vent.on('movie:show:request', showMovieDetails);

var showMovieDetails = function(model) { ... }

Lastly, check out MarrionetteJS. It uses the publish/subscribe pattern to handle communication between parts of an app. It's a really nice framework since you basically opt-in to the parts that you want to use. It's very well documented and supported. Also, its creator, Derick Bailey, is very active on Stackoverflow, so you'll get help quick.
Comment: This solution doesn't account for when someone refreshes the page once they're at http://website/model_id. You lose the reference to the model.
Comment: Thanks a lot Will, you've been very helpful! I have already checked out marionette.js and I think that I'll use that for my future application! :)
Comment: Glad I helped, Augusto. Good luck with your project.

Backbone passing a model to Router


question on function and image

Question: Consider $f: R^2-> R$ given by
$f(v,w)=(v+w)/2 +|v-w|/2$
We also had to show that $g=f$ where $g: R^2-> R$ given by
g(v,w)= v if v>=w and w if v<0
Derive with proof the image of [0,1] times [-1,1] under f.
Quite stuck with this question i think i have figured out that the image is [0,1] but not sure. Then you have to prove this so something to do with showing f([0,1] times [-1,1]) is a subset of [0,1] and show the other way but no idea reall yhow to do this. Thanks for help in advance
im ok with the g=f part just need help with the image part.
Answer: The definition of $f(v,w)$ suggests that it is just the maximum of $v$ and $w$
The image is $[0,1] $ because you can simply pick $v=0$ and run $w$ over $[0,1]$
Answer: Consider the cases $v \geq w$ and $v<w$. In the first case $|v-w|=v-w$ so $f(v,w)=v$ and in the second case $|v-w|=w-v$ so $f(v,w)=w$. This proves that $f=g$. Note that $|x|+x \geq 0$ for any real number $x$. Hence $f$ takes only non-negative values. From the form of $g$ it follows that the image is contained in $[0,1]$. To show that the image is all of $[0,1]$ just note that $g(t,0)=t$ for all $t \in [0,1]$.

question on function and image