How to Inject a Spring Service into a Non-Component Parent Class

Question: I have a parent class that is not managed by Spring which has multiple @Component's inherited from it:
public class Parent {

  public void commonMethod(SomeObj obj) {
    //...
  }
}

@Component
public class ChildA extends Parent {

  public MyObj doSomething(/*...*/) {
    // Some external call
    commonMethod(obj);
  }
}

@Component
public class ChildB extends Parent {

  public MyObj doSomething(/*...*/) {
    // Some external call
    commonMethod(obj);
  }
}

Now I need to call a Spring managed @Service from the Parent class. Of course, since Parent is not a Spring-managed bean, I was thinking to do something like:
@Service
public class SomeServiceImpl implements SomeService {

  public void serviceWork(MyObj obj) {
    // Some static method call
  }
}

public class Parent {

  private SomeService someService;

  public Parent(SomeService someService) { this.someService = someService; }

  public void commonMethod(MyObj obj) {
    someService.serviceWork(obj);
    //...
  }
}

@Component
public class ChildA extends Parent {

  public ChildA(@Autowired SomeService someService) { super(someService); }

  public MyObj doSomething(/*...*/) {
    // Some external call
    commonMethod(obj);
  }
}

@Component
public class ChildB extends Parent {

  public ChildA(@Autowired SomeService someService) { super(someService); }

  public MyObj doSomething(/*...*/) {
    // Some external call
    commonMethod(obj);
  }
}

My question is, is this thread safe? Second, is there a better design for this since now I have to @Autowired SomeService and pass it to Parent's constructor for every child class.
Can I make the Parent class a Spring-managed class? Would that cause any issues since now it becomes a singleton class that's being shared among all the children?
Comment: Why not just have Parent be a @Component, have SomeService autowired there, and have the Child classes directly use the parent's service field?
Comment: That's my question, can both the child and parent be `@Component`'s? How does one do this with annotations (Spring 5.2+)? Also, I don't need to use the parent's service field in child, but rather only in the parent as part of refactoring. I'm not changing the state of either Child, Parent or the other `@Service` class for that matter. Simply passing an object to their methods (stack per thread).
Answer: You're confusing classes and instances of objects.
Using your schema above you would have 3 objects instantiated
1 instance of class SomeServiceImpl
1 instance of class ChildA (which happens to implement Parent)
1 instance of class ChildB (which happens to implement Parent)
This is because Spring will create these objects as they are defined as Components/Services. The 1 instance of SomeServiceImpl will be handed to both
the instance of ChildA and the instance of ChildB.
Each instance of class ChildA and ChildB would have their own copy of all the data fields in their own class and all super classes. However because you've auto wired the SomeServiceImpl they are pointing at the same instance of SomeServiceImpl.
So if you goal is to call SomeServiceImpl from ChildA and ChildB and have them thread safe this won't work since they are both talking to the same instance.
The general strategy looks correct, you'd have to mark the functions on SomeServiceImpl as synchronised. Assuming it is that you want ChildA and ChildB to share the SomeServiceImpl.
Comment: And that's ok as far as both `ChildA` and `ChildB` using the same `SomeService` instance, since I'm just passing a newly created `MyObj` to `SomeService.doWork()`, and therefore, per each thread, this is going to on the thread stack, which makes it thread safe.
Answer:
My question is, is this thread safe

no : Spring does not guarantee thread safety.
look at Are Spring objects thread safe?

is there a better design for this since now I have to @Autowired SomeService and pass it to Parent's constructor for every child class.

public class Parent implements ApplicationContextAware {

private static ApplicationContext context;
public Parent() { this.someService = context.getBean(someService.class); }

But if parent need some bean maybe parent must be a bean to and let the appContext use DI
Comment: Since neither of these classes changing a state of `SomeService`'s implementation class, and simply calling a method, the call will be placed on a stack, per thread. Can I just annotate `Parent` as `@Component`, which would make it Spring managed, but a singleton. Would that cause an issue with child-parent where both are Spring managed "and" inherited?
Answer: First of all, please have your future questions more focused and do not ask 5 questions in one post.

How to Inject a Spring Service into a Non-Component Parent Class?

You cannot.
You cannot inject an object managed by Spring, into another object NOT managed by Spring.
Why? because, Spring has no idea what other objects in your program are, and hence, it will never have any reference(s) to them, unless they're also managed by Spring, i.e. they are beans.

My question is, is this thread safe?

There is nothing about Thread-safety here.

Second, is there a better design for this since now I have to @Autowired SomeService and pass it to Parent's constructor for every child class?

There are several ways of injection: Setter, Field, and Constructor. Look it up in Google;

Can I make the Parent class a Spring-managed class? Would that cause any issues since now it becomes a singleton class that's being shared among all the children?

Yes, you can. You can read Bean Definition Inheritance to see how.
Comment: Thanks Giorgi. If I can just mark the `Parent` class as `@Component`, then that should resolve the issue (and I believe that's the only thing I need to be doing, other than `@Autowiring` `SomeService` in the `Parent` class. That said, I updated the solution above, and locally, it seems like I can deploy it just fine. Can you take a look at it and see what you think?


Can't install ggplot with anaconda

Question: (I'm aware of this question Cannot install ggplot with anaconda but that is aimed at Windows, and I'm running a Linux OS)
I'm attempting to install the ggplot package in a python3 (v3.6.0) Anaconda environment:
$ conda install ggplot
Fetching package metadata .............

PackageNotFoundError: Package missing in current linux-64 channels:
  - ggplot

Close matches found; did you mean one of these?

    ggplot: r-ggplot2, r-gplots

If I use conda search I get:
$ conda search ggplot
Fetching package metadata .............
r-ggplot2                    1.0.0                         0  defaults
                             1.0.0                        0a  defaults
                             1.0.1                  r3.2.2_0  defaults
                             1.0.1                  r3.2.0_0  defaults
                             1.0.1                  r3.2.1_0  defaults
                             1.0.1                 r3.2.1_0a  defaults
                             1.0.1                 r3.2.2_0a  defaults
                             1.0.1                 r3.2.0_0a  defaults
                             2.1.0                  r3.3.1_0  defaults
                             2.2.0                  r3.3.1_0  defaults
                             2.2.0                  r3.3.2_0  defaults

but if I search https://anaconda.org/search for ggplot I get lots of results.
The questions: why am I not seeing those results when using conda search? What is the difference between ggplot and r-ggplot2 (the package it offers to install when I search for ggplot)?
Answer:
Why am I not seeing those results when using conda search?

The difference for search is that conda search only searches in your channels, anaconda search or the search on anaconda.org includes all (public) channels. The name in front of the package name is the channel, for example xyz/ggplot the xyz is the channel.

What is the difference between ggplot and r-ggplot2

It's probably a naming convention. anaconda has several R based packages and it's likely they seperate them using the r- prefix from more regular python packages. So if you don't plan to use it with "R" you should probably look for a suitable candidate without the r-.
Comment: Thank you, your answer makes things much more clear.

Can't install ggplot with anaconda


Why can't I use Javascript in the  tag?

Question: I saw a question on placing script tag optimally inside the HTML.
Should I write script in the body or the head of the html?
However, the answer's fifth point advise not to place script in markups like input tag. Why?
Thanks!
Comment: check this out https://stackoverflow.com/questions/5871640/why-is-using-onclick-in-html-a-bad-practice
Answer: Because you will have problems to manage your code. It is difficult to understand the problem when you have a single  element. However, imagine what happens when you have 10, 50 or 100  elements with inline event handlers and you need then to add a new parameter to your function? It will become a nightmare. You will have to go through all elements and adjust inline event handlers. It can cause potential bugs which are never desirable. In addition, if you try to keep JavaScript and HTML separate, it has also an advantage that you can use the same JavaScript code for many different HTML documents.
For more details and examples: Inline event handlers — don't use these

Why can't I use Javascript in the  tag?


Call another field inside preprocess_views_view_field

Question: how can I access the value of another field inside the preprocess_views_view_field.
This is an example:

function THEMENAME_preprocess_views_view_field(&$variables) {
  $view = $variables['view'];
  $field = $variables['field'];

  if ($view->id() == 'VIEW_NAME' && $view->current_display == 'DISPLAY_NAME') {
    if ($field->field == 'FIELD_NAME') {
      $my_output = manipulation(ANOTHER_FIELD_NAME_IN_VIEW);
      $variables['output'] = $my_output;
    }
  }
}

It's possible or should i use it _preprocess_views_view?
Comment: Have a look in `$variables['row']` that should contain all the fields in your view
Comment: Should be you can see it here https://api.drupal.org/api/drupal/core%21modules%21views%21views.theme.inc/function/template_preprocess_views_view_fields/8.8.x you can see $variables['row'] being used
Comment: I am using _preprocess_views_view_field single with no final s. Maybe it's not possible.
Comment: Ok, I solved, thanks your suggestion helped me.
Answer: Ok,
I solved it like this:

function THEMENAME_preprocess_views_view_field(&$variables) {
  $view = $variables['view'];
  $field = $variables['field'];
  $rows = $variables['rows'];

  if ($view->id() == 'VIEW_NAME' && $view->current_display == 'DISPLAY_NAME') {
    if ($field->field == 'FIELD_NAME') {
      foreach ($view->field as $fieldId => $field) {
        if ($fieldId === 'ANOTHER_FIELD_NAME_IN_VIEW') {
          $my_output = $view->style_plugin->getFieldValue($row->index, $fieldId);
        }
      }
      $variables['output'] = $my_output;
    }
  }
}


Finding historical mean and using it as a threshold

Question: Using this data:
         USER   MEDIA DD_MM          SCORES
0         4       w  02/11          9737662
1         4       k  03/11         11691966
2         4       a  02/11          5140069
3         4       w  03/11         10165111
4         4       w  01/11          8962654
5         4       k  02/11         10112785
6         4       a  03/11          5661891
7         4       a  01/11          4942428
8         4       k  01/11         12246323
0         5       a  03/11           314034
1         5       w  01/11         16071400
2         5       k  03/11         16767571
3         5       k  01/11         20256912
4         5       k  02/11         15766468
5         5       w  02/11         18605524
6         5       w  03/11         20559416
7         5       a  02/11           260323
8         5       a  01/11           287743
0         8       w  03/11          2155365

I want to predict whether new information that comes in is  anomalous  or not. How can I set a threshold using an historical data (see below)? For instance, using the data below,  I want to raise an alarm new data comes  such as this comes in.
user =4, media = k, scores = 500

This should be classified as an anomaly. My approach is  to find the historical daily mean for user and media and then take two standard deviations (+/-) away from the mean. However, the resultant min_threshold is always negative. That means the dataset with the score of 500 is not classified as an anomaly.  Is there a better way to do this?
Answer: Thresholds based on mean and standard deviation are reasonable if you know that your data is approximately normally distributed. While there are hypothesis tests for normality, these might not yield useful results for outlier detection, because you are interested in the variable range with very low probabilities, i.e. the long tails of the distribution. If you have many data points, you can visually check it with the R function density and compare it with the normal distribution, e.g. (assuming that x is the data):
plot(density(x))
lines(dnorm(seq(min(x),max(x),by=(max(x)-min(x))/500), mean=mean(x), sd=sd(x), col="red")

In any case, you can try a non-parametric approach by defining your thresholds on quantiles of the empirical distribution function as follows:
F.emp <- ecdf(x)
quantile(F.emp, c(0.01, 0.99))

The same thresholds could be obtained by directly computing the quantiles from the data, but using the empirical CDF has the advantage that you can also compute a (one-sided) p-value for your test value y:
m <- median(x)
if (y < m) {
  p <- F.emp(y)
} else {
  p <- 1 - F.emp(y)
}

In more than one dimension, the same apporach is possible on basis of a distance statistics. Here is a technical report, in which I have described the method and applied it to OCR error detection:

Dalitz: "Reject Options and Confidence Measures for kNN Classifiers." In C. Dalitz (Ed.): "Document Image Analysis with the Gamera Framework." Schriftenreihe des Fachbereichs Elektrotechnik und Informatik, Hochschule Niederrhein, vol. 8, pp. 16-38, Shaker Verlag (2009)


Transforming an array in Python

Question: I am doing sentiment analysis on a text and it analyses sentiment on a sentence-to-sentence basis, and below is the result I got.
[1.0, 1.0, 0, 0, 0, 0.0, 0, 1.0, 0, 1.0, 0, 0, 0, -1.0, 1.0]

I would like to plot a graph sentiment score against sentence number using Python, can anyone tell me how to do it?
Do I need to create another array like [1, 2, 3, 4, ..., 15], something like that and plot it? If so, how can I do it in Python?
I have not much experience in Python nor programming, so I would really appreciate it if someone could help, thank you.
Answer: You can construct an array or list for the x coordinates if you want, but it is not necessary. You can plot the values without giving x coords and in this case you will get them as a sequence starting from 0.
Here is a simple example:
from matplotlib import pyplot as plt
y=[1.0, 1.0, 0, 0, 0, 0.0, 0, 1.0, 0, 1.0, 0, 0, 0, -1.0, 1.0]
plt.plot(y)
plt.show()

Transforming an array in Python


boto3 Get a resource from a client

Question: The AWS Library for python (boto) has two different types of interfaces for working with AWS, a low level client and a higher level more pythonic resource.
Parts of my code use one, while other parts use the other.
Getting a client from a resource is found from the docs.
# Create the resource
sqs_resource = boto3.resource('sqs')

# Get the client from the resource
sqs = sqs_resource.meta.client

My questions is if have the client sqs, how do I get a boto3.resource from this?
(I can't simply just call boto3.resource('sqs') because the client has other things, such as credentials already attached to it, the resource for some design reason tries to fetch the AWS credentials from a bunch of places I don't want it to, I'd like it to use whatever credentials/account is set on the client)
Comment: See also https://github.com/boto/boto3/issues/747 which would enable you to get it, if implemented.
Answer: There is no way to do this. If you want to use both, you should create a resource and use the embedded client. You can instantiate a resource with the exact same configuration as a client. The underlying client for the resource is created in the exact same way. The only difference between a resource's client and a client created with the exact same parameters is that the resource client adds 'Resource' to the user-agent.
Answer: I think you should create resource and client separately as below:
import boto3
sqs_resource = boto3.resource("sqs")
sqs_client = boto3.client("sqs")

print dir(sqs_resource)
print dir(sqs_client)

Output:
[u'Message', u'Queue', '__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', u'create_queue', 'get_available_subresources', u'get_queue_by_name', 'meta', u'queues']
['_PY_TO_OP_NAME', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_cache', '_client_config', '_convert_to_request_dict', '_endpoint', '_force_path_style_s3_addressing', '_force_virtual_style_s3_addressing', '_get_waiter_config', '_loader', '_make_api_call', '_register_handlers', '_register_s3_specific_handlers', '_request_signer', '_response_parser', '_serializer', '_service_model', u'add_permission', 'can_paginate', u'change_message_visibility', u'change_message_visibility_batch', u'create_queue', u'delete_message', u'delete_message_batch', u'delete_queue', 'generate_presigned_url', 'get_paginator', u'get_queue_attributes', u'get_queue_url', 'get_waiter', u'list_dead_letter_source_queues', u'list_queues', 'meta', u'purge_queue', u'receive_message', u'remove_permission', u'send_message', u'send_message_batch', u'set_queue_attributes', 'waiter_names']

From above output, you will always get client from resource as sqs_resource.meta.client.
But vice-versa is not possible.
Instead, create resource and client both and use whatever you required.
Please let me know if this is useful.

boto3 Get a resource from a client


The algebraic interior of a convex set is convex

Question: I'm reading the concept of algebraic interior in which I tried to prove $2$ basic results to strengthen my understanding. Could you have a check if my proofs are fine?

Let $X$ be a vector space, $Y$ a subspace of $X$, and  $A \subset X$.

Then algebraic interior of $A$ with respect to $Y$ is defined as
$$
\operatorname{aint}_{Y} (A) := \{x \in X \mid \forall y\in Y, \exists t >0: [x, x+t y] \subset A \}.
$$
Clearly,  $\operatorname{aint}_{Y} (A)  \subset A$. If $A$ is convex, then the above definition reduces to
$$
\operatorname{aint}_{Y} (A) = \{x \in X \mid \forall y\in Y, \exists t >0: x+t y \in A \}.
$$

The algebraic interior of $A$ is defined as
$$
\operatorname{aint} (A) := \operatorname{aint}_{X} (A).
$$

Theorem 1: $x \in \operatorname{aint} (A)$ if and only if $x \in \operatorname{aint}_{L} (A)$ for every line $L \subset X$ passing through $x$.
Proof: Because $L \subset X$, so $\operatorname{aint} (A) =\operatorname{aint}_{X} (A) \subset \operatorname{aint}_{L} (A)$ for every line $L \subset X$ passing through $x$.
Next we prove the converse direction. We fix $x\in X$ such that $x \in \operatorname{aint}_{L} (A)$ for every line $L \subset X$ passing through $x$. Let $y \in X$ and $L$ the line connecting $x,y$, i.e., $L = \operatorname{conv} \{x, y\}$. Then $x \in \operatorname{aint}_{L} (A)$. In particular, $y \in L$, so $\exists t>0$ such that $[x, x+ty] \subset A$. It follows that $x \in \operatorname{aint} (A)$.
Theorem 2: Let $A$ be a convex subset of a vector space $X$. If $x \in \operatorname{aint} (A)$ and $y\in A$, then $[x, y) \subset \operatorname{aint} (A)$. In particular, $\operatorname{aint} (A)$ is convex.
Proof: Let $\lambda \in (0, 1]$ and $z := \lambda x+(1-\lambda)y \in [x, y)$. Fix $w\in X$. There is $t>0$ such that $x+tw \in A$. We want to find $t'>0$ such that $z+t'w = \lambda(x+tw) +(1-\lambda)y + (t'-\lambda t)w\in A$. It suffices to take $t' := \lambda t$.
Answer: Thm 1: main idea is there, although a bit tersely written. Only issue: how do you define a line in this class? $L=\textrm{conv}(x,y)$ makes it look like a line segment, not a line with infinite lenth
Thm 2: checks out, but could be made clearer by just removing the $(t'-\lambda t)w$ term entirely.
Comment: You are right. It should be $L = \operatorname{aff} \{x, y\}$.


Windows Forms, double click que abre um novo Form

Question: Tenho uma tabela chamada Torneio e gostava de ao fazer DoubleClick no tipo de jogo abrisse todas as equipas desse jogo.
Tenho 4 botoes que representam os 4 jogos que tenho, nos 4 jogos tenho os torneios as equipas e as classificações e ao inserir um torneio queria que quando fizesse DoubleClick no jogo abrisse todas as equipas de cada jogo que já estão por classificação em uma datagridview.
O código é o seguinte:
private void Dgv1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (dataGridView1.CurrentCell.ColumnIndex == dataGridView1.Columns["Jogos"].Index)
            {
                EquipasLOL Tela = new EquipasLOL(dataGridView1.SelectedRows[0].Cells["Jogos"].ToString());
                Tela.Show();
                this.Hide();
            }
        }

Obrigado pela ajuda!
Comment: Os Forms estão dentro da DGV?
Comment: Sim, estão todos dentro da DGV, mas não estou a conseguir fazer a ligação de ao fazer o *doubleclick* na coluna do tipo de jogo.
Answer: Eu entendi mais ou menos mas vou fazer meu maximo.
pelo que entendi vc quer que em um dataview quando dado duplo click ele abra algo um form pelo que entendi
então vc poderia utilzar o evento de click junto com posição do mause
Codigo De Exemplo:
bool Click = false;
Point Cell = new Point(-1, -1);

private void Dgv1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            // Si possivel dezativar o multiselect antes melhor
            DataGridViewHistory.MultiSelect = false;

            // Verifica si esta na coluna certa
            if (dataGridView1.CurrentCell.ColumnIndex != dataGridView1.Columns["Jogos"].Index) return;

            if(Click == false)
            {
                 Click = true;
                 Cell = new Point(DataGridViewHistory.SelectedCells[0].RowIndex, DataGridViewHistory.SelectedCells[0].ColumnIndex);
            }
            else if (Click && Cell == new Point(DataGridViewHistory.SelectedCells[0].RowIndex, DataGridViewHistory.SelectedCells[0].ColumnIndex))
            {
                 Click = false;
                 Tela.Show();
            }
            else if (Click == false)
            {
                 Click = true;
                 Cell = new Point(DataGridViewHistory.SelectedCells[0].RowIndex, DataGridViewHistory.SelectedCells[0].ColumnIndex);
            }
        }

Explicação eu criei um bool para poder determinar quando for o 2° click
e um point para ajudar a armazenar a colum e a row que foi selecionada e comparar si foi a mesma celula a ser clicada.
|> quando vc clica uma cellula o codigo seta o valor do point cell para o da célula selecionada.
|> quando vc da mais um click na mesma celula ele confere si e a mesma célula e si é si for o 2 click execulta ou abre o form
|> quando vc click pela 2 vez só que e em outra celula ela e seta para o ponto do 1° click para ele
Qualquer duvida só perguntar.


knockoutjs when checked data binding call function

Question: I need to do following things: When user checks the checkbox, some function is called.
<input type="checkbox" data-bind="what to write here?" />

and in model:
var viewModel = {
    this.someFunction = function() {
       console.log("1");
    }
};

I have not found anything about this is documentation here.
Answer: What you need is the click binding:
<input type="checkbox" data-bind="click: someFunction" />

And in your view model:
var ViewModel = function(data, event) {
    this.someFunction = function() {
       console.log(event.target.checked); // log out the current state
       console.log("1");
       return true; // to trigger the browser default behavior
    }
};

Demo JSFiddle.
Or if you want to you use the checked binding you can subscribe on the change event of your property:
<input type="checkbox" data-bind="checked: isChecked" />

And in your viewmodel:
var ViewModel = function() {

    this.isChecked = ko.observable();

    this.isChecked.subscribe(function(newValue){
        this.someFunction(newValue);
    }, this);

    this.someFunction = function(value) {
        console.log(value); // log out the current state
        console.log("1");
    }
};

Demo JSFiddle.
Comment: Is it possible to distinguish when checkbox is selected and when unselected?
Comment: When using the `subscribe` you get the value with: `this.isChecked.subscribe(function(newValue){` see http://jsfiddle.net/qx8DC/1/ and in the click binding case you can get with  `this.someFunction = function(data,event) {
        console.log(event.target.checked);` see: http://jsfiddle.net/GH2tJ/1/


$2019^{2n}$ can be expressed as a sum of ten different positive squares, for every positive integer $n$.

Question: Show that $2019^{2n}$ can be expressed as a sum of ten different positive squares, for every positive integer $n$.
I have tried to solve this problem considering first particular cases and then expressing 2019 as the sum of two integers and trying to use and apply Newton's binomial, but I have not taken what is wanted. I would like to know if there is a less cumbersome test using perhaps a simpler method.
Answer: Hint: if $2019^{2m} = a_1^2 +\ldots + a_{10}^2$, then
$2019^{2m+2} = (2019 a_1)^2 + \ldots + (2019 a_{10})^2$.  So you really only
need to do it for $m=1$.
Comment: I don't understand why it is enough to do it for $m = 1$ Could you explain this please.
Comment: As the hint shows, if it's true for $m$ then it's true for $m+1$.  Use mathematical induction.


Eclipse Helios Integration of Maven 2 and Web Projects

Question: I have m2eclipse and its extras installed and am using Helios/Mvn2/jdk6/Tomcat 7/MacOs. I've been able to create a test maven webapp and run it on Tomcat 7 in Eclipse. But I can't get an existing application to 'Run on Server' via Eclipse. I've run into numerous configuration issues, almost all to do with the Eclipse .project/.classpath/.settings files. I've removed and recreated them many times, even copying the config files from the webapp that worked. I can't locate any documentation from Eclipse that goes through the basics and explains how to configure these files. Is there any such documentation?
At the moment, the application doesn't seem to be deploying the webapp files; tomcat can't find them.
I can launch tomcat outside Eclipse, build and deploy the application as a war successfully, but in Eclipse there is still this configuration issue.
<code> <wb-resource deploy-path="/" source-path="/src/main/webapp"/>
     .settings/org.eclipse.wst.common.component
</code>
Not sure what is missing, as the configuration is the same between the the two apps. Any help would be appreciated. Thanks!
Comment: Have you tried opening the project as a **maven** project in Eclipse after doing an `mvn eclipse:clean` (to remove existing eclipse configuration)?
Answer: .settings/org.eclipse.wst.common.component isn't meant to be edited manually - unless you have to add a workaround for some specific bug.
When using m2eclipse, m2eclipse will create/modify .classpath, .project and any file under .settings automatically. Generation/modification happens on project creation, checkout, modification of pom.xml and on right-click on project with selection of Maven->"Update Project Configuration". For web applications, m2eclipse uses some values from your configuration of the maven-war-plugin in your pom.xml to generate these files. For details see Integration of m2eclipse and WTP. Instead of editing manually, you should change your pom.xml and settings in Eclipse.
I recommend re-creating the project according to this tutorial. See this stackoverflow answer for additional hints.
Concerning the documentation of org.eclipse.wst.common.component: The content of this file can safely be modified in Eclipse under Project->Properties->"Module Assembly". Just add/remove different folders and references and see how org.eclipse.wst.common.component changes.


C++ Variable number of std::vector arguments results in exception: std::bad_array_new_length

Question: I'm trying to pass a variable number of std::vector to a function, but I get the below exception.
I'm using Visual Studio 16 2019
#include <iostream>
#include <vector>
#include <cstdarg>
#include <type_traits>
#include<tuple>

class Test
{
public:

    template <class ...Trgs>
    void funct(...)
    {
        int n = 2;
        va_list vr;
        va_start(vr, n);

        if (std::is_same<std::tuple_element<1, std::tuple<Trgs...> >::type, std::vector<int> >::value)
            std::cout << "true" << std::endl;

        using ResultType = typename std::tuple_element<0, std::tuple<Trgs...> >::type;

        ResultType x = va_arg(vr, ResultType);

        using ResultType2 = typename std::tuple_element<1, std::tuple<Trgs...> >::type;

        ResultType2 y = va_arg(vr, ResultType2);

        va_end(vr);
    }
};

int main()
{
    Test t;
    std::vector<bool> c = { 0 };
    std::vector<int> d = { 1 };
    t.funct<std::vector<bool>, std::vector<int> >(c, d);

    for (int i = 0; i < c.size(); ++i)
        std::cout << c[i] << std::endl;
}

I get the following exception:
Unhandled exception at 0x76B74662 in TestT.exe: Microsoft C++ exception: std::bad_array_new_length at memory location

at this line:
ResultType x = va_arg(vr, ResultType);

Is this related to the fact that some compilers have issues with variable number of arguments when the arguments are structures/classes?
Answer: C-ellipsis is different than variadic template.
C-ellipsis accepts just a limited kind of type (std::vector is not part of those).
You don't need C-ellipsis here:
template <class ...Ts>
void funct(const Ts&... args)
{
   // ...
}

Answer: As Jarod42 already stated, you missed to really refer to newer C++ variadic templates and mixed things up a bit here. You're not the first one with that issue, it's quite likely to happen.
For the actual reason why you crashed (be happy with that, several online compilers run fine here though it is undefined behavior actually... MS VS2017 emits warnings at least), see here for instance:
https://learn.microsoft.com/bs-latn-ba/cpp/error-messages/compiler-warnings/compiler-warning-level-4-c4840?view=msvc-160&viewFallbackFrom=vs-2017


How to escape javascript code in php

Question: I´m working on php to send data to ajax.
<code>        $phpArray = array("ok", "
          <script>
        mygallery = [
                        {type: "image", image: "img/gallery/slider/1.jpg", thmb: "img/gallery/slider/thumbs/1.jpg", alt: "", title: "", description: "", titleColor: "#000000", descriptionColor: "#000000"},
        {type: "image", image: "img/gallery/slider/2.jpg", thmb: "img/gallery/slider/thumbs/2.jpg", alt: "", title: "", description: "", titleColor: "#000000", descriptionColor: "#000000"},
</script>"
        );
     echo json_encode($phpArray);
</code>
How to do the escape properly for this ? I have tried online javascript escape but doesn´t work
Comment: And the problem is?
Comment: The problem is I can not get it work because I have ("")
Comment: Just ran this locally and works as expected for me.
Comment: Annnnnnnnnnd now you change the question in it's entirety. Do as you previously had, replace all `"` with `'`, or just escape every `"` with `\"` I just tried both of these solutions and they both work, and print the expected value.
Comment: This is  PHP file. I think yo misunderstood me. I want to send this data to javascript file. As you can see if you have ("") you can not send it unless you have correct backspace to ("")
Comment: I am sorry I wrote it wrong.
Comment: You are JSON encoding it, the output is properly JSON encoded. Your question is unclear, and I am voting to close as such.
Answer: Just escape the " with backslashes:
<code>$phpArray = array("ok", "
          <script>
        mygallery = [
                        {type: \"image\", image: \"img/gallery/slider/1.jpg\", thmb: \"img/gallery/slider/thumbs/1.jpg\", alt: \"\", title: \"\", description: \"\", titleColor: \"#000000\", descriptionColor: \"#000000\"},
        {type: \"image\", image: \"img/gallery/slider/2.jpg\", thmb: \"img/gallery/slider/thumbs/2.jpg\", alt: \"\", title: \"\", description: \"\", titleColor: \"#000000\", descriptionColor: \"#000000\"},
</script>"
);
echo json_encode($phpArray);
</code>
Comment: Thank you for you reply. But the script I am using in javascript only accept double quotes
Comment: It actually work !! but I think because I send  inside data that is why ?
Comment: Yes that changes a lot, looks way different when you do it without, just tested it on my server. But i am happy that it works as needed/wished
Comment: No actually not yet because I have issue with
Comment: Oh okay not good^^ so just tell me what it should look like at the end in the sourcecode at the frontend
Comment: When I put this code directly to the index.php it works.
But when I pass it through ajax it doesn´t work.
Comment: AHH sorry i overread that you send it with ajax TO server.. okay i had same/similuar issue on one of my sites.. one moment
Comment: var dataString = YOUR DATA IN ARRAYFORM
var jsonString = JSON.stringify(dataString);
   $.ajax({
        type: "POST",
        url: "script.php",
        data: {data : jsonString},
        cache: false,

        success: function(){
            alert("OK");
        }
    });
In your PHP:

$data = json_decode(stripslashes($_POST['data']));

How to escape javascript code in php


How to add Javascript tag in the head tag?

Question: I want to add Javascript in Head Tag. I found an answer in
How to add script to ? but it doesn't work for a theme.
function mytheme_preprocess_page(&$vars, $hook) {
  drupal_set_html_head('');
  $vars['head'] .= drupal_get_html_head();
}

Can I add JavaScript code in the  tag through page.tpl.php?
Comment: Have you read [Managing JavaScript in Drupal 7](https://drupal.org/node/756722)? And docs of [`drupal_add_js()`](https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_add_js/7)?
Answer: Here's the link to the full document on module developing aspect which I assume is not your main goal, there are some ways that you wanna skip for now, my suggestion is depending on the theme you are using, is to do it via .info file.   the easiest and common way.
This link is a very good guide for adding js files to omega subtheme, you may find it useful.
The .info file approach:
first open your theme's .info file that it should be something like YOURTHEMENAME.info
if you are using a subtheme there must be already some js files in there, you can find them and use them as an example.
what you wanna do is to add your js file like this:
scripts[] = somescript.js

this way the js file will be added to head of your website, remember after each time of editing a .info file you need to clear cache.
Adding External js to your site:
In your theme's template.php file use drupal_add_js() to the page preprocess method (or an equivalent preprocess).
function hook_preprocess_page(&$vars) {
  drupal_add_js('http://cdn.jquerytools.org/1.2.6/jquery.tools.min.js', 'external');
}

Edit: also with the extra info you just provided regarding using functions in the header you need to make a custom tpl file, locate the file that has  tag in your theme, it most likely be html.tpl.php (depends on the base theme you are using) if you couldnt find it you can copy it from modules/system/html.tpl.php and paste it into your theme's folder. edit the name of your file as this:
html--node--id.tpl.php like html--node--1.tpl.php and clear cache afterwards. edit the file as you wish and you must be good to go.
Comment: It appears to me OP needs external js, so the info file is of no use. But maybe that's only my impression based on the question he linked to in his own?
Comment: yea I actually just noticed the link, anyhow I edited the answer and added the external js thing too.
Comment: It is adding path link, as below

but I want to add script as below in head tag
Comment: do you want it to be on a specific page or all of your pages?
Comment: I need only for specific page.
Comment: Then first you need to edit your question and add extra information you just provided in this comment and I'll add the details in the answer on how to do it.
Answer: The drupal_add_js  function takes an $options argument.
This is an array that may have a value for key scope as header that would place the JS file specified in the header part of your template.
drupal_add_js('path/to.js', array('scope'=>'header'));

Another way if you are working in a module :
Add this in your module's .info
scripts[] = somescript.js
Comment: `drupal_add_js` is deprecated in favor of using the `#attached` key in render arrays.
Comment: really ? I can't see that anywhere on the API documentation... weird, I would still use it as far as D7 is concerned
Comment: I read that link you posted in a comment on the other answer and it only concerns D8 so `drupal_add_js` still looks like a viable solution for @jdln 's issue
Comment: Yes, it will work in D7.  However, there is an active push to try to get people to stop using these functions for new code as it will make the D8 transition harder.  For example, we try to mention whenever we see it during the project application review process.
Answer: You can add something like this on your page. Use path and argument to identify the correct page. Or you can add it in hook_init but in that case it will display on all pages which is not recommended.
drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });',
    array('type' => 'inline', 'scope' => 'header', 'weight' => 5)
  );

Alternatively you can use drupal_add_html_head like the following
 $inline_script = <<<EOL

      </script>
EOL;
    $element = array(
      '#type' => 'markup',
      '#markup' => $inline_script,
    );
    drupal_add_html_head($element, 'jquery-tmpl');

Comment: `drupal_add_js` is deprecated in favor of using the `#attached` key in render arrays.
Comment: Finally found your sample how to add custom markup like JSON-LD snippets as in schema.org microdata to the head! Thanks a lot!
Answer: You can add javascript to head by using theme_preprocess_html()
function theme_preprocess_html(&$var) {
  $script = array(
    '#tag' => 'script',
    '#attributes' => array('type' => 'text/javascript'),
    '#value' => 'Add your javascript here',
   );
   drupal_add_html_head($script, 'script');
}

Answer: Sure thing! drupal_add_js is your friend here. Documentation for Drupal 7 is here: https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_add_js/7
Basically, with drupal_add_js you get to select where the JS gets added, from a set of predefined options, which consist of 'header', 'footer', and your regions. So your function call, assuming this is a file in your module/theme, would look something like this:
drupal_add_js($path_to_js_file, array('scope' => 'header'));

There's a bunch more options you can use, like type to define the sort of JS you're adding (inline, external, etc) and weight to define the weight of the JS file relative to other JS files. There's more about that on the page linked in the first paragraph.
As for where this goes, I usually put mine in a hook_init function if it's part of a module, or in my hook_preprocess_html function if it's part of my theme.
There's also the option, if you have an html.tpl.php file that you can edit, of directly adding the JS to there. I'm not sure that that's the preferred method, though, and you can't sort where it lands in the list of other JS; it has to either be before the other JS is printed to the page or after it. Overall, not ideal.
Comment: `drupal_add_js` is deprecated in favor of using the `#attached` key in render arrays.
Comment: I thought it was only deprecated in D8?
Comment: It was deprecated for D7 a couple of years ago @Erin (but not removed, for BC reasons)
Comment: @ErinMcLaughlin Yeah, deprecated in D7 and gone in D8, https://www.drupal.org/node/2169605
Comment: Daaang I am behind the times apparently. Can someone post an answer on how you would do this the proper way with a render array from both a module and a theme? I still can't quite wrap my head around render arrays.


Mapa mostrar localização atual

Question: Gostaria de saber como fazer para que o mapa mostrasse a localização atual do usuário.
Criei este código que aparentemente estava funcionando, só que algumas vezes ele não consegue pegar o local e a aplicação da erro.
public class VisualizarMapa extends FragmentActivity {

protected GoogleMap map;

@Override
protected void onCreate(Bundle icicle) {

    super.onCreate(icicle);
    setContentView(R.layout.visualizarmapa);

    getActionBar().setTitle("Visualizar Mapa");
    getActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));

    SetupMapNull();

}

private void SetupMapNull(){

    if (map == null){

        map = ((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

        if(map != null){
            setUpMap();
        }

    }

}

private void setUpMap() {

    map.setMyLocationEnabled(true);

    LocationManager locationmanager = (LocationManager)getSystemService(LOCATION_SERVICE);

    Criteria criteria = new Criteria();

    String provider = locationmanager.getBestProvider(criteria, true);

    Location localatual = locationmanager.getLastKnownLocation(provider);

    map.setMapType(map.MAP_TYPE_HYBRID);

    double lat = localatual.getLatitude();
    double longi = localatual.getLongitude();

    LatLng LatLong = new LatLng(lat, longi);

    map.moveCamera(CameraUpdateFactory.newLatLng(LatLong));

    map.animateCamera(CameraUpdateFactory.zoomTo(19));

}

}
LogCat:
02-02 23:13:37.267: E/AndroidRuntime(9556): Process: br.find.me, PID: 9556
02-02 23:13:37.267: E/AndroidRuntime(9556): java.lang.RuntimeException: Unable to start activity ComponentInfo{br.find.me/br.find.me.VisualizarMapa}: java.lang.NullPointerException
02-02 23:13:37.267: E/AndroidRuntime(9556):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2202)
02-02 23:13:37.267: E/AndroidRuntime(9556):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2252)
02-02 23:13:37.267: E/AndroidRuntime(9556):     at android.app.ActivityThread.access$800(ActivityThread.java:139)
02-02 23:13:37.267: E/AndroidRuntime(9556):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200)
02-02 23:13:37.267: E/AndroidRuntime(9556):     at android.os.Handler.dispatchMessage(Handler.java:102)
02-02 23:13:37.267: E/AndroidRuntime(9556):     at android.os.Looper.loop(Looper.java:136)
02-02 23:13:37.267: E/AndroidRuntime(9556):     at android.app.ActivityThread.main(ActivityThread.java:5103)
02-02 23:13:37.267: E/AndroidRuntime(9556):     at java.lang.reflect.Method.invokeNative(Native Method)
02-02 23:13:37.267: E/AndroidRuntime(9556):     at java.lang.reflect.Method.invoke(Method.java:515)
02-02 23:13:37.267: E/AndroidRuntime(9556):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
02-02 23:13:37.267: E/AndroidRuntime(9556):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:606)
02-02 23:13:37.267: E/AndroidRuntime(9556):     at dalvik.system.NativeStart.main(Native Method)
02-02 23:13:37.267: E/AndroidRuntime(9556): Caused by: java.lang.NullPointerException
02-02 23:13:37.267: E/AndroidRuntime(9556):     at br.find.me.VisualizarMapa.setUpMap(VisualizarMapa.java:70)
02-02 23:13:37.267: E/AndroidRuntime(9556):     at br.find.me.VisualizarMapa.SetupMapNull(VisualizarMapa.java:49)
02-02 23:13:37.267: E/AndroidRuntime(9556):     at br.find.me.VisualizarMapa.onCreate(VisualizarMapa.java:36)
02-02 23:13:37.267: E/AndroidRuntime(9556):     at android.app.Activity.performCreate(Activity.java:5275)
02-02 23:13:37.267: E/AndroidRuntime(9556):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
02-02 23:13:37.267: E/AndroidRuntime(9556):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2166)

Comment: Editei agora!!!
Comment: E qual é o erro? [Edite](http://pt.stackoverflow.com/posts/49162/edit) a sua pergunta incluindo essa informação.
Answer: Utilizei o código abaixo:
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
    @Override
    public void onMyLocationChange(Location location) {
        LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
        mMarker = mMap.addMarker(new MarkerOptions().position(loc));
        if(mMap != null){
            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
        }
    }
};

Então set no seu mapa:
mMap.setOnMyLocationChangeListener(myLocationChangeListener);

Answer: Cara, tente isso aqui:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.the_map)).getMap();

    mMap.setMyLocationEnabled(true);

    myPosition = getMyLocation();

    markerClicked = true;
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myPosition, 18));

}

private LatLng pegaMyLocation(){
    try{
        // Getting LocationManager object from System Service LOCATION_SERVICE
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        // Creating a criteria object to retrieve provider
        Criteria criteria = new Criteria();

        // Getting the name of the best provider
        String provider = locationManager.getBestProvider(criteria, true);
        // Getting Current Location
        Location location = locationManager.getLastKnownLocation(provider);

        if(location!=null){
            // Getting latitude of the current location
            double latitude = location.getLatitude();

            // Getting longitude of the current location
            double longitude = location.getLongitude();

            LatLng my = new LatLng(latitude, longitude);

            return my;
        }
    }catch(Exception e){
        Log.e("Erro", "(pegaMyLocation) : "+e);
    }

    return null;
}

Comment: Batendo o olho, me parece que esse código cai no mesmo problema do código da pergunta. O método `getLastKnownLocation()` pode retornar `null` e quebrar o restante do código, no caso quando `myPosition` é passada para o método que movimenta a câmera.
Comment: "pega" o mapa, habilita MyLocation, chama um método, responsável por pegar a Localização (lembrando que no AndroidManifest deve ter a permissão de GPS), o método retorna um objeto LatLng, que é passada como parâmetro para o método moveCamera...
respondido?
Answer: É assim que eu faço
private FusedLocationProviderClient mFusedLocationProvider;
MapView mMapView;
GoogleMap googleMap;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_estacionar, container, false);

    mMapView = (MapView) rootView.findViewById(R.id.mapView);
    mMapView.onCreate(savedInstanceState);

    mMapView.onResume(); // needed to get the map to display immediately

    mFusedLocationProvider = LocationServices.getFusedLocationProviderClient(getActivity());

    try {
        MapsInitializer.initialize(getActivity().getApplicationContext());
    } catch (Exception e) {
        e.printStackTrace();
    }

    mMapView.getMapAsync(new OnMapReadyCallback() {
        @Override
        public void onMapReady(GoogleMap mMap) {
            googleMap = mMap;

            googleMap.setBuildingsEnabled(false);
            if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
                return;
            } else {
                googleMap.setMyLocationEnabled(true);

                mFusedLocationProvider.getLastLocation()
                        .addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
                            @Override
                            public void onSuccess(Location location) {
                                // Got last known location. In some rare situations this can be null.
                                if (location != null) {
                                    googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 13));

                                    CameraPosition cameraPosition = new CameraPosition.Builder()
                                            .target(new LatLng(location.getLatitude(), location.getLongitude()))      // Sets the center of the map to location user
                                            .zoom(14)                   // Sets the zoom
                                            .build();                   // Creates a CameraPosition from the builder
                                    googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

                                }
                            }
                        });

            }

        }
    });

    return rootView;
}

Esse código também mostra como eu seto o mapa, caso seja necessário

Mapa mostrar localização atual


Is an anticipation capable of causing parallel 5ths?

Question:
This is in 4/4 time. To me this does not sound like parallel 5ths between the top 2 voices because there is a 3rd on beat 2 and the 5th is in the up beat before the chord. Can someone share their thoughts on whether or not they see something line this as perfect parallel 5ths or not?
Comment: A good rule of thumb -especially if you're painted into a corner like this- is to take advantage of the common tone F that is a member of both chords.  It immediately simplifies your work by eliminating a potential improper parallel
Comment: Also watch for a similar issue between soprano and tenor, with the staggered D–C octaves.
Answer: This would be a case of what we'd call Akzentparallele in german or indirect parallel., where we make use of diminuition to mask a parallel. This not an uncommon thing to do. In your cases there are two points to make though:
Notice how all your voices progress downwards. This is usually considered as not being elegant (especially as not only the single notes all move down but the pivotal notes do the same, notice how in your case if you only take the 1 of the measure the second measure would be the same as the first, just shifted down a third, creating something like a parallel fifth between Bass and Soprano as well as a parallel octave between Bass and Alto). Also the movement of soprano into a C while the alto remains on the Bb calls for a strong resolution of the alto into the A. Jumping off into the F sounds a bit unelegant.
So how can we solve this? Progressing into C F A C is not really an option because the use of 4-6 chords is quite restricted in strict 4-part writing. If we accept all Voices moving into the same direction we can instead resolve to F C A C. But suppose you let the bass start an octave lower you can use the same resolution to achieve a cross movement.
Answer: Yes, as @Lazy says, the anticipation masks the parallel.   But it's still there, and is emphasised  by the overall parallel motion.
But @armani, you've been asking questions about 'textbook' 4-voice harmony around here for quite a long time now.  Is this an actual piece of music?  It's time it started to be.   We're not in the year 1700 any more.   You've got a nice jumpy little tune, why not back it up in the same style?  Think 'Manhattan Transfer' rather than - well, whoever Bach's favourite vocal group was :-)   Embrace the parallel motion, embrace the syncopated rhythm!
Comment: @armani Textbooks may emphasize the "harmonic style of 18th Century European Musicians" (as Adam Neely puts it), but may not explicitly state that music as a whole is no longer constrained by those rules.  Depending upon the textbook, what you have may be as much a lesson in European music history as it is anything.
Comment: Laurence, yes it is actually the chorus to "can you feel the love tonight" from the Lion King :) I was trying to harmonize it
Comment: @armani In that case, why are you worried about the 'rules' of 18th century vocal writing?
Comment: @armani Hm, it is not really the rules of 18th centurey vocal writing. Rather it is an academic analysis of what makes the music of the baroque masters sound great. And knowing this is still of vast importance today. Quite often you might think: This one passage just does not sound right. And with the knowledge of voice leading rules you're much better equipped for trying to find the problem and to solve it. It is something you should know and ignore by intent, not by accident.
Comment: I second the notion that centuries-old rules of polyphonic counterpoint are not overly relevant to modern homophonic pop music.  Unless you're arranging this for an SATB choir, I wouldn't worry too much about the rules.
Comment: I am following the rules of my textbooks for now and they seem to make a fuss about those rules so I am not ready to disregard them yet
Comment: FYI the textbooks I am learning from are from this century... all of them, in fact some are quite new
Comment: @ibonyun  A bit of 'rule-breaking' is fine for modern SATB too!  It's good to strive for rich-textured individual parts.  But a reinforced melody, everyone in similar motion and damn the consecutives can sound good too.


converter conteúdo no input

Question: Galera uso um script em javascript para converter tudo o que digito, dentro do input para maiúsculo.
Porem tenho um input específico a onde não posso alterar seu conteúdo. Como posso fazer isso?
Segue o código:

// Converte minusculas em maiusculas
$(document).ready(function() {
  $('input').on('input', function() {

    // Armazena posição corrente do cursor
    var start = this.selectionStart,
      end = this.selectionEnd;
    this.value = this.value.toUpperCase();

    // Restaura posição armazenada anteriormente.
    this.setSelectionRange(start, end);
  });
});

<input type='text' name='video'>
<input type='text' name='video'>
<input type='text' name='video'>
<input type='text' name='video'>

<input type='text' name='nao_alterar'>
Comment: Mas onde quer apareça o texto em maiusculo?
Comment: em todos os input, menos no input name='nao_alterar'
Answer: Criar um evento executado em todos os inputs excepto naquele cujo nome é nao_alterar. Faça:

$('input').not('[name="nao_alterar"]').on('input', function() {

// Armazena posição corrente do cursor
var start = this.selectionStart,
  end = this.selectionEnd;
this.value = this.value.toUpperCase();

// Restaura posição armazenada anteriormente.
this.setSelectionRange(start, end);
  });

<input type='text' name='video'>
<input type='text' name='video'>
<input type='text' name='video'>
<input type='text' name='video'>

<input type='text' name='nao_alterar' placeholder="não alterar">
Comment: poderia só `$('input[name="video"]').on('click', ...`, e retirava o `.not(...)`
Comment: bom tinha que ser usando o código que eu postei, pois ele armazena o local do cursor.
Comment: desculpe. vou fazer
Comment: Editado @HugoBorges
Comment: muito bom, vlw mesmo. Tem como verificar o nome de forma ao contrário? Tupi assim ele ser executado para todos os nomes menos para o name='nao_alterar' ?
Comment: perfeito amigo, muito obrigado mesmo.
Comment: @HugoBorges isso foi exatamente o que fiz. Todos os inputs excepto onde o nome é "nao_alterar", `$('input').not('[name="nao_alterar"]')...`
Comment: De nada @HugoBorges

converter conteúdo no input


Implementing onChanged of MapChangeListener - why this lambda

Question: In my JavaFX, I attempted to have an ObservableMap<String, String> and a MapChangeListener that listens to keys and values changes(adding/removing a key or the corresponding value) and then does its job.
To make the listener be effective, the method to implement is:
void onChanged(MapChangeListener.Change<? extends K,? extends V> change)

What I first did, with a lambda expression, that doesn't generate any error:
map.addListener((MapChangeListener.Change<? extends String, ? extends String> change) -> {
    //code here to implement onChange method
}

And here is what I discovered, that still doesn't generate any error:
map.addListener((MapChangeListener<String, String>) change -> {
    //code here to implement onChange method
}

Note the position of the round brackets in this two different examples. The second seems to me to be a cast, but I really don't understand why this second option works.
Can anyone explain me this, please?
P.S.: Actually, I came accross this because I was dealing with a
ObservableMap<String, List<String>>,
that is a multimap, and the first "way" of the two above didn't work (with the right adjustments). /EDIT: I tried again with the first "way" and actually it does work, there was an error on the code I didn't notice END EDIT/. Then I tried with the second option, and it did work, and I was dazed. Then I discovered this same "behaviour" with a simple map <String, String> and this question has arisen.
Comment: Gave you an extra example which would illustrate the differences.
Answer: These two are equivalent. The first one, you are defining the parameter of the lambda expression - note that your bracket covers the whole change parameter. This allows the compiler to know which overload to match it against.
The second one is simply a cast. You are telling the compiler what kind of method signature to match this lambda against. (MapChangeListener<String, String>) casts the whole lambda expression into a MapChangeListener, so the compiler knows that it really is addListener(MapChangeListener). Since you have defined the single parameter defined by MapChangeListener, the compiler doesn't complain that it is wrong either.
Edit
Now that I have a bit more time, I would give you some concrete example that will help you understand a little more in depth.
public class Foo {
    public final void bar(IntfA a) {}
    public final void bar(IntfB b) {}
    public final void bar(IntfC c) {}
}

@FunctionalInterface
public interface IntfA {
    void doSomething(Double a);
}

@FunctionalInterface
public interface IntfB {
    void doSomething(Integer a);
}

@FunctionalInterface
public interface IntfC {
    void doSomething(Double a);
}

public class Test {
    public static void main(String[] args)
    {
        Foo foo = new Foo();

        foo.bar(a -> {}); // Ambiguous
        foo.bar((Integer a) -> {}); // Okay, this is IntfB
        foo.bar((Double a) -> {}); // Ambiguous between IntfA and IntfC
        foo.bar((IntfC) a -> {}); // No longer ambiguous since you specified that it's IntfC
        foo.bar((IntfC) (a, b) -> {}); // Method signature does not match IntfC
    }
}

Edit 2
It seems like you need a little more help here.
When you define a method bar(IntfA), you are expecting an object of IntfA, regardless whether IntfA is an interface type or a class type.
Then, lambda expressions are just compile-time convenient syntax. When I write foo.bar((Integer a) -> {}), the compiler will eventually turn it into Java bytecodes (within .class file) that is equivalent to this:
foo.bar(new IntfB() {
    public void doSomething(Integer a) {
    }
});

That equivalence is what we call Anonymous Class.
The biggest and possibly only difference in using lambda is, it makes your code shorter. Sometimes it makes your code more readable, sometimes it makes your code less readable.
Since lambda reduces the amount of things that you need to type out, it is very easy to have a lambda expression that is ambiguous for the compiler when there are overload methods like in the example. Remember that the compiler needs to figure out which overload first, then it will help you to instantiate the object for you.
When you write foo.bar((Double a) -> {}), the compile notices that you have a lambda expression that takes in one Double parameter and returns nothing. It will then look at the three overloads of bar(). It notices that both bar(IntfA) and bar(IntfC) takes in a functional interface, and both interface's method takes in one Double parameter and returns nothing. At this point, the compiler is not sure whether it should generate bytecodes equivalent to which two set of codes:
Choice 1:
foo.bar(new IntfA() {
    public void doSomething(Double a) {
    }
});

Choice 2:
foo.bar(new IntfC() {
    public void doSomething(Double a) {
    }
});

If you write foo.bar((IntfC) a -> {}), you are already hinting to the compiler that you want it to match foo.bar(IntfC) overload. The compiler sees that you have one parameter of unknown type, but since you have already tell it to match to IntfC, it will assume that parameter is Double.
Now to the last part, calling foo.bar(IntfA) doesn't automatically call the doSomething(Double a) method specified by IntfA. In my example the bar() methods did nothing, but normally people would write something useful.
Example again:
public final void bar(IntfB obj) {
    if (obj == null)
        System.out.println("I was waiting for an IntfB object but I got nothing!");
    else
        obj.doSomething(100);
}

foo.bar((Integer a) -> {
    System.out.println("I got " + a + " marks for my exam!");
});

This causes "I got 100 marks for my exam!" to be printed on the console.
Comment: @Kenna It's always nice to see that people are trying to understand. Some people just learn how to copy the right things and paste at the right place - probably works once or twice, not always.
Comment: Ok, this made me understand more, really. But I have a question. Whenever I see this, like in your example, I should expect to have `a1.doSomething(a2)` in the body of `bar` method, where to distinguish `a1` is of type `IntfA` and `a2` of type `Integer`. Am I right?
Comment: @Kenna I don't understand your question. It is impossible to have `a1.doSomething(a2)`
Comment: No, I meant that `foo.bar((Integer a) -> {})` gives the implementation of `doSomething(Integer a)` and then `bar(IntfA a)` is called. Now I should expect that inside `bar` I have a call to `doSomething(Integer a)`. But since the arguments of `doSomething(Integer a)` and `bar(IntfA a)` have the same name `a`, I wanted to distinguish and I said `a1` and `a2`. I just meant that I should expect to have a call of `doSomething` inside `bar`, otherwise `(Integer a) -> {}` would be uneffective because it is not called inside `bar`. Or am I missing something?
Comment: Perfect! Thank you so much Jai! Especially the last part was of my interest and you made me understand better. Infact, what I was meaning in my comments was that normally inside `bar`-like method there is a call to the `doSomething`-like method (that is implemented with the lambda or method reference or anonymous class), but if there isn't, `doSomething` method is not called (but is implemented).
Comment: Yes! You've got that right! Thank you so much again, Jai.
Answer: Lambda in reality doesn't require its type to be expressed unless there is an ambiguity.
If you would not type change it would conflict with addListener(InvalidationListener) that has the same argument length. There are 2 ways of solving this, either by explicitly expressing the type (your first snippet) or by directing the compiler to the correct overload (second), which has nothing to do with lambda semantics.
To reiterate the second point, say you have
void print(String s)

and
void print(Integer i)

calling
print(null) would cause an ambiguity. The solution is print((String)null) which is of course not a type cast, as null has no type, but rather a compiler note.


Why can anonymous users see my block, whose visibility is set to hide it for anonymous users?

Question: I have a block on one of my sites, in which all content is private.  Anonymous users don't see any of my content types, any of my views, blocks, etc.
The problem is one single block.  The problem block is the only one not created by a view or a module.  I created it simply by adding it via the block page interface.  I have set its visibility settings to be restricted to a certain role (not 'Anonymous', of course :-)).
However, this is the one piece of content that is still showing up on my site for anonymous users (before one logs in).  I've cleared cache multiple times, so that isn't the issue.
Has anyone else run into this issue?  Why would the block not respect the visibility settings?  I'm wondering if there are some modules that may be interfering with this or if there's another explanation I'm not seeing....
Comment: Can you provide screenshot of block settings form. Need to see other settings of block
Answer: The strangest thing fixed my issue.  I'm still not sure why.
I was placing the block in a certain region with the 'Context' module.  When I removed the block placement from that context and set it directly in the block's configuration page, the block stopped being visible to anonymous users.
Not sure why that would matter!  Placing blocks generated by views with the 'Context' module is not interfering with their visibility settings, but for some reason it was interfering with this one.  It's just a regular block with text, nothing funky.
In any case, that's what solved my problem...
Answer: I had a problem like that in my website which was caused by a totally unrelated module. In my case the coder module caused my admin page to break. But finding the module which caused the problem was very tedious. Just disabling the modules did not work. I had to move each module outside the modules folder, clear the cache and reload the webpage each time I did this. If the problem is caused by a module then you can make modifications as necessary.
Comment: Thanks for the ideas, Sharanc!!  Luckily, I found the culprit.  :-)
Answer: As per your own answer, it seems that you're using the Context module. That helps to answer to this part of your question:

Why would the block not respect the visibility settings?  I'm wondering if there are some modules that may be interfering with this or if there's another explanation I'm not seeing....

Actually, the Context module does not check (take into account) the "Block visibility settings". If you want that to be the case, then you need to use the Context Respect module. Some details about this module, from its project page:

Extends the Context module by making it respect default block settings.
This makes it so you can retain your block visibility when assigning them into various Contexts. You can also 'Override' from the block level to ignore Context Respect.

Alternative to context module
If you're using the Context module (only) to only show some block on selected paths (which you can't specify with the standard block visibility settings), then you may want to have a look at the Rules block visibility module as a valid alternative. Refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?" for more details about it.
By using this module as an alternative, you'd only have to create a Rules Component with Conditions to verify the path(s) on which to show the block, and to check the roles for which you want to show the block, it's that easy ...


Using DNS to redirect website

Question: I would like to redirect domain1.com to domain2.com using DNS. I would further like to redirect www.domain1.com to www.domain2.com.
For domain1.com zone file, do I need to have an A record or are CNAME records sufficient, e.g.
<code>*                               IN      CNAME           domain2.com.
www.domain1.com                 IN      CNAME           www.domain2.com.
</code>
The goal is that when visitors visit domain1.com or www.domain1.com, they go to domain2
Comment: DNS doesn't have the ability to 'redirect'.  What you have above says 'www.domain1.com is the same thing as www.domain2.com'.  Maybe that's what you want, but that's not a redirect which is at the HTTP protocol.
Comment: I edited a note in parenthesis into that comment: you may need to refresh your page. As for whether yoonix's comment helps answer the question...that doesn't matter. It's a comment. And a very applicable one, because you can't use DNS to perform a redirect. If you're not trying to accomplish a HTTP redirect, then please word your question differently. *Many* people think DNS handles website redirection.
Comment: OK, so it seems it is not possible??
Comment: @yoonix, that doesn't help answer the question.
Comment: You also [cannot use a CNAME at the root of a zone](http://serverfault.com/questions/613829/why-cant-a-cname-record-be-used-at-the-apex-of-a-domain), so that's yet another reason why you can't do this for `domain1.com`.
Answer: Impossible.
You can redirect using your web server configuration, or with your preferred scripting language (such as PHP).
With DNS you can only point to the server, like you did in your example, but the domain name won't change from one to the other.

Using DNS to redirect website


Is there music that recursively subdivides the beat in odd subdivisions?

Question: For example: 3/4 has 3 quarter notes per beat, and each quarter note subdivides into 2 eighth notes, 4 sixteenth notes etc. which makes the total count an even number (6/8 or 12/16 etc.)
Is there any example of music that subdivides the beat in three nth-notes, each of which are subdivided in 3 thirds or, 9 ninths or 27 twenty-sevenths? (like an hypothetical 3/3 subdivided in 9/9, 27/27 etc.).
Or analogously a hypothetical 5/5 whole note subdivided in 25/25, 625/625 (I know this'd be unplayable unless the tempo was very slow)
Whether this exists or not (and I am curious as to how this would sound), how would one go about notating such an experiment?
My first thought was taking my shortest note usage, lets say 27 sixteenth notes and group them by three, above them in the subdivision tree, I'd have 9 dotted eighth notes, and above them (if I'm correct) one half note tied to a sixteenth note, but I get the impression it would be kind of annoying to read (?)
Comment: I believe everything you're asking about can be achieved by using the appropriate time signature and various types of tuplets. Also in your last paragraph, 27 16th notes divided into 3's is actually 9 dotted 8th notes, not 9 dotted quarter notes.
Comment: 9/8 is `SwwMwwMww` (where `S`=strong, `M`=medium, `w`=weak), is that what you mean?
Comment: it's not what you're looking for, but [Nancarrow's player piano pieces](https://en.m.wikipedia.org/wiki/Studies_for_Player_Piano_(Nancarrow)) do some pretty crazy things with time.
Comment: @JohnBelzaguy Maybe a combination of tuplets and compound time if the recursion goes really deep.
Comment: (Oh, and yes: you're right that these experiments would be hard to read and/or play. By no means impossible for new-music performers, though, especially if you explain what's going on. You might also experiment, like Nancarrow, with using non-human playback, like MIDI.)
Comment: The lemon can be cut in as many pieces as you want it to be cut. You even get two lemons in a beat. Dont know why you think beats are divided in twos or fours rathet than threes or fives
Answer: 9/8 comes close, like in the third motion of Bach's A minor violin concerto, BWV1041

.
Answer: Use nested tuplets.
In Musescore you just select a note or rest and then hit  or use the add tuplet menu...
Answer: To the "are there example" part of the question: Not that I'm aware of. There are plenty of examples of "triple compound meter": Three beats, each divided into three, aka 9/8, but I'm not aware of any "five beats, divided into quintuplets." (Speculation as to why might be found under this question; aside from "because of how we've always done it," I suspect it's because 2 and 3 are prime numbers, and larger numbers like 5 or 7 are often conceptualized as combinations of them—5/8 is often notated in a way that makes it clear whether it's "two plus three" or "three plus two".)
As to how you would notate it: "tuplets" can be given in any amount. Simply beam together as many notes as you wish and write that number outside of the beam.
For instance, using 5: You might declare your time signature to be 5/4. (It would also be intriguing to continue the conceit at larger levels: organize the music in 5-bar phrases, and sections of 5 phrases each. Maybe there are 5 movements!) Then, to subdivide your beat, write 5 notes connected by a single beam, as if they are eighth notes, and write "5" outside the beam. For the next subdivision, connect 25 notes with a double beam and write "25."
You'll note: your example, using groups of 3, worked from "small notes up to big notes" and wound up with dotted quarters. This is not unreasonable, as an extension of "compound triple," but the fact that you wound up with dotted quarters is a quirk of this one scenario.
Comment: One only has to look at composers like Nancarrow or Adès to find examples of such time signatures. The error of your answer is that everything is still structured within the framework of bifurcated pulse, which is not what the OP is asking.
Comment: @jjmusicnotes Hm, one of us is not understanding the other. I don't mean to be discussing "bifurcation," i.e. divisive rhythm in multiples of two. Meanwhile, Nancarrow was the first name I thought of. I did a quick look over his work, but most of what I see is more about "x against y" relationships; I didn't see an example of "x subdivided into x parts, which are in turn subdivided into x parts."
Comment: @jjmusicnotes (Also, several have already mentioned that "time signature" doesn't tell a lot, and in fairness the OP only barely mentioned it.)
Answer: The famous Spanish Romance for classical guitar is written in 3/4 where each 1/4 is played as a triplet.
This does actually not sound very interesting in terms of rhythmic feeling, it's more about the beautiful harmony.
On the other side there are very interesting rhythms which are technically 4/4 but use a lot of syncopation to give the listener an odd time feeling.
In my opinion the time signature of a piece does not tell you a lot about rhythmic complexity.
Comment: This answer is only opinion and does not contain any factual information pertinent to the original question. A time signature *absolutely* gives information not only about rhythmic complexity, but about phrasing. A piece written 3+2/8 instead of 5/8 is quite literally telling you how the meter is divided. A piece written in 3/1 instead of 3/4 is quite literally telling you to *feel* the music "in one", which in turn shapes the phrasing.
Comment: I don't agree. The piece I given as example (that's what the OP asked for) is in 3/4 and it has a totally different feel and phrasing compared to e.g. a classical waltz which is also in 3/4.


Defining hook_menu() paths for specific base URLs

Question: I have a multi-site; each site has its own database but they all share the same codebase. I would like to know if there is a way to define hook_menu() paths at specific base URLs.
Being it a multisite, I have created a common module used by all the sites. I wanted something like this in hook_menu().
 if (base_url == 'wmc.en') {
   $items['wmc/contact-us'] = array('hook menu stuffs');
 }
 if (base_url == 'gmc.es') {
   $items['gmc/contact-us'] = array('hook menu stuffs');
 }

I tried this type of code, but hook_menu() doesn't seem to recognize base_url or $_SERVER['SERVER_NAME'].
Is it possible to achieve what I am trying to do?
Answer: If you want to use base url, you should first declare it as a global variable and then use it as $base_url. You should also note that $base_url will include the url scheme (i.e) http or https.
If you have a development or staging environment setup, your base url will probably differ between dev, stg and prod environments. In most of the cases, the production environment will be SSL enabled. So you may have to consider this as well while writing code.
In my opinion, as you have mentioned, you may use a different module and enable it only for the specific site. Or if you deliberately want it to be in a common module, consider using access arguments and define hook_permissions.
Comment: Yes I think I should use it as a site specific module as using $base_url conditions does not affect defining hook_menu items.
Answer: In hook_menu() you can access $base_url (not base_url), if you first define it as global (i.e. putting global $base_url as first line of the function) or you access it as $GLOBALS['base_url'].
Keep in mind that $base_url doesn't just contain the domain name, but its content is similar to 'http://example.com/directory_where_drupal_is_installed/'. If you want the domain name you get it with parse_url($GLOBALS['base_url'], PHP_URL_HOST).
That said, I would not use wmc.en/wmc/contact-us and gmc.es/gmc/contact-us as routes, since the domain name makes already the difference between a route and the other one. I would rather use the domain name to execute different code.
if (parse_url($GLOBALS['base_url'], PHP_URL_HOST) == 'wmc.en') {
  // Show the contact form for this domain.
}
elseif (parse_url($GLOBALS['base_url'], PHP_URL_HOST) == 'gmc.es') {
  // Show the contact form for this domain.
}

Comment: Thank you @kiamlalunao. Your solution seems to be the efficient so far. It is working.


Finding the maximum value in a matrix (C programming)

Question: I'm learning to code in C. I've wrote the following code to find the maximum value inside a matrix, but for some reason the program would return the highest value in the first row (87), except the desired 99. I can't find the flaw in the code. Would be really happy for some help!
#include <stdio.h>

int Maxmin(int a[][4], int row, int col) {
  int i, j, max;
  max = a[0][0];

  for (i = 0; i < row; i++) {
    for (j = 0; j < col; j++) {
      if (a[i][j] > max)
        max = a[i][j];
    }
    return max;
  }
}

void main() {
  int a[3][4] = {
    {  3, 87, 11, 23 },
    { 99, 78, 19, 44 },
    { 59, 60, 13, 14 }
  };

  int num;
  num = Maxmin(a, 3, 4);
  printf("%d\n", num);
}

Comment: Indent your code properly and consistently; your return statement in inside one of the loops.
Comment: why are you putting this in comment section and not in answer section?
Comment: Unbelievable, it's a beginner needing debugging suggestions NOT a typo
Answer: Not really easy to spot as usually bugs like this are down to i & j typos.
The return max; is inside the row's for loop.
Move it to the end of the function and then you'll examine every row of the matrix. I actually compiled and ran this fix.
The way to discover such errors, is to either put in extra print statements, like :
printf( "a[%d][%d]=%d ", i, j, a[i][j]);

Or to step through your program with a debugger, setting a break point on the code you're interested in.
Comment: Well, it's very easy to spot when stepped through with a debugger.
Comment: I have tried to tailor the answer for a beginner, everyone makes mistakes and sometimes it's the dumb stupid ones that are hardest to find.  I actually stopped using i & j for a while in the 80's because I spent days looking for a subtle bug in a large program which was basically invisble on the poor quality print outs of that time, as i & j were almost indistinguishable.


Allocate a child resource to two different parents resources (?)

Question: I have a articles blog like so:
(parent) Category: News
(child) article: news-1 written by author-tom
(child) article: news-2 written by author-bill
(parent) Category: Sports
(child) article: sports-4 written by author-bill
(child) article: sports-7 written by author-jack
(parent) Category: Weather
(child) article: weather-1 written by author-tom
(child) article: weather-3 written by author-jack
Author name is a template_variable. And for each article I input the author name manually.
The author names are clickable links. And what I want to achieve is that when a user clicks "author-bill", for example, that the user only sees ALL articles written by "author-bill", thus articles news-2 and sports-4. For "author-jack" the same (sports-7 and weather-3).
I cannot allocate a child to two different parents (i.e. to both the "news" category AND to "author-jack" for example...).
I am stuck in thinking about a feasible solution...
Answer: Use getResources to search all your categories for the author name template variable. You don't need to assign multiple parents [though if you insisted on doing that you could use a resource alias to fake it]
Your getResources would look something like:
<code>[[!getResources?
     &parents=`1,2,3` // your category ids
     &tvFilters=`author_name==[[+author_name]]` //pass the author in a placeholder

etc.
</code>
Read the docs: http://rtfm.modx.com/extras/revo/getresources
Comment: Thanks. I use MODx EVO so I would need to work with Ditto instead to implement your idea. Can I implement your proposal with Ditto too?


How to replace a specific element in a LinkedHashSet?

Question: With an ArrayList I would do something like
myList.set(myList.indexOf(oldItemNumber), newItemNumber);

Is there an easy way to achieve this for LinkedHashSet?
Comment: Related: [Ordered insertion in linkedHashSet, any performant way ?](http://stackoverflow.com/q/12826916)
Answer: Just use the put() method. It will update that specific entry.
Comment: The add() method just adds an element to my set. I want to replace a specific element int the LinkedHashSet.
Comment: Sorry I meant LinkedHashSet instead LinkedHashMap =/
Comment: @GedankenNebel Then the same logic applies. Use add() method.
Answer: From the documentation of LinkedHashMap:

Hash table and linked list implementation of the Map interface, with
  predictable iteration order. This implementation differs from HashMap
  in that it maintains a doubly-linked list running through all of its
  entries. This linked list defines the iteration ordering, which is
  normally the order in which keys were inserted into the map
  (insertion-order). Note that insertion order is not affected if a key
  is re-inserted into the map. (A key k is reinserted into a map m if
  m.put(k, v) is invoked when m.containsKey(k) would return true
  immediately prior to the invocation.)

So you can simply put() the new value in and it will keep it's current location in the ordering. If you want to add it to the end then remove the old value and then add the new one.
Comment: Sorry I meant LinkedHashSet instead LinkedHashMap =/
Answer: The question is meaningless for a Set. A new object added to the Set either equals an existing one (in which case nothing happens) or it doesn't (in which case it is added at the end).
There is no way to insert objects at specific locations without removing and re-adding everything.
You may want to look at TreeSet which allows you to keep an ordered set that will remain ordered by the provided comparator as you add and remove objects.
Comment: I think a TreeSet would be a better choice than. Thanks!
Answer: I solved this problem where a LinkedHashSet member object has a hash code which computes a value on only part of the object (ex its Name field).  Yes this is unconventional but I also had a matching equals() method. Two different objects can have the same hash code and appear equal but internally they have some different values.
An example would be a database record which has key which has to be unique. You need to replace the record with a new set of values, so you find and replace the record with the matching key with new values.
// Rebuild Linked Hash Set in original order with new element.
ArrayList<Item> newSet = new ArrayList<>(oldSet);
newSet.add(newSet.indexOf(oldItem), newItem);
oldSet.clear();
oldSet.addAll(newSet);

The arrayList will have the old values in the same order and the new item will get added in front of the old.  No need to remove the duplicate. When added to the old HashSet (LinkedHashSet) it only keeps the first occurrence of any duplicate hash codes.
Answer: use map.put(key ,value) if you will use same key it will replace previous value
Comment: @GedankenNebel The `Set` dont allows duplicate value and not ordered and also not indexed so we can not replace on index
Comment: Sorry I meant LinkedHashSet instead LinkedHashMap =/


git merge ou rebase

Question: Quando programo utilizando git, sempre utilizo merge da minha branch no master para adicionar novos códigos, porém algumas ferramentas gráficas como o smartgit fazem um rebase ao invés do merge.
Devo utilizar o comando rebase ou merge para adicionar minhas mudanças na minha branch master?
Answer: Vamos considerar o cenário abaixo para entender melhor o que ocorrer e qual opção usar:
--- A --- B --- C --- D --- remotes/origin/master
           \
            --- E --- F --- master

Digamos que você baseou seu trabalho no commit B, e criou os commits E e F, e, enquanto isso, foram adicionados os commits C e D no branch remoto. O merge pode funcionar de duas formas: fast forward e merge commit. O fast forward só funciona se você não fez commit nenhum, o que não é o caso. Nos casos em que o fast forward é possível, não há diferença entre usar ele e o rebase.
O merge commit vai ficar assim:
--- A --- B --- C --- D --- remotes/origin/master
           \           \
            --- E --- F --- M --- master

Isto é, ele cria o commit M, que tem dois pais: os últimos commits do seu branch e do branch que você está fazendo merge.
Já o rebase fica assim:
--- A --- B --- C --- D --- remotes/origin/master
                       \
                        --- E' --- F' --- master

A principal vantagem do rebase é que sua história permanece linear: todo commit tem um único pai. Mas note que os commits E e F não existem mais no seu branch: o que existem são commits E' e F', que são equivalentes aos E e F originais, mas diferentes. A principal desvantagem é a seguinte: digamos que você tenha publicado o seu branch no repositório "meurepo":
--- A --- B --- C --- D --- remotes/origin/master
           \
            --- E --- F --- master, remotes/meurepo/master

E outra pessoa fez fork desse seu repositório e fez algo nele:
--- A --- B --- C --- D --- remotes/origin/master
           \
            --- E --- F --- master, remotes/meurepo/master
                       \
                        --- G --- remotes/outrorepo/master

Agora você fez o rebase, e adicionou um commit:
--- A --- B --- C --- D --- remotes/origin/master
           \           \
            \           --- E' --- F' --- H -- master
             \
              - E --- F --- G --- remotes/outrorepo/master

Agora a outra pessoa tem problemas sérios. Os commits E e F e os commits E' e F' são diferentes, o que pode trazer sérios problemas para a outra pessoa se ela tentar fazer merge. Além disso, a outra pessoa não pode fazer um rebase com a mesma facilidade que você (é possível, mas requer que ela saiba exatamente o ponto em que você fez o rebase -- trivial acima, mas nem tanto na prática).
Vamos ver como fica a opção de fazer merge, e já vou incluir o branch da outra pessoa:
--- A --- B --- C --- D --- remotes/origin/master
           \               \
            --- E --- F --- M -- H -- master, remotes/meurepo/master
                       \
                        --- G --- remotes/outrorepo/master

Observe que agora foi criado um commit M. Esse commit tem dois pais: D e F. A principal desvantagem desse tipo de operação é justamente essa falta de linearidade. Fica mais difícil localizar o momento exato em que algum problema foi introduzido no código (no exemplo acima parece fácil, mas pense como fica se todo mundo faz merges desse tipo regularmente).
Existem duas vantagens. A primeira é que fazer merge disso é mais simples: como a história foi preservada, o git já sabe que os commits E e F são comuns entre remotes/meurepo/master e remotes/outrorepo/master, e podem ser ignorados na hora de verificar conflitos.
A outra vantagem é que é mais fácil entender o que as pessoas que estavam trabalhando no código estavam pensando. Digamos que uma outra pessoa criou um bug em H, causado pela interação de C com E. No caso de merge, ela sabe que C e E foram desenvolvidos de forma independente, e por isso a interação é inesperada. No caso do rebase, ela vai achar que você já sabia da interação ao criar E', pois a história é linear, e vai ficar na dúvida se foi intencional ou não.
A regra que me parece ser a mais recomendada é a seguinte: enquanto você não publicar seu branch, pode fazer rebase. Uma vez publicado, faça merge. Entretanto, rebases são muito utilizados na comunidade Linux, que é a criadora do git, o que serve de contraponto.
Comment: Bom ponto na última frase: rebase não é uma coisa possível de fazer com patches uma vez publicados.
Comment: Muito bem explicado. Os rebases são incríveis pra deixar o "desenho" bonito, mas pra trabalhar em conjunto são desaconselháveis, assim como afirmou o @epx acima. Agora se só você está com a "feature branch" no seu repositório, ou se tem certeza que só você mexeu nela, daí vale muito a pena fazer o `rebase`. Com o rebase, também, fica fácil retirar alguma funcionalidade caso seja necessário.
Answer: Depende em parte do seu gosto.
O "merge" reúne duas linhas de desenvolvimento separadas. É mais fácil de fazer e qualquer desenvolvedor pode a qualquer momento fazer um merge com o repositório "oficial".
Porém muitos mantenedores de projetos que usam Git não gostam dos commits de merge, pois eles são meio opacos. Cada commit de merge tem dois "pais" diferentes. A história do projeto deixa de ser linear.
Já o "rebase" permite reescrever a "história" do repositório. Entre outras coisas isto permite reformar seus commits antes de serem mandados ao repositório "oficial".
Isto permite manter a ilusão que o histórico do desenvolvimento é perfeitamente linear e serial, um commit tendo apenas um pai. Facilita muito, por exemplo, fazer um teste de regressão para localizar que commit introduziu um bug.
Para referência, artigos que escrevi a respeito: Git merge: one legitimate use and a goof e The many faces of git rebase

git merge ou rebase


Counting $5$-character long Passwords with a Fixed Starting and Ending Points

Question: Students are required to create $5$-character long passwords to access the library. The characters must be from lowercase letters or digits. Each password must start with a lowercase letter and end with a digit and contain at most $2$ digits. How many valid passwords are there?
Is this solution correct?
$(26×(26^3) ×10) + (26×(26^2×10)×10)$
Comment: That is not right.  How many have the extra digit in the second spot, or the third spot, or the fourth spot? They are all different.
Comment: Thank you for identifying the mistake brother!
Answer: 26 possibilities for the first character
10 possibilities for the last character (a digit)
2 cases:
there is a 2nd digit or there isn't.
case 1 : there is a 2nd digit
digit can go in any of 3 spots.
$T_1 = 3 \times 10 \times 26^2.$
case 2 : there is no 2nd digit
$T_2 = 26^3.$
Final answer:
$$26 \times 10 \times [T_1 + T_2].$$
Comment: Thank you so much brother, both of the above answers have cleared the concept. Next time, I'll look closely for the positions too. Thank you again mate!!!
Answer: Your solution is not correct.  As noted in the comments, you have not accounted for the fact that the extra digit can go in one of three different slots.  Given the constraints, there are $26^4 \times 10$ passwords with exactly one digit, and there are $3 \times 26^3 \times 100$ passwords with exactly two digits, so the answer is the sum of those two numbers, $26^3 \times 560$.
Comment: Ohh, alright I get it now, Thank you so much! I totally forgot about them being at different positions in the 3 slots. Basically, I was confused about how to do it, but now it's pretty clear. Thank you again!


Number theory and Dirichlet's principle problem

Question: Prove that there exists such a number, that can be divided by 2011 and ends with ...2010
Give me a hand, please. Unfortunately, i do not even know where to start.
Comment: Chinese Remainder Theorem
Comment: Consider the numbers $2010, 20102010, 201020102010, \cdots$. In the first 2012 numbers in the series there are two numbers with same remainder. See what you get when you subtract the two numbers with the same remainder.
Comment: Ok, will look into these. Thank a lot, all of you!
Comment: Can you solve the problem for smaller numbers? For instance *Prove that there exists such a number, that can be divided by $13$ and ends with $12$.* Please show the own effort... As it is, the (not explicitly stated) question is missing a lot of context... Adding context is important. (Else the question may be closed soon, there are good reasons to do it - as it stays there...)
Comment: Yes, thank for suggestion, but i solved it with some help of the people above.
Answer: Yes, that was pretty obvious, thanks for pointing out, Asher2211. I knew that algorithm before, but wasn't able to see it here for some reason
His part of solution:
Consider the numbers $2010,20102010,201020102010,⋯$.
In the first $2012$ numbers in the series there are two numbers with same remainder.
My continuation:
If we subtract these two numbers were are left with
$20102010...2010000...$
Now we can divide it by $10^n$(depending on zeroes) and we are left with a number that can be divided by $2011$ and ends
with $2010$ . We can do it because $2011$ does not have the same multipliers(in fact, it is a prime number) as $10$.
Comment: Please use mathjax https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference for the mathematical objects involved in the answer.
Comment: Thank you for reminding!