$\mathcal{O}(Spec(A) \setminus \{x\})$, where $A$ is the local ring of the origin

Question: Let $A$ be the local ring of the origin in $\mathbb{A}^2$. I have to find $\mathcal{O}(U)$, where $U=Spec(A) \setminus \{x\}$, with $x$ is the closed point.
I solved the exercise in the following way:
$A=\{\frac{f}{g}: g(0,0) \ne 0\}$ and $\mathcal{O}(U)=A_{(0,0)}$. But $A_{(0,0)}=A$. I've done right this exercise? I think my solutions is very simplified and I'm not convinced that it's right.
Can you help me, please?
Answer: You're not quite right. The answer is that $\mathcal{O}(U) = A$. This is because the structure sheaf is basically just a sheaf of "regular functions", and functions in algebraic geometry only encode codimension-1 data. Ie, the zeros and poles of functions on a space $X$ are both closed codimension 1 subschemes. Thus, when you remove the closed (codimension-2) point $x$ of Spec $A$, you're asking for functions which are now allowed to have poles at $x$. However, because $x$ is codimension 2, this isn't enough to give you more functions (a function on 2-dimensional space never has a single pole. If it has poles, it will have poles along a plane curve). Thus, to get more functions you have to allow them to have poles at a codimension 1 subscheme (ie, at a plane curve). Note that your answer would have been correct if $A$ were the local ring of a curve.
Anyway, here's a proof:
Observe that your $U$ is the union of the (infinitely many) distinguished open sets $D(f)$ for $f\in (x,y)\subset A$.
On the other hand, for any global section $h\in\mathcal{O}(U)$. You may restrict $h$ to a global section of $D(f)$ for every $f\in (x,y)$. For any single $D(f)$, we have $\mathcal{O}(U)\subsetneq \mathcal{O}(D(f)) = A_f$, but because the $D(f)$'s for $f\in (x,y)$ cover $U$, by the gluing property of sheaves, we get that $\mathcal{O}(U)= \bigcap_{f\in (x,y)}\mathcal{O}(D(f)) = \bigcap_{f\in(x,y)} A_f$, where the intersections are taken in $Frac(A) = A_{(0,0)}$. It's clear that this intersection is just $A$.
Note that $\mathcal{O}(U)\ne Frac(A)$ because $Frac(A)$ is just the set of all rational functions $f/g$, and any such global section on $U$ should restrict to a global section of every $D(f)$ for $f\in (x,y)$. On the other hand, $1/x\in Frac(A)$, but $1/x$ isn't in $D(y)$.


Hodge theory on semi-Riemannian manifolds [reference request]

Question: I need to learn a bit of Hodge theory on manifolds and I am looking for a reference which covers the case where the metric has arbitrary signature $(p,q)$. Most books I have found seem to focus on the Riemannian case alone.
Could anyone point me in the right direction? I know some basic sheaf theory and sheaf cohomology, if that matters.
Comment: I don't know to what degree the semi-Riemannian case is salvageable, but certainly the standard approach does not work. The point is that for a Riemannian metric, the Hodge Laplacian $(d+d^*)^2$ is elliptic, but this is not at all true in the semi-Riemannian setting; an explicit calculation on $T^n$ shows that it acts on functions on $T^n$ by $\sum_{i=1}^p \partial^2/\partial x_i^2 - \sum_{j=p+1}^{p+q} \partial^2/\partial x_j^2$ which is of course not even a little elliptic. Do you have some specific reason to think that Hodge theory should work in any reasonable way?
Comment: @eyes: [Here](http://mathoverflow.net/a/132924/40804) is a more authoritative denial than I can give, by someone who thinks about this sort of question.
Comment: To be honest, I have to particular reason to expect it to work. I was just hoping that some of theory might be salvageable in the case of arbitrary signature (or at the very least Lorentzian signature). If it isn't, could you recommend a good Hodge theory text for the Riemannian case (as an answer)? I would happy to accept that.
Answer: I am extremely skeptical that one could do Hodge theory on a semi-Riemannian manifold without extreme changes, because the Laplacian in signature $(p,q)$ is $\partial/\partial x_1^2 + \dots + \partial/\partial x_p^2 - \dots - \partial/\partial x_{p+q}^2$, which is not an elliptic operator, and ellipticity is completely crucial to the Hodge theory. This is probably not the only issue, but it's certainly first that comes to mind.
A great source for Hodge theory on Riemannian manifolds in the appropriate generality (elliptic complexes of differential operators on vector bundles) is Wells, Differential analysis on complex manifolds. A different approach (less general and different in flavor) can be found in both Griffiths and Harris and Warner; both are more or less the same proof.


Backbone.js event after view.render() is finished

Question: Does anyone know which event is fired after a view is rendered in backbone.js?
Answer: I ran into this post which seems interesting
var myView = Backbone.View.extend({

    initialize: function(options) {
        _.bindAll(this, 'beforeRender', 'render', 'afterRender');
        var _this = this;
        this.render = _.wrap(this.render, function(render) {
            _this.beforeRender();
            render();
            _this.afterRender();
            return _this;
        });
    },

    beforeRender: function() {
       console.log('beforeRender');
    },

    render: function() {
        return this;
    },

    afterRender: function() {
        console.log('afterRender');
    }
});

Comment: @pilau - Refer [this](http://blog.bigbinary.com/2011/08/18/understanding-bind-and-bindall-in-backbone.html) for understanding _.bind and _.bindAll. It helped me, hope it would help you too.
Comment: Why do you need this line: `_.bindAll(this, 'beforeRender', 'render', 'afterRender');`?
Comment: I know what it does, I am inquiring about why you require using it at all, since they (the functions), are all extending the view object anyway?
Comment: Just to help clarify: To add your own functions to the model and collection, you have to use bindAll.  This is not the case for the view they are 'bound' automatically.
Comment: @JohnMoses Exactly my point, they are already part of the View object
Comment: @abritez How can I get this working if I want to pass parameters to render function? If I change the definition to ```render: function(opts)``` I can't access ```opts``` object.
Comment: If you dont use `Function.prototype.bind`, `_.bind`, or `_.bindAll`, the context of `render()` will be `window`
Answer: Or you can do the following, which is what Backbone code is supposed to look like (Observer pattern, aka pub/sub). This is the way to go:
var myView = Backbone.View.extend({
    initialize: function() {
        this.on('render', this.afterRender);

        this.render();
    },

    render: function () {
        this.trigger('render');
    },

    afterRender: function () {
    }
});

Edit: this.on('render', 'afterRender'); will not work - because Backbone.Events.on accepts only functions. The .on('event', 'methodName'); magic is made possible by Backbone.View.delegateEvents and as such is only available with DOM events.
Comment: @PHPst: The custom event being triggered is named `render`, as in `this.trigger('render');`. Where are you getting `show` from? Do you have a link to some documentation? As far as I know, there is no  Backbone event called `show`.
Comment: @PHPst Your edit completely breaks my code, you see that line `this.trigger('render');`? Well, because I'm registering `this.afterRender` on the `render` event (a custom event, not part of Backbone), `this.afterRender` will get fired after the template is rendered. I don't know why did you make that edit, by I'm reverting it. By the way, the word "show" doesn't even appear in the Backbone annotated source...
Comment: @Trip Fixed. Didn't think it would matter but apparently it doesn't work with the name of the method alone. I now have to find out why.
Comment: @PHPst: What is the purpose of your edit, i.e. changing `render` to show`?
Comment: After trying a ton of fixes, this one worked out best for me. Thanks pilau
Comment: Uncaught TypeError: Object afterRender has no method 'call'
Comment: @pilau I wonder why `render` do not work for my but `show` works. I will investigate on it.
Comment: @PHPst Great, let us know!
Comment: @GONeale Sure buddy :) The correct way is always the best way!
Answer: As far as I know - none is fired. Render function is empty in source code.

The default implementation of render is a no-op

I would recommend just triggering it manually when necessary.
Comment: @StefanSchmidt btw - try reading backbone.js source code yourself. it's quite readable.
Comment: yeah ... thats what i figured out after your post. before I was a little bit scared. kinda javascript noob :D
Answer: If you happen to be using Marionette, Marionette adds show and render events on views.  See this StackOverflow question for an example.
On a side note, Marionette adds a lot of other useful features that you might be interested in.
Answer: I realise this question is fairly old but I wanted a solution that allowed the same custom function to be called after every call to render, so came up with the following...
First, override the default Backbone render function:
var render = Backbone.View.prototype.render;
Backbone.View.prototype.render = function() {
    this.customRender();
    afterPageRender();
    render();
};

The above code calls customRender on the view, then a generic custom function (afterPageRender), then the original Backbone render function.
Then in my views, I replaced all instances of render functions with customRender:
initialize: function() {
    this.listenTo(this.model, 'sync', this.render);
    this.model.fetch();
},

customRender: function() {
    // ... do what you usually do in render()
}

Answer: Instead of adding the eventhandler manually to render on intialization you can also add the event to the 'events' section of your view. See http://backbonejs.org/#View-delegateEvents
e.g.
events: {
   'render': 'afterRender'
}

afterRender: function(e){
    alert("render complete")
},

Comment: This doesn't work. Delegate Events refer to events that occur on the dom.  Not callbacks on the view object itself.
Comment: `events` is used for `declarative callbacks for DOM events`, see [backbone/#View-delegateEvents](http://documentcloud.github.io/backbone/#View-delegateEvents)
Answer:  constructor: function(){
   Backbone.View.call(this, arguments);
   var oldRender = this.render
   this.render = function(){
      oldRender.call(this)
      // this.model.trigger('xxxxxxxxx')
   }
 }

like this  http://jsfiddle.net/8hQyB/
Comment: You do not need to overwrite the `constructor` for this.
Comment: Constructor isn't the point. you also can trigger it manual or use  jquery $.Deferred. @cept0


Erro ao deletar FK

Question: Tenho uma tabela chamada:
solicitacaoemprestimo
codemprestimo, dataemprestimo, horaemprestimo
E outra tabela chamada:
emprestados, codemprestados, dataemprestimo, horaemprestimo, fk(solicitaremprestimo_codemprestimo)
e usei esse comando:
INSERT INTO emprestados (dataemprestimo,horaemprestimo, solicitacaoemprestimo_codemprestimo);

SELECT data emprestimo, horaemprestimo, codemprestimo FROM solicitacaoemprestimo WHERE codemprestimo = '13'

DELETE FROM solicitacaoemprestimo WHERE codemprestimo = '13';

erro que esta dando:

Error Code: 1451. Cannot delete or update a parent row: a foreign key constraint fails (trabalhoclubedodvd.emprestados, CONSTRAINT fk_emprestados_solicitacaoemprestimo1 FOREIGN KEY (solicitacaoemprestimo_codemprestimo)

Só que, na hora que eu vou deletar na tabela solicitacaoemprestimo porque meu dvd foi alugado, ele não deixa, mas eu gostaria de deletar porque esse item não será mais usado por que o dvd já foi alugado... Se alguém puder me ajudar desde já eu agradeço...
Comment: Forneça mais dados , que tipo de erro ocorre , estrutura das tabelas fks , fks , triggers etc.
Comment: A coluna `solicitaremprestimo_codemprestimo` faz referência `a coluna `codemprestimo` da tabela `solicitacaoemprestimo`?
Comment: Esse erro:Error Code: 1451. Cannot delete or update a parent row: a foreign key constraint fails (`trabalhoclubedodvd`.`emprestados`, CONSTRAINT `fk_emprestados_solicitacaoemprestimo1` FOREIGN KEY (`solicitacaoemprestimo_codemprestimo`)
Comment: Sim faz referencia ...
Comment: @CarlosLeandroFerreiradeAlm conseguiu resolver essa pergunta?
Answer: Isso é intencional — a ideia de criar uma chave estrangeira é impedir que uma coluna que faz referência a um ID em outra tabela armazene um valor inválido. Se a consulta que você quer fazer fosse permitida, uma linha teria o valor 13 para a coluna solicitacaoemprestimo_codemprestimo apesar de não existir nenhuma linha em solicitacaoemprestimo com codemprestimo igual a 13.
A motivação de apagar a linha correspondente em solicitacaoemprestimo é que a semântica que você tem em mente pra essa tabela é que ela só vai guardar solicitações ativas? Considere repensar o design do seu banco de dados e deixar todas as solicitações, pra sempre, nessa tabela — se você quiser filtrar só as solicitações que ainda não foram atendidas, você sempre pode fazer
…
WHERE codemprestimo NOT IN (SELECT solicitaremprestimo_codemprestimo FROM emprestados)

(mas aí seria importante você não mais repetir as colunas dataemprestimo, horaemprestimo na tabela emprestados)
Answer: Complementando a resposta do ctgPi você poderia criar um campo booleano para informar se a solicitação já foi alugada. Por exemplo:
ALTER TABLE solicitacaoemprestimo
ADD alugado BOOLEAN

E no seu caso ficaria:
UPDATE solicitacaoemprestimo SET alugado = 1 WHERE codemprestimo = '13';

Ao invés do DELETE.
Comment: Essa solução funciona, mas eu não quis sugeri-la porque ela cria a possibilidade de você ter um registro em `emprestados` mas `alugado = 0` no registro correspondente `solicitacaoemprestimo` (ou vice-versa).

Erro ao deletar FK


How to redirect to a translatable page

Question: I have a bilingual site and I want to redirect to a custom page, which has two language versions, upon form submitting. This may be a pretty basic thing, but I am only starting to learn how to code for Drupal in PHP. This is what I tried:
$form_state['redirect'] = t('message-sent-successfully');

'message-sent-successfully' is the URL for the English version of the page. It has a different URL for the other language the site is using. In whatever language I submit the form, I get redirected to the above URL, i.e. the url doesn't get translated.
Comment: Using `node/[nid]` instead should solve this problem; the user should be redirected to the proper alias of the node, translated in the currently active language.
Comment: I just tried this and the two translations have two different node ID's which is quite a surprise to me.
Comment: Hm, I might be mistaken - will check it now quickly.
Comment: This works as I mentioned, but you need to have i18n module + globalredirect configured; will post it as an answer as there isn't enough space here.
Answer: Install i18n and enable the Translation Redirect module within.
Install Globalredirect and go to admin/config/system/globalredirect and check "Language path checking".
You can then take the user to either source or translated node, and Globalredirect will take the user to the page which is in the currently active language.

How to redirect to a translatable page


Closure of Open Balls Vs Corresponding Closed Balls in Normed Linear Spaces

Question: Let $(V,\|\cdot\|)$ be an $\mathbb{F}$ normed vector space and, for any $x \in V$ and $r>0$, let $$T=\{y \in V:\|y-x\| \leq r\}$$ and $$S=\{y \in V:\|y-x\|<r\}.$$
(a) Show that $T$ is closed and $S$ is open.
(b) If $z \in T$ and $z_n=\left(r-\frac{1}{n}\right) z$, for $n \in \mathbb{N}$, show that $\lim _{n \rightarrow \infty} z_n=z$ and hence show that $\bar{S}=T$
One can easily show $T$ is closed by showing $T^C=V-T$ is open using the basic open balls. However, I feel that we have to show that $z_n=(r-\frac{1}{n})z \in S$ whenever $z \in T$ prior to $\lim_{n \to \infty} z_n=z$.
That is, we need $\lVert (r-\frac{1}{n})z-x \rVert<r$, whenever $\lVert z-x \lVert=r,$ for each $n \in \Bbb N$. I am looking for a thread.
Comment: In (b) you should take $z_n= x+ (1-{1\over n})(z-x).$
Comment: It seems wrong, as $z_n\to rz$.and you need $z_n\to z$ and $z_n\in S.$
Comment: @Ryszard Szwarc I think the convergence of $z_n=(r-1/n)z$ is not relevant here, right?
Answer: For any $z\in T$ we need to see $z_n=x+(1-1/n)(z-x)\in S$ for every $n\ge 1$. But this can be done easily:
$$
\Vert x+(1-1/n)(z-x)-x\Vert = \Vert (1-1/n)(z-x)\Vert = (1-1/n)r <r
$$
as $\Vert z-x\Vert =r$.
Now clearly as $n\to \infty$ we have $z_n \to x+(z-x) = z$, so $z\in \overline{S}$. Thus, $T\subset \overline{S}$. As you have noted $T$ is closed. Clearly, $T$ contains $S$, so $T\supset \overline{S}$ by which we obtain $T=\overline{S}$.


Custom line item total calculation

Question: I have looked for the solution for weeks, but I have not found any. It must be very trivial that I missed.
I'm adding a line item field in addition of the default unit price and quantity called "length" in the cart view and Order. I would like to get the new calculated line item total = price * quantity * length.
Solutions that I have found so far change the line item unit price, which is not desirable.
How can I do this?
Answer: The line-item unit price is used throughout commerce and the total order amount is based on the line-item total value (quantity * unit price). There is no way to circumvent this behavior.
Better would be to add another price field to the line-item Price per length-unit. Hide the default price field and calculate the sales price as you've found in other answers.
Basically this is a pricing rule in Store > Configuration > product pricing rules where you add the event Set the unit price to a specific amount to a calculated value.

Custom line item total calculation


Adding files to a file[] statement in java

Question: Hello members of stackoverflow
I need some help with adding files from a directory to a bunch of files (File[])
So basically i want to add all the files in a directory to the following group of files:
File[] contents = {};

The user of my application will select a directory and i want that directories contents to be added to the above group of files ('contents I'm not sure how this is done because it doesn't have a simple 'add' method like an ArrayList/List does.
Any help with this would be greatly appreciated.
Thanks.
Comment: If you want to be able to easily add to a list after it's created, use a List, not an array.
Answer: Use File.listFiles():
File dir = new File("/somedir");
File[] files = dir.listFiles();

Comment: Thanks for this, didn't realize it was such a simple solution. I was trying to use a for loop to add files but this is much better :)
Comment: Taking a look at the API documentation is always helpful.
Answer:     try
    {
        File folder = new File(FOLDER_NAME);
        File[] contents = folder.listFiles();
    }
    catch(Exception e)
    {
        System.out.println("[Error] Folder not Found");
    }

Comment: Could you elaborate ?
Comment: The `File` constructor throws only a `NullPointerException` when the argument is `null`. On the other hand `listFiles` throws a `SecurityException`. None of the exceptions say anything about the file/directory not being found.
Comment: The constructor is not validating the path. From doc - It "Creates a new File instance by converting the given pathname string into an abstract pathname." So even `File f = new File("");` will execute without throwing any exception.
Comment: Nope, just checked again. It throws an exception if you have an incorrect path. Try it yourself once.
Comment: I doubt. Why do you think then `File.exists()` method is there for?


Tangent in specific point without model fitting

Question: I have a question about differential function.
When I have one database with x and y, how can I find the slope in specific point?
For example,
<code>x = c(3935, 3992, 4079, 4100, 4156, 4169, 4197, 4217, 4246, 4262, 4280, 4287, 4313, 4328, 4334, 4352, 4371, 4377, 4397, 4408, 4416, 4430, 4444, 4461, 4467, 4483, 4496, 4510, 4523, 4531, 4542, 4559, 4574, 4579, 4595, 4613, 4631, 4637, 4657, 4673, 4691, 4713, 4726, 4751, 4784, 4801, 4850, 4883, 4939, 5082)
y = c(30.75, 30.81, 30.9, 30.92, 30.97, 30.98, 31, 31.02, 31.04, 31.05. 31.07, 31.07, 31.09, 31.1, 31.1, 31.11, 31.12, 31.13, 31.14, 31.15, 31.15, 31.16, 31.16, 31.17, 31.18, 31.18, 31.19, 31.2, 31.2, 31.21, 31.21, 31.22, 31.22, 31.22, 31.23, 31.24, 31.24, 31.24, 31.25, 31.26, 31.26, 31.27, 31.27, 31.28, 31.28, 31.29, 31.3, 31.3, 31.31, 31.33)
</code>

And I want to know the slope when x=4476.8 (it is average value of x).
I know that the best way is to fit the function of x with respect to y and then differentiate it.
However, I am asking this question because I want to know if there is a way to find the tangent of a specific point without fitting the model.
Thank you!
Answer: First, we have to presume that the function is differentiable at that point, we cannot know this. And then, you can only obtain approximations.
For instance, you could take the two points $(x^1, y^1), (x^2, y^2)$ (the superscript is just an index, not a power), where $x^1, x^2$ satisfy $x^1 < x^2$, and are the two points nearest to $x=4476.8$, and then compute $d = \frac{y^2 - y^1}{x^2 - x^1}$.
Next, you could take several such pairs $((x^1_i, y^1_i), (x^2_i, y^2_i))$ near $x$, compute for each such pair a weight $w_i$ that is somehow decreasing with the increasing sum $|x^1_i - x| + |x^2_i - x|$ and then take the weighted mean of the belonging quotients:
$$
d = \sum_{i=1}^k w_i \frac{y^2_i - y^1_i}{x^2_i - x^1_i}.
$$
But maybe this already counts as "fitting a model"...


How to get current EntityManager in JPA without spring?

Question: I'm working on a homework that using JPA but without spring.
It has service layer and repository layer.
I try to begin transaction in service and call save or update from repository and then commit in service.
But how to get Current EntityManager in repository?
My cod is like this:
Service:
public void save(Entity entity){
    var em = factory.createEntityManager();
    var t = em.getTransaction();
    try {
        t.begin();

        repository1.save(entity);

        // For saving one to many relation
        repository2.save(entity.getChildEntity());

        t.commit();
    } catch (Exception e) {
        t.rollback();
    }
}

Repository:
// I don't want to pass EntityManager to method

public void save(T entity) {
    var em = ?      // How can I get EntityManager hear?

    em.persist(entity);
}

Comment: Have you tried to inject entityManager to bean?
Comment: @ScaryWombat please don't link to that site. Their tutorials and articles are really low quality, and often downright wrong (many code samples don't even compile or teach how to do things wrong).
Comment: I don't know how to inject Gurkan İlleez :(
Answer: public class EntityManagerProvider {

   private static final EntityManager entityManager;

   public EntityManagerProvider() {
      EntityManagerFactory emf = Persistence.createEntityManagerFactory("com.example.factory");
      this.entityManager = emf.createEntityManager();
   }

   public static EntityManager getEntityManager() {
       return entityManager;
   }
}

Second Approach :
public class EntityManagerProvider {

   private static final EntityManager entityManager;

   private EntityManagerProvider() {}

   public static synchronized EntityManager createOrGetEntityManager() {
        if(entityManager == null) {
           EntityManagerFactory emf = Persistence.createEntityManagerFactory("com.example.factory");
           EntityManagerProvider.entityManager = emf.createEntityManager();
           return EntityManagerProvider.entityManager;
        }

        return EntityManagerProvider.entityManager;
   }
}

You need to create entityManager once and use it everywhere. I don't know where you create factory class but you can create entityManagerProvider class after creation of factory class.
You can simply call EntityManagerProvider.getEntityManager() to receive entityManager from class.
Please note that you don't need to initialize everywhere you can do it once and use it everywhere.
SecondApproach is better you can use it simply everywhere. EntityManagerProvider.createOrGetEntityManager method will give you entityManager.
Comment: Autowire it how? There is no spring.
Comment: I read it as spring application you are right then you have to configure it. I will change answer.
Comment: I have updated my answer. You can simply get from a class
Comment: next question will be "how to get EntityManagerFactory "
Answer: In your first snippet of the service I see that you have a factory and there you create an EntityManager. So the factory exists...
Take your factory and make it accessible everywhere in your program. How?
Create a class specific only to creating the factory and the hibernate session. There you create public static getters for the fields that you need (such as the factory and EntityManager).
Example:
public class HibernateUtils
{
    public static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory()
    {
        try
        {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().configure().buildSessionFactory();
        }
        catch (Throwable ex)
        {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
        // Close caches and connection pools
        getSessionFactory().close();
    }
}

Comment: And please if your question has no connection to hibernate, remove the tag.
Comment: But my project is JPA and I want to do it with JPA. My factory is EntityManagerFactory.
Comment: Then do the same thing for your JPA implementation. You create your factory somehow right? Then create it in this helper class and make it available through static getters...
Comment: Renis1235 I removed hibernate tag But can I use JPA persistence.xml and hibernate.cfg.xml same time to resole this?
Comment: Does your first snippet of code work? Are you able to create a factory? If yes problem solved check my implementation. If no, then you have to go deeper and select a JPA implementation (such as Hibernate)
Comment: I can create factory with : Persistence.createEntityManagerFactory("my_pu");
Comment: Then perfect, do what I have done above and fetch your factory using the getters of the helper class.
Answer: In Spring, the use of Services and Repositories is a further abstraction of JPA.
If you want to use JPA without Spring, you can inject EntityManager using standard JavaEE/JakartaEE technologies, that is what Spring does under the hood.
Otherwise, if you want to do it by yourself, keep in mind that JPA is a standard for which there are a couple of implementations.
Let's take in consideration Hibernate, go to read the docs, stick with EntityManagerFactory and EntityManager instead of SessionManager (specific to Hibernate).
You can instantiate an EntityManager as:
EntityManagerFactory emf = Persistence.createEntityManagerFactory("my_PU");
EntityManager em = emf.createEntityManager();

The "my_PU" is a persistenceUnit that you need to define.
More info here: https://docs.oracle.com/cd/E19798-01/821-1841/bnbrj/index.html#:~:text=A%20persistence%20unit%20defines%20a,the%20persistence.xml%20configuration%20file.
Answer: After some time I found a safe way to get Current EntityManager in current thread.
I lust link so just sharing code that I want get your feedback and opinions.
I think in this way I can even user Aspectj too.
public class EntityManagerUtil {
    //for holding EntityManager in current thread
    private static final ThreadLocal<EntityManager> THREAD_LOCAL;

    static {
        THREAD_LOCAL = new ThreadLocal<>();
    }
    // singleton creating EntityManagerFactory
    private static class LazyHolder {
        private static final EntityManagerFactory ENTITY_MANAGER_FACTORY =
                Persistence.createEntityManagerFactory("persistence-unit");
    }

    public static EntityManagerFactory getEntityManagerFactory() {
        return LazyHolder.ENTITY_MANAGER_FACTORY;
    }

    public static EntityManager getCurrentEntityManager() {
        EntityManager entityManager = THREAD_LOCAL.get();

        if (entityManager == null) {
            entityManager = getEntityManagerFactory().createEntityManager();
            // set your flush mode here
            THREAD_LOCAL.set(entityManager);
        }
        return entityManager;
    }

    public static void closeCurrentEntityManager() {
        EntityManager em = THREAD_LOCAL.get();
        if (em != null) {
            em.close();
            THREAD_LOCAL.remove();
        }
    }
}


Android Studio - How to upgrade jetpack compose?

Question: I am currently using Android studio (2021.2.1 Patch 2). On choosing empty compose activity, the compose version being used is 1.1.0-beta01 .How can I upgrade it to 1.2.0-beta01 as the earlier one gives error while using LazyVerticalGrid? I am beginner to android. Any help would be greatly appreciated.
Here is the app/build.gradle file of the project :
plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
}

android {
    compileSdk 32

    defaultConfig {
        applicationId "com.example.courses"
        minSdk 21
        targetSdk 32
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables {
            useSupportLibrary true
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
    buildFeatures {
        compose true
    }
    composeOptions {
        kotlinCompilerExtensionVersion compose_version
    }
    packagingOptions {
        resources {
            excludes += '/META-INF/{AL2.0,LGPL2.1}'
        }
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation "androidx.compose.ui:ui:$compose_version"
    implementation "androidx.compose.material:material:$compose_version"
    implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
    implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.1'
    implementation 'androidx.activity:activity-compose:1.3.1'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
    debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"
    debugImplementation "androidx.compose.ui:ui-test-manifest:$compose_version"
}

Toplevel build.gradle file :
buildscript {
    ext {
        compose_version = '1.1.0-beta01'
    }
}// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
    id 'com.android.application' version '7.2.2' apply false
    id 'com.android.library' version '7.2.2' apply false
    id 'org.jetbrains.kotlin.android' version '1.5.31' apply false
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

I have tried changing compose version in toplevel build.gradle file to 1.2.0-beta01 but the build of the project fails.
Please specify in comments if you need some more information.
Thanks
Comment: Try the same with `1.3.0-beta02`
Comment: How did you solve? Can you tell me?
Answer: Without seeing the compilation error message I can only guess at what might be the cause. But I see a couple of things that might give you problems.
The Compose Compiler for 1.2.0-beta01 requires Kotlin Plugin version 1.6.21 See Compose Kotlin Compatibility Map
Additionally, from version 1.2.0 onwards they've introduced independent versioning for Compose Compiler from the rest of the Compose libraries, meaning that kotlinCompilerExtensionVersion needs to point to a different version. As of right now the latest compiler version is 1.3.1 which needs kotlin plugin version 1.7.10.
Try these changes.
ext {
    compose_version = '1.3.0-beta02' // or 1.2.1 if you want the latest stable version
}

composeOptions {
    kotlinCompilerExtensionVersion "1.3.1"
}

plugins {
    // others omitted
    id 'org.jetbrains.kotlin.android' version '1.7.10' apply false
}

Comment: As far as I know there is no way to edit the 'new project' templates. I'm on the latest Android Studio Electric Eel Canary 10 preview build and the 'empty compose activity' templates (they added another one for Material 3) there start with compose version 1.2.0 which is already out of date. These new libraries have so frequent updates that trying to keep on top of it is probably more trouble than it's worth.
Comment: Awesome!! Apart from the above changes, I had to change compileSdk to 33 (it needs at least 33) and it works. The compose kotlin compatibility map was really useful. Thanks!  One more thing, the changes that I am making are applied only to that project. Is there a way to make these changes global? I mean creating a new project should start with that compose version.
Answer:
If anyone wants to read about the independent versioning for Compose Compiler from the rest of the Compose libraries, as mentioned in the previous answers. You can find the release notes HERE


eclipse error with android: id cannot be resolved or is not a field

Question: I just started playing around with android development, and already with just an attempt at making a button, I have encountered a problem.
The error I'm given in the following code is right on "R.id.button1".
It says id cannot be resolved or is not a field.
Do I need to manually reference every single object I make in the layout xml file? I found that this did work, but it does seem to be a bit much for every button I want to make...
package com.example.helloandroid;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class HelloAndroid extends Activity {
    /** Called when the activity is first created. */

 private Button button1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        button1 = (Button)findViewById(R.id.button1);
        button1.setOnClickListener(new OnClickListener()
        {
         public void onClick(View v)
         {
          finish();
         }
        });
    }
}

Answer: I've been wasting a lot of time (two weeks) because of the same problem until I discovered the problem wasn't mine but Eclipse's.
I guess there's a lot of people with the same problem.
Just try this: Save your project, close Eclipse and then open it again. So simple.
Answer:

Do I need to manually reference every single object I make in the layout xml file

Yes, otherwise you won't be able to do anything with those views. It's not that bad actually. So, each time you create a view in your XML, and you want to reference it, put an ID:
<View
    android:id="@+id/the_id"/>

And then, from your code you can reference it using the R class. You can type, in the example, R.id.the_id and then Ctrl+Shift+O to make Eclipse auto import the needed files.
You can speed up your productivity by using frameworks like Roboguice; I think it's for lazy people, though.
Answer: This answer is not applicable to this question (looking at code you have provided). Just adding it if someone else stumbles here and above mentioned answers do not help.
If cleaning (Project --> clean) doesn't helps or saving and restarting eclipse doesn't help either, check for the following incorrect import.
import android.R;

Which Eclipse sometimes add by mistake on auto-import (Ctrl+Shift+O).
Remove that line (import) and it's done :D
Answer: Following this EXCELLENT tutorial , I encountered the same problem.  After reading Carmello's answer (Sept 17, 2011.  07:23)  I simply clicked File->Save All, and voila, 'button0' was automagically defined, and even syntax highlighted.
Answer: If "R.id.button1" is not defined, then you'll get a compile error, just as you saw.  If you don't define this in the layout, then it won't be defined.
You don't have to specify every object you create in the layout, but you do if you try to reference it from "R.*".  You can manually create buttons and other objects that are not specified in the layout.
Answer: I ran through the same issues for time being. Plz, do not forget to define as follows:
<View
android:id="@+id/button1" />

if you are using the id in your .java class.
Button b =(Button) findViewById(R.id.button1);

Being said that, the id defined in xml file must match with the id in findViewById().
Answer: Go to the 'R.java' file under the 'gen' folder and check whether your 'button1' is present under the class 'id'.If not,then this could be the reason you got that error.When you use the statement " R.id. " make sure that the  is present under the appropriate class,in this case under  the 'id' class.
Answer: R.id is a generated object that assigns int numbers to resources. Try this go to your gen/mypackage/R.java and delete the file. As you can see it is re-generated. This file provides static references where as the context is more of the dynamic state of your app. If you have syntax errors that will prevent automatic re-generation of that R.java file so you will get lots or R. errors. As everyone else has said you can click save all icon or ctl+shift+s on windows. You can clean the project project/clean and that will clean up 95% of those exceptions. Yes eclipse is buggy that way but netbeans does not support android that well. this link may help
Good luck
Answer: Do these things,anyone of this will help you

Project -> Clean,
Right click -> Fix Project Properties
Restart Eclipse
make some fake modification in manifest and save
check your console for any error message
check your drawable folder, check the image names satisfy the rules


Remove some default created fallback routes

Question: In CakePHP 3 the default behavour is DashedRoutes, which I am happy with. However, in some instances, I want to replace the routes with my own custom routes and remove the default created routes. My routes file looks like this:
<?php
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;
use Cake\Routing\Route\DashedRoute;

Router::defaultRouteClass(DashedRoute::class);

Router::scope('/', function (RouteBuilder $routes) {
    $routes->registerMiddleware('csrf', new CsrfProtectionMiddleware([
        'httpOnly' => true
    ]));

    $routes->applyMiddleware('csrf');

    $routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);

    $routes->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']);

    $routes->connect('/register', ['controller' => 'Users', 'action' => 'register']);
    $routes->connect('/login', ['controller' => 'Users', 'action' => 'login']);
    $routes->connect('/logout', ['controller' => 'Users', 'action' => 'logout']);

    $routes->fallbacks(DashedRoute::class);
});

In this case, I want the following routes to not work and basically return a 404 error:
/users/login
/users/logout
/users/register

How would I 'disconnect' these routes?
Answer: You probably can just set another route for /users/* that goes to a 404-redirect function, basically adding this to the route:
$routes->connect(
    '/users/*',
    ['controller' => 'Users', 'action' => 'serve404']
);

And then this to the UsersController (or if you want AppController for later reuse):
public function serve404(){
    throw NotFoundException();
}

Comment: There is various workarounds, but was hoping for a built in solution to deleting a route. I'll keep this in mind. Thanks.


Abraham Wald survivorship bias intuition

Question:
During World War II, the statistician Abraham Wald took survivorship bias into his calculations when considering how to minimize bomber losses to enemy fire. Wald noted that the study only considered the aircraft that had survived their missions; any bombers which had been shot down or otherwise lost had logically also been rendered unavailable for assessment. The holes in the returning aircraft, then, represented areas where a bomber could take damage and still return home safely. So Wald proposed that the Navy reinforce areas where the returning aircraft were unscathed, since those were the areas that, if hit, would cause the plane to be lost.

So here's the thing that comes to mind: From what intuition did Wald draw such an idea? Because as a statistician, I assume that also for the rigor of his work, he very probably had to demonstrate through mathematical proofs that in fact it was necessary to reinforce the armour exactly where the holes are not, and not simply force the armour first and then observe if that would resulte positive.
Was his idea born from some formula? From what pattern of thought could he do just the opposite of what all his statistical colleagues had thought? For one thing to me to have this insight intuitively, and for another thing it is to be able to describe it mathematically.
Comment: Can you *please give the source of the image*, because it is a wonderful illustration that I would love to use in my future teaching on this subject.
Comment: @Ben-ReinstateMonica, the image appears to come from the [Wikipedia page](https://en.wikipedia.org/wiki/Survivorship_bias).  The image caption says, "Image shows hypothetical data" (alas).
Comment: Is that a historical image or just an illustration?
Answer: Wald wrote his analysis in a set of eight technical memoranda for the Statistical Research Group (SRG), and these documents have been published by the Centre for Naval Analysis, so you can actually read them and see exactly what he did in his written work.  The original memos can be found here and a good summary and analysis of his work on survival of aircraft is set out in Mangel and Samaniego (1984).  If you read this paper and the accompanying technical memos you will see that Wald did indeed develop a theoretical model of aircraft survival to make his conclusions.
Wald's analysis covered multiple problems, starting with estimation of the survival probabilities for aircraft based on the number of hits to those aircraft, and then proceeding in more detail to estimation based on the number and location of the hits.  His method goes essentially like this.  For any plane that leaves on a bombing run, there is a distribution for the number of hits that plane will take.  For any given number of hits there is an associated survival probability; a plane with no hits is assumed to survive with probability one, and the conditionl probability of survivial from each hit is some positive probability.  Based on this, it is possible to use data on the returning planes to estimate the conditional probabilities of survival for each hit.  (Any plane that does not return is assumed to have been hit at least once, and is missing data.)
To deal with different probabilities for hits to different locations, Wald expanded his model to divide the plane into a finite number of locations, and expanded the model so that there is an unknown conditional probability of survival for each hit to each location.  Wald assumed that the conditional distribution of hits to specific locations (given the total number of hits) was fixed.  He advanced the view that this could be determined experimentally within the military research centres by firing dummy bullets at real aircraft.  Given assumed values for these probabilties (based on independent experiments), and some sensible statistical independence assumptions, you can then use the data on the number and locations of hits on returning planes to estimate the conditional probabilities of survival for each hit on a particular location.  (Again, any plane that does not return is assumed to have been hit at least once, and is missing data.)  If you formulate a model like this, the phenomenon under consideration here will emerge --- i.e., the more hits observed on a particular location, the higher the estimated survival probability for hits on that location will be.  Thus, the parts of the aircraft showing the lowest survivial probability for hits will be those that have the lowest number of hits in the returning planes (relative to the probability of being hit in that location).
Wald's technical memoranda on this subject give specific formulae for his models and estimation methods for the unknown conditional probabilities.  Nevertheless, it is not necessary to understand the technical details to understand his basic insight that areas of the plane exhibiting low numbers of hits (on the returning planes) are actually the most vulnerable parts.  The reason this story is so wonderful is that it illustrates a counter-intuitive problem involving missing data where the intuitive answer for most people is the opposite of the correct answer.  I have used this problem as a teaching example in statistics seminars a number of times, and when asked their advice, the audience inevitably advise that more armour should be attached to the parts of the planes that showed the most damage in the data.  When they are informed of Wald's opposite advice, and the reasoning for it, they are usually very impressed and realise their error.
Finally, with regard to the actual folk legend that has emerged around this, I am not aware of any evidence showing exactly what conversations Wald had with the military, what he said, or who disagreed with him (or was surprised by his advice).  However, in the versions of the story I have heard, it was not other statisticians he was disagreeing with, but military officials who lacked the statistical training needed to have the intuitively correct answer to this missing data problem.  In any case, it is a brilliant story about a brilliant man.
Comment: @BryanShalloway: Sorry for the long delay in responding; I just noticed this comment.  I'm not aware of any ```R``` package specifically for this, but it would essentially be a kind of hierarchical survival model.
Comment: Do you know of any R or other statistical packages that can be used to apply his methods? E.g. picture you take the titanic dataset -- get rid of all the attribute information associated with those who died. How would Wald build a model that predicted surviving? (Is there a software package that implements this...?)
Answer: I thank all those who have had their time bringing an answer.
In the meantime, I have been looking for more on the subject and found his article with the intuitions and mathematical proofs. Follow this link:
https://apps.dtic.mil/dtic/tr/fulltext/u2/a091073.pdf

Really a remarkable statistician!
Comment: Nice work finding the memos (+1).  I have updated my own answer to add the link.
Answer: I think it is just that Abraham Wald was a clever man and an acomplished statistician, and saw that aircraft observed were not a random sample, but rather a sample self-selected by survivorship.
I do not think that a "mathematical proof" can be given that certain concrete areas need reinforcing. Rather what Wald did is a sensible descriptive analysis of the data at hand, supplemented with sound statistical judgement. I imagine that when he proposed to reinforce areas with no impacts, subject-matter specialists looked upon those areas and confirmed that they were the critical ones to protect.
Comment: This answer does not appear correct to me.  Wald's memoranda go far beyond descriptive analysis; they include models for estimating the conditional probabilities of survival based on hits to areas of the plane.  His models seem to me to constitute "proof" of the phenomenon (so far as statistical models ever do this.).  All Wald's memos on this are published, so there is no need to speculate on what we imagine his reasoning might have been.
Comment: On absence being informative as well as presence, see e.g. https://bigthink.com/artful-choice/lessons-from-sherlock-holmes-pti-paying-attention-to-what-isnt-there
Comment: I have not read the memoranda you mention: I know this story second hand, from one of his students (who was in turn one my professors).  If you have read said memoranda and they say what you say,  I gladly accept your correction. I did not say that Wald's work was only descriptive, but rather that built on clever description.  Let me point also that the question asked about what may have led Wald to reason along the lines he reasoned ("From what intuition did Wald draw such idea?") on which I think it is fair to speculate.
Comment: An additional (and most important) point is that I think no "mathematical proof" can be given that a certain area needs reinforcing. One may offer evidence that damage in certain parts appears to make survival difficult of impossible, much as you can find evidence that a certain drug protects from coronavirus. This is no "mathematical proof" that you have to take said drug (maybe another one would be preferable). It is only evidence for the subject-matter specialist to reflect and decide.
Comment: I think you can still show rigorously that the probability of be downed if you are hit in certain places is higher than in other. Thus you should reinforce those places.


When does this integral exist?

Question: I try to learn about Sobolev-spaces defined with tempered distribution.

I would like to understand for what  $s\in\mathbb{R}$ does
  $$\int (1+|\xi|^2)^s \mathrm d\xi\,, \qquad \xi \in \mathbb{R}^n$$
  exist?

I think this could be helpful to understand Sobolev-spaces in this context.
Can anybody help me with this? I am thankful for every help.
Comment: You can use `\quad` and `\qquad` for horizontal spacing, too=)
Answer: You function is continuous everywhere, hence you need to study what happens when $|\xi|\to\infty$. By comparison with $|\xi|^{2s}$ you deduce easily that for $2s+n < 0$ the integral converges and for $2s+n\ge0$ the integral diverges. Polar coordinates help, too.

When does this integral exist?


What happens to $\frac{|x-3|}{x}<2$ for $x\geq 3$?

Question: I need to find real numbers $x$ that satisfy the inequality
$\frac{|x-3|}{x}<2$
My analysis goes like this:
Case 1) $x<0$
Then, $\frac{|x-3|}{x}<0<2$, so all negative $x$ satisfy the inequality.
Case 2) $0<x<3$
Then, $\frac{3-x}{x}<2$, and as $x>0$, we can say $3-x<2x\implies x>1$
$\therefore x\in(1,3)$ satisfies the inequality, but $x\in(0,1]$ does not.
This is all fine, but my issue is in the 3rd case.
Case 3) $x\geq 3$
Then, $\frac{x-3}{x}<2$
$\iff x-3<2x$
$\iff x>-3$
What does the final line tell us about the $x\geq 3$ case?
When I plot $\frac{|x-3|}{x}$, I can see that all $x\geq 3$ satisfy the inequality, but why does the $x>-3$ result tell us this?
Comment: It doesn't. You must take the intersection of both interval.
Comment: @ChristianF I see what you mean. The intersection of $x\geq 3$ and $x>-3$ is simply $x \geq 3$. Indeed, I've applied this same logic in case 2. So in conclusion, the solution set is $\{x\in \Re : (x<0)\cup  (x>1)\}$.
Comment: The final line tells you that the inequality holds for every $x\geq 3$. (which makes sense as you have a fraction with larger denominator, $x-33$ then the inequality holds" and clearly, the "addition" doesn't matter.
Comment: @HumptyDumpty True
Answer: Any way, you don't have to consider 3 cases. If $x>0$ you get $$|x-3|<2x$$ so $$-2x<x-3<2x$$...
Answer: The logic might be more clear if you reverse the steps in the $x\ge3$ case, keeping only the reverse direction of the if-and-only-if double arrow:
$$x\ge3\implies x\gt-3\implies x-3\lt2x\implies{x-3\over x}\lt2\implies{|x-3|\over x}\lt2$$
where the first $\implies$ is trivial, the second is easy, and the final two depend on the assumption $x\ge3$ (which implies $x\gt0$ and $x-3=|x-3|$ for those two steps, respectively).
Answer: You get two cases: At first:$$x>0$$ and $$x\geq 3$$ so we get $$x-3<2x$$
Case two: $$x<0$$ and $$x<3$$ so we get $$-(x-3)>2x$$
And we get $$x<0$$ or $$x>1$$


LoadLibrary is not working

Question: I have created an *.exe and *.dll for my project.
I have provided all the correct path and data.
Myexe.cpp:
#include "stdafx.h"
#include <Windows.h>

int _tmain(int argc, _TCHAR* argv[])
{
    HMODULE hInstLibrary = LoadLibrary(L("..\\Debug\\LoadDLL\\LoadDLL.dll"));// I have checked with complete path as well.
    if(hInstLibrary)
    {
        printf("Hello World");
    }
    return 0;
}

MyDLL.cpp:
#include "MyDLL.h"
#include <stdio.h>

    MyDLL::MyDLL(void)
    {

}

MyDLL::~MyDLL(void)
{
}

extern "C" __declspec(dllexport) void HelloWorld()
{
    printf("Hello DLL");
}

MyDLL.h:
#pragma once
class __declspec(dllexport) MyDLL
{
public:
    MyDLL(void);
    ~MyDLL(void);
};

extern "C" __declspec(dllexport) void HelloWorld();

I have tried providing the complete path also. But it is still failing. The hInstLibrary is setting to 0x00000. I tried in Release mode too but the problem still lies there.
But when I have tried with:
HMODULE hInstLibrary = LoadLibrary(_T("C:\\Windows\\System32\\aeinv.dll"));

it does load the DLL. So, please help me where is it going wrong. The DLL gets build properly, there is absolutely no error in building DLL. Then why am I facing this problem??
Is there any setting need to be done for Debug.
Answer: You need to call GetLastError to find out what went wrong.
Edit:
You got 0x7e, which means:

ERROR_MOD_NOT_FOUND
126 (0x7E)
The specified module could not be found.

Your path is wrong. You need to fix that.
Comment: When I have `wprintf(L"Format message failed with 0x%x\n", GetLastError());`. It prints `Format message failed with 0x7e`
Comment: When I have taken `LPCSTR str = "..\\Debug\\LoadDLL\\LoadDLL.dll"` the passed the `str` into `LoadLibrary` then it did work. So, where exactly was it going wrong?
Comment: You probably used unicode when your project was compiled for non-unicode, although that would have generated warnings. If you want to chose later if your program uses unicode, you can use the _T macros as described in another answer.
Answer: Inspect your executable with DependencyWalker and the profile it from there. You'll get a better picture as to why your dll fails to load and how the dependency tree looks like.
When you start profiling (F7) make sure that 'Log LoadLibrary function calls' is checked.
You can also check Dynamic-Link Library Search Order to see if anything is applicable to your specific case.
Answer: What's L in L("..\\Debug\\LoadDLL\\LoadDLL.dll")?  You probably meant L"..\\Debug\\LoadDLL\\LoadDLL.dll" without the parentheses for a wide-char string.  I'm not sure how that compiles unless you created an L macro?  The _T(x) macro expands to L ## x (in wide-char builds), by the way...

LoadLibrary is not working


Back_inserter or push_back

Question: Just a quick question - Which is better to use to add a string to the end of a vector<string>, back_inserter or push_back? mainly, which works faster(I'm working with a huge data, so the marginal difference is actually important) and what are the main differences?
Comment: `back_inserter` is just a function template that constructs a `back_insert_iterator` for a qualified collection based on its type, and is generally used for iteration algorithms to populate a collection. The resulting iterator invokes `push_back()` when inserting elements, but the two (`back_inserter(col)` and `coll.push_back()`) are not equivalent in either type or function.
Comment: why not profile it by yourself?
Comment: Time both versions and see for yourself.
Comment: They are not comparable :D
Answer: The two are not equivalent. You use std::back_inserter for example when you need to pass an input iterator to an algorithm. std::vector<std::string>::push_back would not be an option in this case. For example
std::vector<std::string> a(100, "Hello, World");
std::vector<std::string> b;
std::copy(a.begin(), a.end(), std::back_inserter(b));

Back_inserter or push_back


MVN Install - Erro Java Home

Question: root@vps145918:/opt/Bot# mvn install
The JAVA_HOME environment variable is not defined correctly
This environment variable is needed to run this program
NB: JAVA_HOME should point to a JDK not a JRE

Informações do Sistema:
Debian 8 - 64 Bits
OVH

O quê fazer?
Answer: Aparentemente faltou definir a variável de ambiente $JAVA_HOME, siga os passos abaixo:

Abra o terminal e execute o comando find /usr/lib/jvm/java-1.x.x-openjdk
Em seguida sudo vi /etc/profile
Pressione "i" para entrar no modo de inserção do vi
Adicione no arquivo as linhas abaixo:
export JAVA_HOME="Adicione aqui o diretório encontrado pelo comando no passo número 1"
export PATH=$JAVA_HOME/bin:$PATH
Pressione "Esc" em seguida :wq!
Execute o comando source /etc/profile para aplicar as mudanças no seu shell.
Tente executar o comando mvn -version para averiguar se tudo funcionou corretamente

MVN Install - Erro Java Home


What is the best way to detect trends in item popularity?

Question: Assume I have kept track of the number of views per page and I want to show trending pages.
I am thinking about applying some statistical tests like Log-likelihood/chi-squared to detect breakthroughs from the popularity expectation.
Can somebody point me to some resources related to this matter?
Answer: One simple approach is to use an exponentially weighted moving average.  This tends to emphasize recent data, while retaining some history.
For example, each hour you could update the estimated popularity $y$ for a page by updating your estimate as follows: $y := (1-\alpha) y + \alpha x$, where $x$ denotes some measure of its popularity over the past hour (e.g., number of visits) and $\alpha$ is a constant that determines how rapidly the estimate discounts older values.
You could then sort pages by their estimated popularity.  Pages with a high estimate are "trending".
Answer: There is the Cochran-Armitage trend test for linear models but along the lines of D.W.s answer you can view the data as a time series.  The generalization of exponential smoothing is the ARIMA model structure.  The approach to identify trends in ARIMA models is to calculate the estimate of the autocorrelatioon function.  If the function is positive and slowly declining that is an indication of trend (informal).


Does the Crystal Report 10 runtime bundled in VS 2008 needs .Net Framework 3.5?

Question: Do I need to install .NET Framework 3.5 for my deployment if I use VS2008's Crystal Report Viewer - version 10?
My target deployment is just for .NET Framework 2.0 and I have to install with the minimum framework requirements. can I use the previous Report Viewer (VS2005's) in VS2008?
Answer: You should run the Crystal Reports MSI after your Application setup.
The MSI can be found in the following locations:

Crystal Reports Basic for Visual Studio 2008 (x86)
C:\Program Files\Microsoft
  SDKs\Windows\v6.0A\Bootstrapper\Packages\CrystalReports10_5\CRRedist2008_x86.msi
Crystal Reports Basic for Visual Studio 2008 (x64)
C:\Program Files\Microsoft
  SDKs\Windows\v6.0A\Bootstrapper\Packages\CrystalReports10_5\CRRedist2008_x64.msi
Crystal Reports Basic for Visual Studio 2008 (IA64)
C:\Program Files\Microsoft Visual
  Studio 9.0\Crystal
  Reports\CRRedist\IA64\CRRedist2008_ia64.msi

Taken from this MSDN Article


C# ListView search item without clear list

Question: I have winform project on C# platform. I have listview and textbox as you see in pic below.
I want to reorder the list according to the text value entered by the user.
I researched before ask here, I generally saw solutions based on removing and re-adding all units to listview again. I don't want to do that because my listview has too many items with pictures so removing and re-adding items causes listview to work slowly.
What I want is that,  when the user enters characters in the textbox, the items which starts with this characters, bring this items the top of the list something similar google search system.
I tried the codes below but this send the item at the end of the list even though i chose index 0.
Thanx.

private void txt_search_TextChanged(object sender, EventArgs e)
        {
            string text = txt_search.Text;
            var item = listView1.FindItemWithText(text);
            if (item != null)
            {
                int index = listView1.Items.IndexOf(item);

                if (index > 0)
                {
                    listView1.Items.RemoveAt(index);
                    listView1.Items.Insert(0, item);
                }
            }
        }

Comment: Consider using the ListView in _Virtual Mode_ for better performance when you have a large list to display. You'll be able to do better filtering/sorting routines because you have a control over the data is being displayed.
Comment: @Fixations answer worked for me. Thanx for attention.
Answer: ListView is sorted using the .Sort() function, not sure what the default behaviour is, but I think you need a custom comparer.
Here is an example implementation by (ab)using the ListViewItem.Tag.
Custom Comparer:
private class SearchCompare : Comparer<ListViewItem>
{
    public override int Compare(ListViewItem x, ListViewItem y)
    {
        if (x?.Tag != null && y?.Tag != null)
        {
            return x.Tag.ToString().CompareTo(y.Tag.ToString());
        }
        return 0;
    }
}

Initializing the ListView:
var items = new[]
{
    "1 no",
    "2 yes",
    "3 no",
    "4 yes"
};
foreach (var item in items)
{
    listView1.Items.Add(item);
}
listView1.ListViewItemSorter = new SearchCompare(); // custom sorting

And ofcourse the text changed event handler:
private void textBox1_TextChanged(object sender, EventArgs e)
{
    string text = textBox1.Text;
    foreach (ListViewItem item in listView1.Items)
    {
        if (item.Text.IndexOf(text, StringComparison.InvariantCultureIgnoreCase) > -1)
        {
            item.Tag = "a"; // a is sorted before b
        }
        else
        {
            item.Tag = "b"; // b is sorted after a
        }
    }
    listView1.Sort();
}

Typing "yes" in the search textbox will sort items 2 and 4 in front of items 1 and 3.
Comment: Firstly, thanx for attention and your time. It is worked but i removed [AllowNull]. because app can not define it. If I do this, will it cause problems in the future? (see pic) [link](https://ibb.co/6gQy34n)
Comment: Those are custom annotations for code profiling purposes, i dont even notice them anymore. I editted the question and removed those aswell.


Retrieving the last values from the database - should the results be sorted?

Question: The database stores the currency exchange rate on a given day. Each day, one currency exchange value is collected and stored in the database as:

ID (int, AI)
VALUE
DATE

1
2.5
20.01.2021

2
2.7
21.01.2021

3
2.6
22.01.2021

If I would like to calculate the average exchange rate from the last 10 days, should I first sort the data by date and only retrieve the last 10 records when downloading the data, or is it enough to download the last 10 records from the database without sorting?
Comment: SQL Tables represent unordered sets. So you need to sort.
Comment: Probably depends on exact RDBMS you're using but none of the ones I used have any written/documented order in which they return rows without explicit order requested.
Comment: No, does not depend except on VERY special things - unless you order, you are at the mercy of query optimization. It is undefined and any different order for whatever reason - is valid. You basically rely on undocumented behavior. This is essential basic SQL: Want an order, query with an order.
Comment: Why is this question tagged c#, or asp.net?
Answer: You can simply do in SQL Server database
SELECT TOP 10 AVG(VALUE) AS AverageRate
FROM YourTable
ORDER BY Id DESC

Concept should be same in other relational databases.
Comment: 1.That's not what OP wants, 2.The DBMS is still unknown
Comment: @BarbarosÖzhan I have mentioned that in my answer.
Comment: Why did you add `NOLOCK`, do you know that it can give you completely incorrect data? You did not even have the correct syntax. This is also not going to work as OP wants, because only one `AVG` value is returned, unless you use `GROUP BY`
Comment: What was wrong with the syntax? Can you please tell? OP has mentioned that he wants average. @Charlieface
Comment: `FROM YourTable WITH (NOLOCK)` would have been correct syntax if you *really* needed `NOLOCK`, the other syntax is deprecated (see the [docs](https://learn.microsoft.com/en-us/sql/t-sql/queries/hints-transact-sql-table?view=sql-server-ver15#arguments)). This query anyway gets incorrect results because `TOP` is calculated after the aggregation on the whole table. You need a CTE or derived table here
Comment: Without braces also works, I use it very frequent. I have run the query in Sal server and it works as expected @Charlieface
Answer: Tables (and table expressions such as views and CTEs) in SQL represent unordered sets. To get data in a particular order, you must specify an ORDER BY clause.
In fairly generic SQL you can do
SELECT AVG(VALUE) AS AverageRate
FROM (
    SELECT VALUE
    FROM YourTable AS t
    ORDER BY Id DESC
    OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY
) AS t

In some RDBMSs, instead of OFFSET FETCH, you use either LIMIT or TOP to achieve the same effect. You still need ORDER BY.
Comment: There is no "end of the table", a table represents an unordered set. It is certainly possible that you have an index on that column and that most of the time it will read it in index order, but there is **absolutely no guarantee** that this will always be the case. For example, it may use a different index, or it may parallelize, or it may hash join it with something else. If you want it in a particular order you **must** specify. Bear in mind that if you have an index then no sorting actually takes place, the server will just start at the end and read backwards.
Comment: Charlieface, thank you for your answer. I noticed that if I add a new value to a table and the identifier is, for example, of the Guid type, it is added to the table in alphabetical order. However, if the table key is of the int AI type, will there be any possibility that the newly added record will not end up at the end of the table? If, in the case of int AI keys, the new element always goes to the end of the table, why sort the data when retrieving it, if it is known that the last 30 records will always be the latest records?
Answer: You can do it in both ways.
If you're using SQL with Dapper or ADO.NET, then you can write a query.
It should be sorted if you need the last 10 values
SELECT TOP 10 AVG(your value) AS average
FROM YourCurrencyExchangeTable
ORDER BY DATE DESC

If you're using EntityFrameWorkCore, you can write
var avg = db.yourDbContext
        .Where(c => c.Date >= tenDaysAgoDate)
        .Average(c => c.yourValue)

I hope my answer helps :)
Answer: Basically you have to sort first ( on date) and then get the last 10 values, so you're on the right track.
Comment: Hey, I see you are new on SO, welcome! Your answers to this question does not provide much information, so it would be better posted as a comment! If you can find some info on how to write better answers [here](https://stackoverflow.com/help/how-to-answer), hope it helps!


Rotate SVG without misplacing the image

Question: I have this svg "code"
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="34">

<path transform="rotate(0 10 17)" fill="#6699FF" d="M 0.06,25.03 C 0.06,25.03 4.06,20.97 4.06,20.97 4.06,20.97 3.97,5.06 3.97,5.06 3.97,5.06 9.94,0.03 9.94,0.03 9.94,0.03 15.78,5.09 15.78,5.09 15.78,5.09 16.03,21.06 16.03,21.06 16.03,21.06 19.94,25.00 19.94,25.00 19.94,25.00 19.97,30.09 19.97,30.09 19.97,30.09 10.06,20.97 10.06,20.97 10.06,20.97 10.05,23.00 10.05,23.00 10.05,23.00 19.91,32.03 19.91,32.03 19.91,32.03 19.94,33.97 19.94,33.97 19.94,33.97 17.97,33.97 17.97,33.97 17.97,33.97 10.03,26.94 10.03,26.94 10.03,26.94 10.05,29.01 10.05,29.01 10.05,29.01 15.94,34.00 15.94,34.00 15.94,34.00 12.00,33.94 12.00,33.94 12.00,33.94 10.00,32.00 10.00,32.00 10.00,32.00 8.00,34.03 8.00,34.03 8.00,34.03 4.00,34.00 4.00,34.00 4.00,34.00 9.97,29.01 9.97,29.01 9.97,29.01 9.97,26.94 9.97,26.94 9.97,26.94 2.00,33.96 2.00,33.96 2.00,33.96 0.00,33.98 0.00,33.98 0.00,33.98 0.02,32.00 0.02,32.00 0.02,32.00 9.96,23.00 9.96,23.00 9.96,23.00 9.95,20.98 9.95,20.98 9.95,20.98 0.00,30.00 0.00,30.00 0.00,30.00 0.06,25.03 0.06,25.03 Z" />

<path transform="rotate(0 10 17) translate(0 0)" fill="white" d="M 8.04,17.04 C 8.04,17.04 7.98,11.04 7.98,11.04 7.98,11.04 5.00,11.00 5.00,11.00 5.00,11.00 10.00,6.04 10.00,6.04 10.00,6.04 14.96,11.02 14.96,11.02 14.96,11.02 12.02,11.04 12.02,11.04 12.02,11.04 12.02,17.04 12.02,17.04 12.02,17.04 8.04,17.04 8.04,17.04 Z" />

</svg>

its a vessel with a arrow inside.
I am trying to rotate this "picture", (i need to rotate it on 360 degree).
When I change rotate(0 10 17) to rotate(90 10 17) it gets cut away. That's because i don't rotate it from the center of the image.
I tried using this formula to calculate the center but i couldn't manage to do it myself
x = 34; y = 20; o = 4.71238898 //(degrees to radiants) ;
a = Math.abs(x * Math.sin(o)) + Math.abs(y * Math.cos(o));
b = Math.abs(x * Math.cos(o)) + Math.abs(y * Math.sin(o));

I am really bad with those math/svg problems, i am hoping someone can assist me.
Thanks
Comment: `Math.toRadians(degrees)` might a tip.
Answer: The centre of rotation is correct. But the trouble is now that it is rotated, your graphic isn't 20x34 any longer, it is 34x20.
So the first thing you have to do is update the width and height.
<svg xmlns="http://www.w3.org/2000/svg" width="34" height="20">

That's not the final solution of course, because the centre of this new 34x20 SVG is in a different place to the centre of the old 20x34 one.  One solution would be to work out a different centre of rotation that would work so that the graphic rotated around into the right position in the new rectangle.
That's a bit tricky. Luckily there is a much simpler way.  We can just add a viewBox to the SVG to tell the browser the dimensions of the area that the rotated symbol occupies. The browser will reposition it for us.
The four values in a viewBox attribute are:
<leftX> <topY> <width> <height>

We already know the width and height (34 and 20), so we just need to work out the left and top coords.  Those are obviously just the centre-of-rotation less half the width and height respectively.
leftX = 10 - (newWidth / 2)
      = 10 - 17
      = -7
 topY = 17 - (newHeight / 2)
      = 17 - 10
      = 7

So the viewBox attribute needs to be "-7 7 34 20".

<svg xmlns="http://www.w3.org/2000/svg" width="34" height="20" viewBox="-7 7 34 20">

<path transform="rotate(90 10 17)" fill="#6699FF" d="M 0.06,25.03 C 0.06,25.03 4.06,20.97 4.06,20.97 4.06,20.97 3.97,5.06 3.97,5.06 3.97,5.06 9.94,0.03 9.94,0.03 9.94,0.03 15.78,5.09 15.78,5.09 15.78,5.09 16.03,21.06 16.03,21.06 16.03,21.06 19.94,25.00 19.94,25.00 19.94,25.00 19.97,30.09 19.97,30.09 19.97,30.09 10.06,20.97 10.06,20.97 10.06,20.97 10.05,23.00 10.05,23.00 10.05,23.00 19.91,32.03 19.91,32.03 19.91,32.03 19.94,33.97 19.94,33.97 19.94,33.97 17.97,33.97 17.97,33.97 17.97,33.97 10.03,26.94 10.03,26.94 10.03,26.94 10.05,29.01 10.05,29.01 10.05,29.01 15.94,34.00 15.94,34.00 15.94,34.00 12.00,33.94 12.00,33.94 12.00,33.94 10.00,32.00 10.00,32.00 10.00,32.00 8.00,34.03 8.00,34.03 8.00,34.03 4.00,34.00 4.00,34.00 4.00,34.00 9.97,29.01 9.97,29.01 9.97,29.01 9.97,26.94 9.97,26.94 9.97,26.94 2.00,33.96 2.00,33.96 2.00,33.96 0.00,33.98 0.00,33.98 0.00,33.98 0.02,32.00 0.02,32.00 0.02,32.00 9.96,23.00 9.96,23.00 9.96,23.00 9.95,20.98 9.95,20.98 9.95,20.98 0.00,30.00 0.00,30.00 0.00,30.00 0.06,25.03 0.06,25.03 Z" />

<path transform="rotate(90 10 17) translate(0 0)" fill="white" d="M 8.04,17.04 C 8.04,17.04 7.98,11.04 7.98,11.04 7.98,11.04 5.00,11.00 5.00,11.00 5.00,11.00 10.00,6.04 10.00,6.04 10.00,6.04 14.96,11.02 14.96,11.02 14.96,11.02 12.02,11.04 12.02,11.04 12.02,11.04 12.02,17.04 12.02,17.04 12.02,17.04 8.04,17.04 8.04,17.04 Z" />

</svg>

Update
If you need to do arbitrary angles, then there is a better method, using Javascript.

Apply the transform to the paths
Call getBBox() on the SVG to get the dimensions of its content.
Use those values to update the viewBox and the width and 'height`

var angle = 145;  // degrees

var mysvg = document.getElementById("mysvg");
var paths = mysvg.getElementsByTagName("path");

// Apply a transform attribute to each path
for (var i=0; i<paths.length; i++) {
  paths[i].setAttribute("transform", "rotate("+angle+",10,17)");
}

// Now that the paths have been rotated, get the bounding box
// of the SVG contents
var bbox = mysvg.getBBox();

// Update the viewBox from the bounds
mysvg.setAttribute("viewBox", bbox.x + " " + bbox.y + " " +
                              bbox.width +" "+ bbox.height);
// Update the width and height
mysvg.setAttribute("width", bbox.width + "px");
mysvg.setAttribute("height", bbox.height + "px");
<svg id="mysvg" xmlns="http://www.w3.org/2000/svg" width="20" height="34">

<path fill="#6699FF" d="M 0.06,25.03 C 0.06,25.03 4.06,20.97 4.06,20.97 4.06,20.97 3.97,5.06 3.97,5.06 3.97,5.06 9.94,0.03 9.94,0.03 9.94,0.03 15.78,5.09 15.78,5.09 15.78,5.09 16.03,21.06 16.03,21.06 16.03,21.06 19.94,25.00 19.94,25.00 19.94,25.00 19.97,30.09 19.97,30.09 19.97,30.09 10.06,20.97 10.06,20.97 10.06,20.97 10.05,23.00 10.05,23.00 10.05,23.00 19.91,32.03 19.91,32.03 19.91,32.03 19.94,33.97 19.94,33.97 19.94,33.97 17.97,33.97 17.97,33.97 17.97,33.97 10.03,26.94 10.03,26.94 10.03,26.94 10.05,29.01 10.05,29.01 10.05,29.01 15.94,34.00 15.94,34.00 15.94,34.00 12.00,33.94 12.00,33.94 12.00,33.94 10.00,32.00 10.00,32.00 10.00,32.00 8.00,34.03 8.00,34.03 8.00,34.03 4.00,34.00 4.00,34.00 4.00,34.00 9.97,29.01 9.97,29.01 9.97,29.01 9.97,26.94 9.97,26.94 9.97,26.94 2.00,33.96 2.00,33.96 2.00,33.96 0.00,33.98 0.00,33.98 0.00,33.98 0.02,32.00 0.02,32.00 0.02,32.00 9.96,23.00 9.96,23.00 9.96,23.00 9.95,20.98 9.95,20.98 9.95,20.98 0.00,30.00 0.00,30.00 0.00,30.00 0.06,25.03 0.06,25.03 Z" />

<path fill="white" d="M 8.04,17.04 C 8.04,17.04 7.98,11.04 7.98,11.04 7.98,11.04 5.00,11.00 5.00,11.00 5.00,11.00 10.00,6.04 10.00,6.04 10.00,6.04 14.96,11.02 14.96,11.02 14.96,11.02 12.02,11.04 12.02,11.04 12.02,11.04 12.02,17.04 12.02,17.04 12.02,17.04 8.04,17.04 8.04,17.04 Z" />

</svg>
Comment: I guess i can use the if (rotate > 90 and etc... ) { swap width and height }, but what newWidth and newHeight should I be using if I want the rotation to be 145 degree  Sorry if I am asking stupid question, as i said i am very bad with these calculations
Comment: You didn't mention any other angles than 90 degrees. That would have been useful to know sooner :/
Comment: i tried with "I am trying to rotate this "picture", (i need to rotate it on 360 degree)." but i guess i didnt make it clear, sorry. Got the idea how its done. Thanks!

Rotate SVG without misplacing the image


Computing $\lim_{x\to (3/2)^-} (x^2+1)/(3x-2x^2)$

Question: I am trying to compute
$$\large \lim_{x\to \frac32^-}\frac{x^2+1}{3x-2x^2}$$
I know the numerator will equal one fine and how it becomes $x^2+1 * 1/(3x-2x^2)$ because $a/b = a * 1/b$, but then I'm not sure where I go from there, I know the answer is positive infinity but once I get $1/3x-2x^2$ I try to plug $3/2$ in and that gets $0$, I then plugin slightly over or under $3/2$ like $1.6$ or $1.4$ and I get valid outputs. I had the same problem earlier except it approached 0 from the left side and it was negative infinity, I have absolutely no idea what to do or where to go from this.
Comment: Do you mean $$\lim_{x\to 3/2}-\frac{x^2+1}{3-2x^2}$$?
Comment: Yeah the x still needs to stay.
Answer: HINT
Note that
$$3x-2x^2=2x\left(\frac32-x\right)$$
Comment: What are the sign for $2x$ and $(3/2-x)$ as  $x\to \frac32^-$ that is $x=\frac32-\epsilon$ with $\epsilon>0$ "small".
Comment: I'm confused  on how I would use that , shouldn't all instances of x be 3/2? Not just the first one in the parenthesis
Comment: (2(3/2))/(3/2-3/2)?? I know its zero but where does it being negative infinity come? Versus it being positive infinity
Comment: @oso9817 Recall that $x$ is never exactly equal to $\frac32$ but something smaller than that.
Comment: so it would be anything less than 3/2? Either way even when I substitute 1.4 I get 0 again so I'm confused. I'm not sure if I'm understanding the concept
Comment: @oso9817 Let assume for example $x=\frac{30}{21}$, what is the sign of $\frac32-\frac{30}{21}$?
Comment: @oso9817 You need to recall the definition of limit. Not ethat  $x\to \frac32^-$ means that $x$ approches the value $\frac32$ "from the left" of the real line that is with values less that $\frac32$ therefore what is the sign of $(3/2-x)$?
Comment: Ok I think I'm getting it. Was your first step of factoring it out mandatory?
Comment: @oso9817 Well it is a good way in that case to see what is the sign for the denominator. Since it is polynomial and 3/2 is a root it is possible to factorize that, then that's method is recommended here. As an laternative we can derive $f(x)=3x-2x^2 \implies f'(x)=3-4x$ and note that $f'(3/2)=3-6=-3<0$ therefore the function is decreasing in a neighborhood of $x=3/2$, but it is a more complicated way.
Comment: Wait can you explain again the difference it makes? I'm doing it right now on paper and it's positive if 2x(3/2-1) that would be 1 aka positive. It's on the left side of 3/2 too
Comment: Ok I think I understand it now. Disregard the last comment of mine I accidentally read my problem as approaching from the right. Following your function 2x(3/2-x) and substituting -1.6 would make it negative while still being on the left side of 3/2 E: never mind on that forgot the double negatives.
Comment: @oso9817 Yes of course, but since we are considering the limit as $x \to \frac32^-$ what matters here is the sign in a left neighborhood of $\frac32$.
Comment: So everything less than 3/2 ? So it seems everything thay isn't negative or not more than 3/2 would be valid. I don't see how that results in positive infinity
Comment: Seems to be like 00$ as $x \to \frac32^-$ therefore we have a positive finite numerator divided by an arbitrary small positive number and the limit is $+\infty$.
Comment: Ok I'm pretty sure I have the hang of this. Do you do anything with the numerator?
Comment: @oso9817 The numerator approces $13/4$ therefore it is positive when x approches 3/2.
Answer: For such a problem, let $x=y+\frac 32$ to make
$$ \lim_{x\to \frac32}\frac{x^2+1}{3x-2x^2}=-\lim_{y\to0}\frac{13+12y+4 y^2}{12y+8 y^2}=-\lim_{y\to0}\frac{13+12y+4 y^2}{12y(1+\frac 23 y)}$$ Since $y$ is small, the numerator is almost $13$ and the denominator almost $12y$.
Answer: Graphical way to observe the denominator $3x-2x^2$:
$\hspace{3cm}$
It implies that as $x\to 1.5$, $3x-2x^2\to 0+$.
Hence:
$$\lim_{x\to \frac32-}\frac{x^2+1}{3x-2x^2}=\frac{13/4}{0+}=+\infty.$$
Answer: The numerator will not equal $1$, it will approach $1+(\frac 32)^2=\frac {13}{4}$.  The denominator will approach $0$ but always be positive because $x \lt \frac 32$.  The ratio will therefore go to $+\infty$.  A graph is below.  The fact that $x$ approaches from below means you are on the lower piece of the graph, which goes to $+\infty$
Comment: The OP knows the answer is $+\infty$, the problem here is to find a good and simple method to prove that. The plot is very clear but I suppose the OP is looking for something based on alebraic or precalculus considerations. That' only my opinion of course.
Comment: Correct. I'm looking to solve this analytically without a graph or calculator
Comment: I couldn't understand what you were really looking for.  I would just determine that the numerator and denominator are positive and the denominator goes to zero to determine the fact that the limit is $+\infty$.  I put the graph in to explain what is going on.
Comment: How do you get the denominator to be positive? If x<3/2 wouldn't thay mean it would also reach the negatives
Comment: When the denominator is close to $\frac 32$ but below, the $3x$ term is more positive than the $-2x^2$ is negative, so the sum is positive.  Just compute it for $1.49$, for example.  When you are taking a limit you are working close to the point, so don't have to worry about the fact that $3x-2x^2$ gets negative if $x$ is large and negative.


Error E QUERY [thread1] SyntaxError: invalid property id @(shell) using and/or with find()

Question: I am getting the error while using this query
    db.a.find({$or:[{"name" : "aekansh"},{"age" : 21}]}).pretty()
as
E QUERY    [thread1] SyntaxError: invalid property id @(shell):1:11
collection a stores the data as
<code>{ "_id" : 10, "name" : "aekansh" }
{ "_id" : 11, "name" : "ram" }
{ "_id" : ObjectId("59dda15e153802c1d1cf8500"), "name" : "ramu" }
{ "_id" : 12, "nm" : "raj", "age" : 21 }
{ "_id" : ObjectId("59dda1d26b740896d9f067a3"), "nm" : "rj", "age" : 22, "bfff" : "yes" }
{ "_id" : ObjectId("59dda1ea11fc6ddeb8784f7e"), "nm" : "rj1", "age" : 22, "bfff" : "yes" }
</code>
I have looked at syntax and I think it is right. Why I am getting the error. Thanx in advance.
Edit- I am using online terminal for MongoDb https://www.jdoodle.com/online-mongodb-terminal
Comment: Your query is correct, and it is working fine for the sample data provided.
Just ensure that you are using quotes for querying inner documents and strings, which is also there in your query. Try by closing the mongo shell and reopening the shell.
Comment: I am also getting a similar error on jdoodle terminal. It seems the error is specific to this online terminal.
Comment: I am using online shell for mongoDB. https://www.jdoodle.com/online-mongodb-terminal . Is there any issue with this shell. Can you refer me a better terminal online.
Answer: As was mentioned before your query is correct.
If fails on this online terminal it means terminal is buggy.
You have in fact 3 solutions about which I know:

Install MongoDB on your local computer and use MongoDB Compass or MongoShell to query your database.
Use Mongo Web Shell which is accessible on MongoDB documentation site.
The last option is to set up free cluster from Mongo site. They give you for free some space in cloud, set up database for you and as in first option  you can use MongoDB Compass or MongoShell to query it from you local computer.


How to take an array of input fields values and pass it through an Ajax call

Question: I have a web form in which look like this right now. The problem is I have a option which adds more dynamically rows below them which looks the same and have the same name attribute. I have a submit button which gets the value of all the input fields. The submitted values goes through an Ajax call to my PHP where I have to insert them in my database.
Access:

  <input type"text" name="access[name]">
  <input type"text" name="access[type]">
  <input type"text" name="access[description]">

student:

  <input type"text" name="student[name]">
  <input type"text" name="student[type]">
  <input type"text" name="student[description]">

So far I can't get all the values generated by the input field in an array so that I can properly sort and insert them in my database.
I was looking for my array structure to look like this or like a properly JSON formatted. But I don't know how to do this in Ajax call.
access[
         name:xyz,
         type:xyz,
         description
      ]
student[
         name:xyz,
         type:xyz,
         description
      ]

My Ajax function:
    $('.submit').on('click',function(){

    var access;
    $('input[name^="Access"]').each(function() {
        access= ($(this).val());
    });
    var student;
    $('input[name^="student"]').each(function() {
        student= ($(this).val());
    });

    $.ajax({
           url: '../php/Submission.php',
           type: 'post',
           data: {access:access,student:student}
       },
           function(data1)
            {
                console.log(data1);
            }
      );
});

I know my Ajax function is not write but I have tried so many code to make it work as the result it's all messed up and not sure what to do now.
Answer: Change your access and student variables to become arrays, and add the values to them (Note: you can simply use this.value instead of $(this).val()):
var access = [];
$('input[name^="Access"]').each(function() {
    access.push(this.value);
});
var student = [];
$('input[name^="student"]').each(function() {
    student.push(this.value);
});

EDIT If you want to name your values instead of using the index, you'll need to use objects instead of arrays, and manually extract the name:
var access = {};
$('input[name^="access"]').each(function() {
    var name = this.name.substr(7, this.name.length - 8);
    access[name] = this.value;
});
var student = {};
$('input[name^="student"]').each(function() {
    var name = this.name.substr(8, this.name.length - 9);
    student[name] = this.value;
});

Comment: Small note, `this.value` would also work in this case, rather than using jquery to access the property.  And `map()` could also be used rather than `each()`
Comment: @Taplar I know, but I just copied/pasted the code from the OP. I will update my answer. Thanks.
Comment: It can be a stupid question but Does this will contain the key input field of the array value i.e "Name","Description"?
Comment: @RacilHilan thank you for the help. It's working and I'll accept the answer. But right now I am getting the output like this in an array: 0:value1,1:value2, 2:value3. Where 0,1,2 are the index I believe. I was hoping them to be as the key name i.e name:value1,description:value2, etc


Training LSTM a sequence one item at a time

Question: I am trying to train an lstm with a sequence and get the sequence classification for the whole sequence.
I have sequences of varying length so I have one input neuron and I am feeding one item at a time. Isn't that the proper solution?
My issue is that I am training each of these inputs with a single ideal-output, but some of the sequences exist in other sequences with other ideal-outputs.
So when I train 0.74 with 1,0 and 0.83 with 1,0 and 0.32 with 1,0 it gets trained with the class 0, 1. But when I then train with 0.74 0.83 0.32 with 0,1 the training diverges to infinity because I assigned two different classes to the same input.
How am I supposed to train a lstm with a sequence when some of the elements treat across sequences? Unless there is another way to train a deep-network that has an lstm when the sequences are of varying lengths?
Answer: Train it one character at a time.
It shouldn't diverge unless the characters are the same and have different ideal-outputs. In that case consider using one-hot vectors instead of scalar vectors. Meaning if a, b, and c are your characters then if a is the character 1, 0, 0 is the input.


The mutable variable 'x' is used in an invalid way. Mutable variables cannot be captured by closures

Question: I have a couple of books that I am going by, but as I am working on my F# problems, I find some difficulties in syntax here. If anyone thinks I should not be asking these questions here and have another book recommendation on a budget, please let me know.
Here is the code that reproduces the problem I am having with my project
[<EntryPoint>]
let main argv =
    let mutable x = 0

    let somefuncthattakesfunc v = ignore

    let c() =
        let y = x
        ignore

    somefuncthattakesfunc (fun () -> (x <- 1))
    Console.ReadKey()
    0 // return an integer exit code

I am getting the following compile error
The mutable variable 'x' is used in an invalid way. Mutable variables cannot be captured by closures. Consider eliminating this use of mutation or using a heap-allocated mutable reference cell via 'ref' and '!'.

Any clue ?
Comment: No, you're comparing to `x` -- assignment is `<-`. ;-]
Comment: Use `ref` instead of `mutable`, but you're never assigning to `x`, so why is it `mutable` anyway?
Comment: @ildjarn I am assigning to x in the lambda expression
Answer: As the error explains, you can't close over mutable variables, which you are doing in:
let y = x

and
(fun () -> x = 1)

It suggests you use a ref instead if you need mutation:
let x = ref 0

let somefuncthattakesfunc v = ignore

let c() =
    let y = !x
    ignore

somefuncthattakesfunc (fun () -> x := 1)

Answer: As the error message says, mutable variables cannot be captured by closures, use a reference cell instead:
let main argv =
    let x = ref 0

    let somefuncthattakesfunc v = ignore

    let c() =
        let y = !x
        ignore

    somefuncthattakesfunc (fun () -> x := 1)
    Console.ReadKey()
    0 // return an integer exit code

Also see this answer.
Comment: I mistakenly put = instead of <- assignment operator in lambda expression. I have corrected it.  Now this solution does not work. It says x is not mutable.


Excluir linha da tabela pelo checkBox

Question: Estou tentando usar uma checkbox para excluir varias linhas de uma tabela criada pelo javaScript com informações de input.
Porém eu não sei como fazer ele reconhecer a td para pode executar a função de excluir(Botão);

function adicionarItem() {
  var refNome = document.querySelector("#nome").value;
  var refCpf = document.querySelector("#cpf").value;
  var refRg = document.querySelector("#rg").value;

  var usuarioTr = document.createElement("tr");
  usuarioTr.className = "user";

  var selec = document.createElement('td');
  selec.className = 'usr';
  var input = document.createElement('input');
  input.type = 'checkbox';
  selec.appendChild(input);
  var nomeTd = document.createElement("td");
  var cpfTd = document.createElement("td");
  var rgTd = document.createElement("td");

  nomeTd.textContent = refNome;
  cpfTd.textContent = refCpf;
  rgTd.textContent = refRg;

  usuarioTr.appendChild(selec);
  usuarioTr.appendChild(nomeTd);
  usuarioTr.appendChild(cpfTd);
  usuarioTr.appendChild(rgTd);

  var tabela = document.querySelector("#tabela");

  tabela.appendChild(usuarioTr);
}
<!DOCTYPE html>

  <meta charset="utf-8" />
  <title>Teste01</title>

  <link rel="stylesheet" type="text/css" href="main.css" />

    <form>

        Nome:
        <input id="nome" name="nome" type="text" placeholder="Digite seu nome aqui" autofocus/>

        CPF:
        <input id="cpf" name="cpf" type="number" placeholder="Digite seu CPF" />

        RG:
        <input id="rg" name="rg" type="number" placeholder="Digite seu RG" />

      <button id="adicionarBotao" onclick="adicionarItem()" type="button">Adicionar</button>
      <button id="editarBotao" onclick="" type="button">Editar</button>
      <button id="excluirBotao" onclick="" type="button">Excluir</button>
    </form>

        Selecionar
        Nome
        CPF
        RG

Answer: Da para excluir com a seguinte função:
function removerItem() {
  ckList = document.querySelectorAll("input[type=checkbox]:checked");
  ckList.forEach(function(el) {
    el.parentElement.parentElement.remove();
  });
}

onde ckList é uma lista com todos os elementos input do tipo checkbox que estão marcados(checked), e o forEach encarrega-se de remover todas as tr's onde esses elementos estão.

function adicionarItem() {
  var refNome = document.querySelector("#nome").value;
  var refCpf = document.querySelector("#cpf").value;
  var refRg = document.querySelector("#rg").value;

  var usuarioTr = document.createElement("tr");
  usuarioTr.className = "user";

  var selec = document.createElement('td');
  selec.className = 'usr';
  var input = document.createElement('input');
  input.type = 'checkbox';
  selec.appendChild(input);
  var nomeTd = document.createElement("td");
  var cpfTd = document.createElement("td");
  var rgTd = document.createElement("td");

  nomeTd.textContent = refNome;
  cpfTd.textContent = refCpf;
  rgTd.textContent = refRg;

  usuarioTr.appendChild(selec);
  usuarioTr.appendChild(nomeTd);
  usuarioTr.appendChild(cpfTd);
  usuarioTr.appendChild(rgTd);

  var tabela = document.querySelector("#tabela");

  tabela.appendChild(usuarioTr);
}

function removerItem() {
  ckList = document.querySelectorAll("input[type=checkbox]:checked");
  ckList.forEach(function(el) {
    el.parentElement.parentElement.remove();
  });
}
<!DOCTYPE html>

  <meta charset="utf-8" />
  <title>Teste01</title>

  <link rel="stylesheet" type="text/css" href="main.css" />

    <form>

        Nome:
        <input id="nome" name="nome" type="text" placeholder="Digite seu nome aqui" autofocus/>

        CPF:
        <input id="cpf" name="cpf" type="number" placeholder="Digite seu CPF" />

        RG:
        <input id="rg" name="rg" type="number" placeholder="Digite seu RG" />

      <button id="adicionarBotao" onclick="adicionarItem()" type="button">Adicionar</button>
      <button id="editarBotao" onclick="" type="button">Editar</button>
      <button id="excluirBotao" onclick="removerItem()" type="button">Excluir</button>
    </form>

        Selecionar
        Nome
        CPF
        RG

Comment: Muito bom, só aproveitaria o seletor pra já trazer só os checkboxes que já estão selecionados usado isso:  `document.querySelectorAll("input[type=checkbox]:checked")`
Comment: @RicardoPontual Perfeito, acrescentei à resposta, valeu =)

Excluir linha da tabela pelo checkBox


Taking the gradient of $f(w) = \sum^n_{i=1}\log(e^{(w^Tx_i - y_i)}+e^{(y_i - w^Tx_i))}$ w.r.t. $w$

Question: My work:
First, we experiment by taking the derivative w.r.t. $w_1$:
$\frac{\partial f(w)}{\partial w_1} = \frac{\partial }{\partial w_1}\sum^n_{i=1}\log(e^{(w^Tx_i - y_i))}+e^{(y_i - w^Tx_i)}) = \sum^n_{i=1}\frac{\partial }{\partial w_1}\log(e^{(w^Tx_i - y_i)}+e^{(y_i - w^Tx_i)}) = \frac{1}{e^{(w^Tx_i - y_i)}+e^{(y_i - w^Tx_i)}}[x_1e^{(w^Tx_i-y_i)}-x_1e^{(y_i-w^Tx^i)}]$
The last equality, I got from the chain rule and the identity: $$\frac{d}{dw}\ln w = \frac{1}{w}$$.
Therefore, $\nabla f(w) = \begin{align}
    y &= \begin{bmatrix}
           \frac{1}{e^{(w^Tx_i - y_i)}+e^{(y_i - w^Tx_i)}}[x_1e^{(w^Tx_i-y_i)}-x_1e^{(y_i-w^Tx^i)}] \\
           \frac{1}{e^{(w^Tx_i - y_i)}+e^{(y_i - w^Tx_i)}}[x_2e^{(w^Tx_i-y_i)}-x_2e^{(y_i-w^Tx^i)}] \\
           \vdots \\
           \frac{1}{e^{(w^Tx_i - y_i)}+e^{(y_i - w^Tx_i)}}[x_ne^{(w^Tx_i-y_i)}-x_ne^{(y_i-w^Tx^i)}]
         \end{bmatrix}
  \end{align}$
However, I have a bitter feeling that it shouldn't be this complicated. Can someone please verify? Thank you!
Comment: Is your result $\nabla f(w)=\tanh (w^t x_i - y_i) x$?
Answer: You forgot the summation sign. There are $n$ data points, $n$ need not be the length of $w$.
$$f(w) = \sum_{i=1}^n \ln (2\cosh (w^Tx_i - y_i )) = n \ln 2 + \sum_{i=1}^n \ln (\cosh(w^Tx_i-y_i))$$
$$\frac{\partial f}{\partial w_j}=\sum_{i=1}^n \frac{x_{ij}\sinh(w^Tx_i-y_i)}{\cosh(w^Tx_i-y_i)}=\sum_{i=1}^n \frac{x_{ij}\sinh(w^Tx_i-y_i)}{\cosh(w^Tx_i-y_i)}=\sum_{i=1}^n x_{ij}\tanh(w^Tx_i-y_i)$$