Google data proc logs error about insufficient resources but not failing

Question: I run apache spark java job on google dataproc. The job creates spark context, analyses logs and finally closes the spark context. Then creates another spark context for another set of analysis. This continues for 50-60 times. Sometimes I get the error Initial job has not accepted any resources; check your cluster UI to ensure that workers are registered and have sufficient resources repeatedly.
Based on answers on SO, this occurs when there isn't enough resource available while starting the job. But this usually happens mid job.
I want the dataproc job to error out and exit. But instead the job just logs this error. How can I make the job to fail. Also how can I prevent this error.
Answer: This could happen during job execution, because Spark on Dataproc runs driver in client mode (outside of Yarn), only when it needs to launch executors, Spark requests containers for its AppMaster and executors from YARN.
The error simply indicate there is not enough resources, usually you can find in the cluster's monitoring tab YARN Pending Memory > 0. You can manually scale the cluster up 1, or enable autoscaling 2.


Absolute value equality involving complex analysis

Question: I'm preparing for a complex analysis prelim which I'll take next summer by consulting Ahlfor's Complex Analysis: An Intro to the Theory of Analytic Functions of One Variable (3rd edition). My question pertains to Exercise 4 of  Chapter 1, Section 1.5, and it is as follows:
Show that there are complex numbers $z$ satisfying $$|z-a| + |z+a|= 2|c|$$ if and only if $|a| \leq |c|$. If this condition is fulfilled, what are the smallest and largest values of |z|?
Well, for the first part of the question I was able to show only one direction, i.e. if there are complex numbers $z$ such that $|z-a| + |z+a|= 2|c|$, then $|a| \leq |c|$ by applying the triangle inequality. Specifically, I did the following: $$ \begin{array} {lcl} 2|a| &=& |2a| \\ &=& |a-z+z+a| \\&\leq& |a-z| + |z+a| \\&=& |z-a| + |z+a| \\&=& 2|c|. \end{array}$$ Dividing both sides of the inequality by $2$ yields the result in one direction. The other direction is giving me trouble, and so is the second part of the exercise. Some helpful hints and advice would be much appreciated.
Comment: This is also called the [gardeners ellipse](https://en.wikipedia.org/wiki/Ellipse#Pins-and-string_method).
Answer: Draw it, and you'll see that's euclidean geometry, not complex analysis. Anyway, something like $z=ia\sqrt{\frac{|c|^2}{|a|^2}-1}$ should work.
To be more specific:
$$|z-a|=|a|\cdot|i\sqrt{\frac{|c|^2}{|a|^2}-1}-1|=|a|\cdot\sqrt{\frac{|c|^2}{|a|^2}-1+1}=|c|$$
$$|z+a|=|a|\cdot|i\sqrt{\frac{|c|^2}{|a|^2}-1}+1|=|a|\cdot\sqrt{\frac{|c|^2}{|a|^2}-1+1}=|c|$$
Edit: I didn't see the part about max/min.
The points that satisfy the equation draw an ellipse with foci in $a$ and $-a$. Clearly the minimum and maximum values of $|z|$ are on the axes. The first one is the one I've already written, the second one is realised by $a|\frac ca|$.
Comment: Wouldn't this suggestion you gave have to consider the restriction $a \neq 0$? Drawing it is fine, but I think the question asks to be a proof.
Comment: Well, if $a=0$, the exercise is not so difficult... Take $z=c$. Otherwise, you can check that the formula works: this is a correct proof. If you want to know where the formula comes from, you can draw a picture: the formula finds a point on the axis of the segment between $a$ and $-a$.
Comment: I think showing the converse may require $z= \frac{|c|}{|a|} a$. Then I can use the fact that $\frac{|c|}{|a|} \geq 1$ from there.
Comment: My answer is not clear? When $a\neq 0$, you have to use $z=ia\sqrt{\frac{|c|^2}{|a|^2}-1}$, and the fact that $|c|\geq|a|$ ensures that the square root is real.
Answer: You can rotate the complex plane so that $a$ is real.
Let $z= x+ i \,y$. Then the left hand side is
$$
\sqrt{(x+a)^2+y^2} + \sqrt{(x-a)^2+y^2}$$
is minimum when $y=0$, i.e when $z$ is real. Clearly all $z$ in the interval $[-a,a]$ satisfies the condition.
Hence $z=0$ is the minimum, $z=\pm a$ is maximum in magnitude
Note: Added as an after thought.
If you do not want to make the initial rotation, then just consider $z$ of the form
$$
z = \lambda \, (-a) + (1-\lambda) a = a \,(1 - 2 \lambda),~~~ 0 \le \lambda \le 1$$
and show that all these $z$ meet the requirement.
Comment: ?? $z=0$ implies $|z-a|+|z+a|=2|a|\neq 2|c|$.


implementing copy command using file my code is copying garbage?

Question: Implementing copy command using file my code is copying garbage.please help me to fix
   #include<stdio.h>
    int main()
{
    char ch;
    FILE *fp,*fp1;
    fp=fopen("source","r");
    if(fp==NULL)
    {
            printf("no file\n");
            return;
    }
    else
    {
            printf("file is present\n");
            fp1=fopen("dest","w");
            while(ch=fgetc(fp)!=EOF)
            fputc(ch,fp1); // why source contain is not copyed to dest?
    }
             fclose(fp);
             fclose(fp1);
}

Comment: Also, the return type of `fgetc` is `int`. You should change `char ch;` to `int ch;`.
Comment: Hint: http://en.cppreference.com/w/c/language/operator_precedence
Comment: You might want to read about [operator precedence](http://en.cppreference.com/w/c/language/operator_precedence), and then look again at your loop condition.
Comment: @RSahu upon success it return chararcter after converting it to an int without sign extension.Upon failure or end of file or error it return EOF ie -1
Comment: @carrercarrer, if you are not convinced that `int ch;` is the right thing to do, please checkout http://stackoverflow.com/a/23331786/434551.
Answer: while(ch=fgetc(fp)!=EOF)

is eqivalent to:
while(ch = (fgetc(fp)!=EOF))

thus gives ch values either 1 or 0 depending on whether fgetc(fp)!=EOF) is true. What you want is:
while((ch = fgetc(fp)) != EOF)


A basic doubt on some submatrix consisting of transient states of a stochastic matrix

Question: Consider a submatrix of a stochastic matrix where all the states are transient. So, $ Q^n\to  0$ which is clear to me. But why this implies that all of the eigen values of $Q$ have absolute values strictly less than 1.
Answer: Let $v$ be an eigenvector for $\lambda$, then $Q^n\to0$ implies $v^T\, Q^n\, v\to0$. But
$v^T\, Q^n\, v=v^T \lambda^n v=\lambda^n \|v\|^2,$ and this converges to zero only if  $|\lambda|<1$.


Maintaining 60 elements in a observablecollection

Question: Hi I have a ObservableCollection getting data in every minute. When it reaches an hour, I would like to clear the first item and move all the items up then adding the new item, thus maintaining it at 60 elements. Does anyone have any idea how to do so?
Here is my code:
public class MainWindow : Window
{
    double i = 0;
    double SolarCellPower = 0;
    DispatcherTimer timer = new DispatcherTimer();
    ObservableCollection<KeyValuePair<double, double>> Power = new ObservableCollection<KeyValuePair<double, double>>();

    public MainWindow()
    {
        InitializeComponent();

        timer.Interval = new TimeSpan(0, 0, 1);  // per 5 seconds, you could change it
        timer.Tick += new EventHandler(timer_Tick);
        timer.IsEnabled = true;
    }

    void timer_Tick(object sender, EventArgs e)
    {
        SolarCellPower = double.Parse(textBox18.Text);
        Power.Add(new KeyValuePair<double, double>(i, SolarCellPower ));
        i += 5;
        Solar.ItemsSource = Power;
    }
}

Answer: Just count the items in your list and remove the top item if the count equals 60. Then insert the new item like normal.
if (Power.Count == 60)
    Power.RemoveAt(0);

Power.Add(new KeyValuePair<double, double>(i, SolarCellPower ));

Also if you Bind your ItemsSource instead of setting it, it will update automatically when the collection changes.


Como alterar o conteudo "código" de uma section com javascript

Question: Oi, preciso alterar o conteúdo (código) de uma section com javascript com a função .click ou onClick mas o conteúdo não pode sobre por o da outra section! Obrigado
Answer: Se percebi bem o que quer, acho que é isto:

var btn = document.getElementById('btn-sect1');
var sect1 = document.getElementById('sect1');
btn = btn.addEventListener('click', function() {
  sect1.innerHTML = '
Agora já não é o original

Está aqui outro codigo html
'
});

Aqui está o codigo original da sect1

Aqui está o codigo original da sect2

<button id="btn-sect1">Mudar HTML da sect1</button>
Comment: No caso poderia adicionar mais de uma tag!
Comment: @user50404 Mais de uma tag? Como assim, mais de uma tag HTML dentro da section onde queremos alterar o HTML?


Reactive Extensions for Java

Question: Is there any equivalent of Reactive Extensions (.NET) for Java?
About Rx (Reactive Extensions)

Rx is a library for composing asynchronous and event-based programs using observable collections.

I am aware of rule engines such as Drools from JBOSS, but is there some other way that is closer to the Microsoft .NET approach?
Answer: According to this NetFlix blog post, they have ported Rx to Java.  It doesn't seem to be available yet, but they do have a history of releasing such internally developed tools as open source, so I expect it will be released eventually.
Answer: I'm not aware of one - and frankly it would be hard to do in such a neat fashion. The threading side is fine; Java's perfectly capable when it comes to threading... but at the moment, the language just doesn't support the appropriate features.
One of the neat design features of LINQ is that everything is based on interfaces and then extension methods are used to add extra functionality. That allows code to read fluently - imagine if you had to write:
IObservable<int> = Observable.Select(
                       Observable.Where(
                           source, x => x.SomeCondition)
                       x => x.SomeProjection);

Ick. The extension method is much more graceful:
IObservable<int> = source.Where(x => x.SomeCondition)
                         .Select(x => x.SomeProjection);

Now a Java version could be based on an abstract base class instead, but that would lose some of the elegance.
Next come lambda expressions and method group conversions - these really are fundamental to LINQ in general; the closest equivalent in Java (anonymous inner classes) are too ugly to be used everywhere you'd use a lambda expression in C#.
Basically, a Java version of Rx would be feasible, but it wouldn't be nearly as elegant as the C# version - which is probably why it hasn't been done as far as I'm aware. There may be other "asynchrony-driven" libraries around for Java, but they're unlikely to be as comprehensive and neat as Rx.
It's possible that the changes in Java 7 will make this more feasible; as far as I know extension methods aren't being introduced, but an abstract base class version would be reasonable if the lambda syntax ends up being okay...
Comment: You can now write this in Java: IObservable = source.where(condition()).select(selector()).toArray(); See github.com/nicholas22/jpropel-light
Comment: Ok, thanks. Maybe this is more feasible in Java 7 with closures.
Answer: If you are still interested, I've been working on a Java library lately, which offers most of the Rx operators on reactive and interactive side as well.
It is definitely not as nice as the .NET. Java does not have extension methods or function types, therefore, everything must be called via a static method and inner classes.
In .NET:
Observable.Range(0, 10).SelectMany(
    o => Observable.Range(0, o)
).Run(Console.WriteLine);

My library:
Reactive.run(
    Reactive.selectMany(
        Reactive.range(0, 10),
        new Func1<Observable<Integer>, Integer>() {
            public Observable<Integer> invoke(Integer param1) {
               return Reactive.range(0, param1);
        }
    }
), Reactive.println());

Interactive.run(
    Interactive.selectMany(
        Interactive.range(0, 10),
        new Func1<Iterable<Integer>, Integer>() {
            public Iterable<Integer> invoke(Integer param1) {
               return Interactive.range(0, param1);
        }
    }
), Interactive.println());

I use Func0, Func1, Func2 types for lambdas and Closeable type for unregistering. Once Java gets first class function citizens, these FuncX types can be simply replaced. Closeable can be used by a Java 7's try-with-resources enhancement. The third uglyness is due the weak type inference at various places.
Answer: RxJava (RX ported by Netflix) is available and stable here:
https://github.com/ReactiveX/RxJava.
It even works with Java 8's lambda syntax pretty well!
You can do stuff like that:
Observable
  .from(Arrays.asList(1, 2, 3, 4, 5))
  .filter(val -> val % 2 == 0)
  .map(val -> val * val)
  .scan(0, (prev, curr) -> prev + curr)
  .subscribe(System.out::println)

Pretty cool a?
Answer: You might consider porting raix (wiki), written in ActionScript 3, to Java 7 when it arrives. The project (my own) is opensource and includes black-box unit tests of the .NET version of the framework to ensure compatibility.
Like Java, AS3 supports neither extension methods nor lambda expressions so the implementation may be similar. Having said that, you would need to be careful with race conditions since the AVM doesn't support threads so there is no locking code in RxAs.
Answer: You can use the Project Reactor, which implements the Reactive Streams specification. It offers two Publisher interfaces: Mono and Flux.
Mono can emit 0 or 1 items, while Flux can emit 0…n items via the onNext signal.
A good tutorial on Reactive Programming in Java that covers Project Reactor is here.

Reactive Extensions for Java


PHP - Lumen: update retorna true mas não atualiza os dados na base

Question: sou iniciante em PHP - Lumen e estou fazendo minha primeira api. Todos os meus métodos no controller estão funcionando, exceto o update. Mesmo ele retornando true, os dados não são alterados na base.
<code>public function update(Request $request, $id)
{
    $agendamento = $this->model->find($id)
        ->update($request->all());

        return response()->json($agendamento);
}
</code>
Já verifiquei e o $request está trazendo os dados corretamente.
Comment: Existe alguma alteração para ser feita? Como está seu objeto antes e depois de enviar a request? Como estão os dados da requisição?
Comment: 1 -  GET/2
`{
    "Id": 2,
    "IdSala": 2,
    "EmailRequisitante": "firstname.lastname@example.com",
    "DataHoraInicio": "2019-12-06 15:00:00",
    "DataHoraFim": "2019-12-06 16:00:00",
    "Situacao": "Avitva",
    "Descricao": "Teste data e hora"
}`

2 - PUT/2
`{
 "Id": 2,
 "IdSala": 2,
 "EmailRequisitante": "email@example.com",
 "DataHoraInicio": "2019-12-06 15:00:00",
 "DataHoraFim": "2019-12-06 16:30:35",
 "Situacao": "Avitva",
 "Descricao": "Teste data e hora  MODIFICADO"
}`

Após o PUT, ao fazer um novo GET, os dados retornados permanecem como na primeira situação.
Comment: Meu mapeamento `$router->put("/{id}", "AgendamentoController@update");`
Answer: Ana, eu não tenho experiencia no Lumen mas no seu pai Laravel eu trato os dados antes de salvar ou atualizar, nunca chamo  o $request dentro do update mas antes mapeio os dados;
<code> $stockTeam = new StockTeam();
                $stockTeam->idTeam = $request->idTeam;
                $stockTeam->idSupplies = $request->idSupplies;
                $stockTeam->amount = $request->amount;
                $stockTeam->save();
</code>
Espero ter ajudado, essa é a forma que eu já trabalhei com Laravel já fiz isso também:
<code> DB::insert('insert into address_transfers
    ( name, type_id, plan_id, neighborhood_id, status_id, dot, user_id, description, created_at, updated_at)
        VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, current_timestamp, ?)',
     [ $request->name, $request->type, $request->plans, $request->hood, $request->status, $request->dot, Auth::id(), $request->description, $request->date ]);
</code>
Comment: eu tentei mapear os dados do request e mesmo assim não funcionou.
Comment: Eu passei boa parte do dia lendo isso. Descobri que o lumen "engana" as requisições PUT e PATCH e na hora de chamar no postman é preciso colocar os parâmetros em 'x-www-url-formurlencoded'. Mas não sei bem como seria a sintaxe para colocar todo o objeto que está sendo mandando dentro do request.
Comment: Ana vê se esses dois links podem te ajudar.

https://stackoverflow.com/questions/4007969/application-x-www-form-urlencoded-or-multipart-form-data

https://dev.to/sidthesloth92/understanding-html-form-encoding-url-encoded-and-multipart-forms-3lpa
Comment: o que resolveu pra mim foi colocar os nomes dos parametros do model todos em minusculo
Comment: Que bom que conseguiu.


How to store Tornado logs to a file?

Question: I've been facing issues where my server is throwing a 500 if the API isn't accessed for 30 mins at a stretch. To check the problem, I need to keep track of every single API request made. I'm using Tornado in front of Flask. This is my code so far:
import tornado.httpserver
import tornado.ioloop
import tornado.web
from flasky import app
from tornado.wsgi import WSGIContainer
from tornado.ioloop import IOLoop
from tornado.web import FallbackHandler

from tornado.log import enable_pretty_logging
enable_pretty_logging()

tr = WSGIContainer(app)

application = tornado.web.Application([
    (r".*", FallbackHandler, dict(fallback=tr)),
])

if __name__ == '__main__':
    application.listen(5000)
    IOLoop.instance().start()

Whats the most efficient way to store the logs to some file?
I tried doing this but it only works when the process exits with 0:
import sys
import time
timestr = time.strftime("%Y%m%d-%H%M%S")
filename = "C:/Source/logs/" + timestr + ".log"

class Logger(object):
    def __init__(self):
        self.terminal = sys.stdout
        self.log = open(filename, "a")

    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)

    def flush(self):
        pass

sys.stdout = Logger()

Answer: You have used enable_pretty_logging which is good, and if you might note the documentation says you can pass in a logger.  So what is a logger?  Turns out Python has very extensive support for logging actions through the builtin logging module (which is mentioned in the documentation too).  Generally, you need to set up handlers that write to some specific file, which you can do by
handler = logging.FileHandler(log_file_filename)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
logger.info('foo')

This will log all info level entries (or higher) into the file.  These loggers can be gathered by the logging.getLogger function, and you can explicitly select these as per the tornado documentation by
access_log = logging.getLogger("tornado.access")
app_log = logging.getLogger("tornado.application")
gen_log = logging.getLogger("tornado.general")

Simply append your handler to the logger that is generating the messages you want to log to a file.  If it's the tornado.application generating the messages you want to see
handler = logging.FileHandler(log_file_filename)
app_log = logging.getLogger("tornado.application")
enable_pretty_logging()
app_log.addHandler(handler)

Or you can also use the builtin tornado options that enable this
tornado.options.options['log_file_prefix'].set(log_file_prefix)
tornado.options.parse_command_line()

Comment: Thanks so much! Builtin tornado options totally worked.

How to store Tornado logs to a file?


How can we add custom template in keycloak?

Question:
I would like to add some custom tabs(template) in my keycloak? But i cant find the solution. Is anyone here who could help me with this.
Answer: Your screenshot suggest that you are still using the old account console. I recommend to upgrade to the new account console which supports adding additional tabs quite easily. Take a look at this blog post for details and check out this quickstart example to get going.


Moving drupal to a subdirectory

Question: I'm trying to move a Drupal site to a sub-directory of the same domain. I'm very experienced with WordPress but not experienced with Drupal sites. How would I move a website from http://example.com to http://example.com/old-website/ ?
I can't figure out what would cahnge so that I can migrate the site.
Any and all help is appreciated!
Thanks!
Austin
Answer: Just move the files, you don't need to set a base URL like in Wordpress.
If you do run into any problems, uncomment rewritebase in htaccess
Comment: The website now live at example.com/old-website/

Is there a simple way to use rewrite rules to make image links pointing here: https://www.example.com/sites/default/files/picture.png

to point to here: https://www.example.com/old-website/sites/default/files/picture.png
Comment: You should have always used relative urls instead of absolute urls which would make transferring the site really easy. I would use find and replace in your database to change the paths.

Moving drupal to a subdirectory


Show UIMenu without UIButton or UINavigationButton

Question: users.
I'm having an issue that I can't seem to figure out. I want to show a UIMenu when I press a row in my UICollectionView, so I've added a UIButton that spands edge-to-edge in each cell. When the button is pressed, a UIMenu appears. The problem is that the UICollectionView is not scroll-able with a UIButton in each cell. The system prioritises the UIButton over scrolling. I'd love to just have a UILabel and a menu showing when 'didSelectItemAt indexPath' is called, but UIMenus only work with UIButton and UINavigationBarButton.
If someone has a solution for me, please help out!
Thank you very much,
kind regards
Answer: I suspect and I could be wrong, you have set delaysContentTouches to false for the UICollectionView.
This would make any touch be interpreted as a button tap.
Instead of removing the button from the cell, here is my set up which sounds similar to yours and gives the desired end result:
Custom UICollectionView with a label and button that spans the whole collection view cell
class ButtonCollectionViewCell: UICollectionViewCell
{
    static let reuseIdentifier = "ButtonCollectionViewCell"

    let titleLabel = UILabel()
    let hiddenButton = UIButton()

    override init(frame: CGRect)
    {
        super.init(frame: frame)
        contentView.backgroundColor = .yellow
        configureLabel()
        configureButton()
        layoutIfNeeded()
    }

    required init?(coder: NSCoder)
    {
        fatalError("init(coder:) has not been implemented")
    }

    private func configureLabel()
    {
        contentView.addSubview(titleLabel)

        // Auto layout config to pin label to the edges of the content view
        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        titleLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
        titleLabel.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
        titleLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true
        titleLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
    }

    private func configureButton()
    {
        addSubview(hiddenButton)

        // I add this red color so you can see the button takes up the whole cell
        hiddenButton.backgroundColor = UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 0.75)

        // Auto layout config to pin button to the edges of the content view
        hiddenButton.translatesAutoresizingMaskIntoConstraints = false
        hiddenButton.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
        hiddenButton.topAnchor.constraint(equalTo: topAnchor).isActive = true
        hiddenButton.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
        hiddenButton.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true

        // Configure menu
        hiddenButton.showsMenuAsPrimaryAction = true
        hiddenButton.menu = UIMenu(title: "Select an option", children: [

            UIAction(title: "Option 1") { action in
                // do your work
            },

            UIAction(title: "Option 2") { action in
                // do your work
            },
        ])
    }
}

In the ViewController
class UICollectionViewButtonCellViewController: UIViewController
{
    private var collectionView: UICollectionView!

    override func viewDidLoad()
    {
        super.viewDidLoad()

        title = "Button Cell Example"

        view.backgroundColor = .white

        configureCollectionView()
    }

    private func configureCollectionView()
    {
        collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: createLayout())

        collectionView.register(ButtonCollectionViewCell.self,
                                forCellWithReuseIdentifier: ButtonCollectionViewCell.reuseIdentifier)

        collectionView.dataSource = self

        // do not have the below line of code, by default delaysContentTouches is true
        // collectionView.delaysContentTouches = false

        view.addSubview(collectionView)

        // Auto layout config to pin collection view to the edges of the view
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        collectionView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true
        collectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
        collectionView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true
        collectionView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
    }

    private func createLayout() -> UICollectionViewFlowLayout
    {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical

        let availableWidth = view.frame.width
        let interItemSpacing: CGFloat = 5

        // (available width - inter item spacing) / 2
        let itemWidth = (availableWidth - interItemSpacing) / 2
        layout.itemSize = CGSize(width: itemWidth, height: 100)
        layout.minimumInteritemSpacing = interItemSpacing
        layout.minimumLineSpacing = 5

        return layout
    }
}

extension UICollectionViewButtonCellViewController: UICollectionViewDataSource
{
    func collectionView(_ collectionView: UICollectionView,
                        numberOfItemsInSection section: Int) -> Int
    {
        return 20
    }

    func collectionView(_ collectionView: UICollectionView,
                        cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
    {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ButtonCollectionViewCell.reuseIdentifier,
                                                      for: indexPath) as! ButtonCollectionViewCell

        cell.titleLabel.text = "Tap cell \(indexPath.item)"

        return cell
    }
}

This gives me the desired output of a scrollable UICollectionView with it's taps leading to a UIMenu interaction.
Comment: Wow, amazing answer! Thank you so much, that really helped me out!
Answer: Step 1.
 public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = longcollection.dequeueReusableCell(withReuseIdentifier: "longcell", for: indexPath) as! longcell
        let interaction = UIContextMenuInteraction(delegate: self)
        cell.contentView.tag = indexPath.item
        cell.contentView.superview?.tag = indexPath.section
        cell.contentView.addInteraction(interaction)
        return cell
    }

Step  2.
// MARk: - Context Menu & Action Sheet

extension ViewController: UIContextMenuInteractionDelegate {

    public func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
        return UIContextMenuConfiguration(identifier: "anyIdentifier" as NSCopying, previewProvider: nil, actionProvider: { _ in
            let contextMenu = self.getContextMenu(data: "Copy this data")
            return UIMenu(title: "", children: [contextMenu])
        })
    }

    func getContextMenu(data: String) -> UIMenu {
        let systemIcon = UIImage(systemName: "square.and.arrow.up.circle.fill")
        let customICon = UIImage(named: "bin")

        let copyAction = UIAction(title: "Copy", image: systemIcon) { _ in
            UIPasteboard.general.string = data
        }

        let editImageAction = UIAction(title: "Edit", image: customICon) { _ in
            // Edit message
        }

        let infoAction = UIAction(title: "Info", image: customICon, attributes: .destructive) { _ in
            // write info code here.
        }

        let replyAction = UIAction(title: "Reply", image: systemIcon, attributes: .hidden) { _ in
            // Write reply code here.
        }

        let deleteAction = UIAction(title: "Delete", image: systemIcon, attributes: .disabled) { _ in
            // Delete message goes here
        }

        return UIMenu(title: "", options: .displayInline, children: [copyAction, editImageAction, infoAction, replyAction, deleteAction])
    }

}

You can follow this Github repo to understand better.


Accessing the index or a row in a matrix/ list of lists

Question: Without using numpy, my question is related to the for loop in Python, as it doesn't have for i=0, i++ ...
only
for i in list
I need
for i in list
  # print(i.index)
  # i.index being 0 at the first element of the list and
  # ordered to len(list)-1 at the last element

There is something I am missing :
mat=[[1,0,1],
     [1,1,1],
     [1,0,1]]

dict1= []
dict2= []
n=len(mat[0])
for row in mat :
    for j in range(n):
        if row[j]==0:
            dict1.append(mat.index(row))
            dict2.append(j)
print(dict1)
print(dict2)

output should be [0,2] and [1,1] but instead I am getting
[0,0]
[0,1]

How do we explain this?
Comment: Does this answer your question? [Accessing the index in 'for' loops](https://stackoverflow.com/questions/522563/accessing-the-index-in-for-loops)
Answer: Another possibility is for i,v in enumerate(my_list): print(i, v). The i value goes from 0 to len(my_list) - 1. The functionenumerate has keyword argument start that allow to specify where i starts (as above this defaults to 0).
Answer: Use .index()
l=[1,2,3]
for i in l:
    print(i,l.index(i))

1 0
2 1
3 2

Comment: .. What if `l = [1, 2, 1]`
Comment: @ssp , index() return just the first occurrence, so it is basically useless here
Comment: is this behavior standard in python? never at all the indices get mixed, say after altering the list?
Comment: This turns the simple loop into a nested for loop O(n^2)
Answer: Using .index() is okay, as long as the list does not have double entries, because index returns the index of the first occurrence of an item.
The for loop can iterate over an index i in some range as follows:
l=[1,2,3,5,6,7,3,1,89,2,77]
for i in range(0,len(l)):
    print(l[i], i)


Contour Integration of Inverse Hyperbolic Cosine

Question: I have the following integral
$$\int_1^\infty\frac{\text{arccosh}(x)}{x^2+1}\,dx$$
I am convinced that it can be done through contour integration, since we are integrating along the principle branch of the inverse hyperbolic cosine.  But I am unsure of how to handle the inverse hyperbolic cosine when I'm trying to collect the real valued integral along the branch cut.  My contour would be the keyhole contour that has a circle indented at $z = 1$, and we have the two paths that exist along the branch cuts which are at the negative real axis.
You should have residues at $z = i$ and $z=-i$, and the integrals around the small and large circles should be zero, but if anyone has any further thoughts on this integral or any other ways to go about it, I would love to see it.
Answer: I figured it out, this is a really cool problem that requires you to be very careful with the integration paths along the branch cuts.
Firstly, take the branch cut along the principle branch, this would be $(1,\infty]$.  Now we consider the contour integral of the following function
$\oint_C \frac{arccosh^2(z)}{z^2+1}dz$
The Paths of C are broken up in the following way
$\oint_C = \int_{C_{1}}+\int_{C_{2}}+\int_{C_{3}}+\int_{C_{4}}+\int_{C_{5}}+\int_{C_{6}}+\int_{C_{\Gamma}}+\int_{C_{\gamma}}$
The integral around $C_{\Gamma}$ is the usual large circle $z = Re^{i\theta}$.
The integral around $C_{\gamma}$ is the indented circle $z = 1+\epsilon e^{i\theta}$, where we indent around $z = 1$.
You can use the fact that $|zf(z)| \rightarrow 0$ as $z \rightarrow \infty$, and that $(z-1)f(z) \rightarrow 0$ as $z \rightarrow 1$, to estimate both of those integrals to be 0.
So all we need to do is consider each path very carefully, as the arccosh(z) is multi-valued across the branch cut.  I've taken $\epsilon \rightarrow 0$ as a consequence of the integral along the indented circle to be zero.  The reason I broke up $C_{2}$ and $C_{3}$ is because this integral transitions from the negative real axis to the positive real axis, so our choice of parametrization has to reflect this.  The same thing applies for $C_{4}$ and $C_{5}$.
$C_{1}: z = -x$  , $x \in (R,1]$
$C_{2}: z = -x$  , $x \in [1,0]$
$C_{3}: z = x$  , $x \in [0,1]$
$C_{4}: z = x$  , $x \in [1,0]$
$C_{5}: z = -x$  , $x \in [0,1]$
$C_{6}: z = -x$  , $x \in [1,R)$
Now Lets look at integrals $C_{2}$ through $C_{5}$.  This specifically concerns the branch cut $z \in [-1,1]$ and we must be careful of how we define the $arccosh(z)$ around each path. Generally speaking
$arccosh(z) = \pm ln(i\sqrt{1-z^{2}}+z)$, $z \in [-1,1]$
For $C_{2}$ and $C_{3}$ use the positive branch, for $C_{4}$ and $C_{5}$ use the negative branch.
$\int_{C_{2}}\frac{arccosh^2(z)}{z^2+1}dz+\int_{C_{3}}\frac{arccosh^2(z)}{z^2+1}dz+\int_{C_{4}}\frac{arccosh^2(z)}{z^2+1}dz+\int_{C_{5}}\frac{arccosh^2(z)}{z^2+1}dz$.
To be continued I need sleep!
Edit:  It was a long nap!!
$\int_{C_{2}}\frac{(ln(i\sqrt{1-z^{2}}+z))^2}{z^2+1}dz+\int_{C_{3}}\frac{(ln(i\sqrt{1-z^{2}}+z))^2}{z^2+1}dz+\int_{C_{4}}\frac{(-ln(i\sqrt{1-z^{2}}+z))^2}{z^2+1}dz+\int_{C_{5}}\frac{(-ln(i\sqrt{1-z^{2}}+z))^2}{z^2+1}dz$ =
$\int_1^0\frac{ln^2(i\sqrt{1-x^{2}}-x)}{x^2+1}(-dx)+\int_0^1\frac{ln^2(i\sqrt{1-x^{2}}+x)}{x^2+1}dx+\int_1^0\frac{ln^2(i\sqrt{1-x^{2}}+x)}{x^2+1}dx+\int_0^1\frac{ln^2(i\sqrt{1-z^{2}}-x)}{x^2+1}(-dx)$ =
$\int_0^1\frac{ln^2(i\sqrt{1-x^{2}}-x)}{x^2+1}dx+\int_0^1\frac{ln^2(i\sqrt{1-x^{2}}+x)}{x^2+1}dx-\int_0^1\frac{ln^2(i\sqrt{1-x^{2}}+x)}{x^2+1}dx-\int_0^1\frac{ln^2(i\sqrt{1-x^{2}}-x)}{x^2+1}dx$
But all of these terms cancel and the contribution of these integrals is zero.  So now we consider the integrals around $C_{1}$ and $C_{6}$.  The $arccosh(z)$ has the following values on these integrals.
$arccosh(z) = \pm i\pi+ln(\sqrt{z^{2}-1}-z)$, $z \in (-\infty,-1]$
For $C_{1}$ use the positive branch, for $C_{6}$ use the negative branch.
$\int_{C_{1}}\frac{arccosh^2(z)}{z^2+1}dz+\int_{C_{6}}\frac{arccosh^2(z)}{z^2+1}dz$ =
$\int_{C_{1}}\frac{(i\pi+ln(\sqrt{z^{2}-1}-z))^2}{z^2+1}dz+\int_{C_{6}}\frac{(-i\pi+ln(\sqrt{z^{2}-1}-z))^2}{z^2+1}dz$ =
$\int_R^1\frac{(i\pi+ln(\sqrt{x^{2}-1}+x))^2}{x^2+1}(-dx)+\int_1^R\frac{(-i\pi+ln(\sqrt{x^{2}-1}+x))^2}{x^2+1}(-dx)$ =
$\int_1^R\frac{-\pi^{2}+2\pi iln(\sqrt{x^{2}-1}+x)+ln^2(\sqrt{x^{2}-1}+x)}{x^2+1}dx+\int_1^R\frac{\pi^{2}+2\pi iln(\sqrt{x^{2}-1}+x)-ln^2(\sqrt{x^{2}-1}+x)}{x^2+1}dx$ =
$\int_1^R\frac{-\pi^{2}+2\pi iln(\sqrt{x^{2}-1}+x)+ln^2(\sqrt{x^{2}-1}+x)+\pi^{2}+2\pi iln(\sqrt{x^{2}-1}+x)-ln^2(\sqrt{x^{2}-1}+x)}{x^2+1}dx$
Canceling the appropriate terms, and letting $R \rightarrow \infty$
$4 \pi i \int_1^\infty \frac{ln(\sqrt{x^2-1}+x)}{x^2+1}dx$ = $4 \pi i \int_1^\infty \frac{arccosh(x)}{x^2+1}dx$ = $4 \pi i I$
Where I is the integral we are looking for.  Now by construction this is equal to
$\oint_C \frac{arccosh^2(z)}{z^2+1}dz$
And this is equal to the residues that are collected at $z = \pm i$, multiplied by a factor of $2 \pi i$.  A quick computation shows,
$\oint_C \frac{arccosh^2(z)}{z^2+1}dz = 4 \pi i I = 2 \pi i ln(\sqrt{2}+1) $
In conclusion,
$I = \frac{1}{2} 1n(\sqrt{2}+1)$
$\int_1^\infty \frac{arccosh(x)}{x^2+1}dx = \frac{1}{2} 1n(\sqrt{2}+1) = \frac{1}{2} arcsinh(1)$


Tracking a subdomain separately in Google Analytics

Question: So I've been trying to set up Google Analytics to track site's (Tumblr) blog separately from the rest of the site, but I've been having no luck. All of the tutorials online seem to be outdated, and Google's own help center isn't helping.
Can someone please help. I tried messing with filters, but simply can't get it to work.
The website is sitename.com and the blog is blog.sitename.com. They both share a tracking code.
Thanks!
Answer: Create an a custom include filter on the hostname:
on one profile, include only ^www.domain.com$
on another profile, include only ^blog.domain.com$
Beware that e-Commerce transactions can't be filtered by hostname but only by transaction ID
I encourage you to keep a 3rd profile without filters, to be able to check that you don't miss anything.
Answer: Create two Analytics profiles, one for each site.  Then put their respective tracking codes on each site.


JavaScript RegExp to match all subpaths from location

Question: Given the following
const location = '/level_1/level_2/level_3/';

I would like to find a RegExp to pass to
location.match(regexp);

so that I can get all subpaths within the full path
"/level_1/"

"/level_1/level_2/"

"/level_1/level_2/level_3/"

Ideally, the RegExp would work no matter the number of levels.
I have already tried
location.match(/^\/.*?\//);

but it only returns the first occurence
"/level_1/"

Any help is highly appreciated !
Comment: You have to use the `g` flag to return multiple matches. But it won't return overlapping matches, so you can't do what you want with a single regexp.
Comment: Why don't you just use `location.split('/')` and then make all the concatenations you want?
Comment: @Barmar Yeah, of course some JavaScript would work to achieve that, but I wanted to let the power of RegExp do the job ! Thank you for your time.
Answer: Use a loop that tries finding matches of every length until it fails.

const loc = '/level_1/level_2/level_3/';
const result = [];
for (let i = 1; ; i++) {
  const regex = new RegExp(`^(?:/.*?){${i}}/`);
  const match = loc.match(regex);
  if (match) {
    result.push(match[0]);
  } else {
    break;
  }
}
console.log(result);
Answer: This is a bit different than the request, as I'm not sure about arbitrary matching groups in regexp. But the String.prototype.split takes a regexp or a string to split on. So could you do something like:
const loc = "/level_1/level_2/level_3/"
const strippedString = loc.match(/^\/(.+)\/$/)
let result = []
if (strippedString.length === 2) {
  strippedString[1].split("/").forEach(path => {
    result.push(`/${path}/`)
  })
}


Calculating the sum of even terms in a fibanocci series which is less than 4 million

Question: I get the correct answer here:
Sum - 4613732
Time- 0.0
import time

def factorial():
        i=1
        j=2
        fac=[]
        final_list=[]
        fac.append(i)
        fac.append(j)
        z=i+j
        while(z<4000000):
                z=i+j
                fac.append(z)
                i=j
                j=z
        for n in fac:
                if(n%2==0):
                        final_list.append(n)
        return sum(final_list)

if __name__ == "__main__":
        start = time.clock()
        print "Sum is"+ " " + str(factorial())
        print "Time taken"
        print time.clock() - start

Just want to get some insight oh how I coded the logic in python. Is it fine or can it be done better(w.r.t coding standards etc)?
Comment: There is a separate website called, [codereview.stackexchange.com](http://codereview.stackexchange.com/)
Comment: In my opinion almost every program can always be written in much more better way! Always!
Answer: There's a really neat trick for this.
Here's the fibonacci numbers:
F_1 : 1
F_2 : 1
F_3 : 2
F_4 : 3
F_5 : 5
F_6 : 8
F_7 : 13
F_8 : 21
F_9 : 34

The sequence is (odd, odd, even) repeat.
The even number is the sum of the two odd ones by definition
So the (sum of odd and even) = (sum off the odd) + (sum of the even) = 2 * (sum of the odd).
So long as we're summing up to a value which an even value.

i.e.
1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 =
1 + 1 + (1+1) + 3 + 5 + (3+5) + 13 +21 + (13 + 21) =
2 * (1 + 1 + 3 + 5 + 13 + 21 )

Now the sum of the first N Fibonacci numbers is the N+2 th fibonaci number - 1
Continuing our sequence slightly we get 34, 55, 89, ...
So
1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 = 89 - 1

and so
1 + 1 + 3 + 5 + 13 + 21 = (89 - 1)/2 = 44.

This leads us to the following algorithm:

Find N and F_N such that F_N <= M but F_{N+1} > M . To do this we use a formula from wikipedia
if F_N is even our result is just (F_{N+2}-1)/2, note that F_{N+2} can be calculated in O(log(N)) time.
if F_N is odd we step back until we find an even one, (either one or two steps back).

if it was one step then our result is (F_{N+1}-1)/2 + F_N,
if it was two our result is (F_N-1)/2 + F_{N-1} + F_N

All these steps are doable in log(N) time.


node.js back-pressure and drain event. I encountered memory leak warning

Question: I am currently studying node.js back-pressure myself.
I intend not to use .pipe() or .pipeline()
because I want to understand back-pressure and drain event.
but I don't know how to write appropriate drain handler.
let's see the below code.
"use strict";

const rs = getReadableStreamSomehow();
const ws = getWritableStreamSomehow();

rs.on("data", function handler(data) {
  if (!ws.write(data)) {
    ws.once("drain", handler);
  }
});

it seems that the above source code has some problem. because I encountered memory leak warning from console.
(node:29788) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 drain listeners added to [WriteStream]. Use emitter.setMaxListeners() to increase limit

Is there anyone knows how to write drain event handler?
Thank you.
Answer: I think the following is the right way to handle backpressure and drain event.
const rs = getReadableStreamSomehow();
const ws = getWritableStreamSomehow();

rs.on("data", function (data) {
  if (!ws.write(data)) {
    rs.pause();
    ws.once("drain", function () {
      rs.resume();
    });
  }
});

is it correct?
if it is not correct, please leave a comment.


Listar todos os dados de uma pesquisa

Question: Como listar todos os dados dessa consulta, eu só consigo mostrar a primeira linha mas quero consultar todas e mostrar elas.
public function gerarCardapio(){
        try{
            $cat = "M";
            $sql = "SELECT * FROM alimentos WHERE id_usuario = :idUser AND categoria = :cat AND quantidade >0 ";
            $stmt = DB::prepare($sql);
            $stmt->bindParam('idUser', $_SESSION['user_id']);
            $stmt->bindParam('cat', $cat);
            $stmt->execute();//Executa o comano SQL
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            echo $stmt->rowCount();
        }catch (PDOException $e){
            echo $e->getMessage();
        }
    }

Comment: No código, não vejo aonde você esta retornando ou imprimindo o resultado na tela, a não ser o número de linhas que foi retornado `echo $stmt->rowCount();`
Comment: A documentação é sua amiga, veja o exemplo #2: http://php.net/manual/en/pdostatement.fetch.php#example-1058
Answer: Percebi que você está retornando o número de linhas do campo alimentos da tabela usando echo $stmt->rowCount();
Use $result->fetchAll(PDO::FETCH_ASSOC),
E também use : no tratamento do bindParam(:..., $....);
public function gerarCardapio(){
  try{
    $cat = "M";
    $sql = "SELECT * FROM alimentos WHERE id_usuario = :idUser AND categoria = :cat AND quantidade > 0 ";
    $stmt = DB::prepare($sql);
    $stmt->bindParam(':idUser', $_SESSION['user_id']);
    $stmt->bindParam(':cat', $cat);
    $stmt->execute();//Executa o comano SQL
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
    var_dump($result);
  }catch (PDOException $e){
    echo $e->getMessage();
  }
}

Answer: Como comentado pelo @Knautiluz, você deve utilizar o while.
# Apenas um exemplo de uso, pois não sei os nomes das colunas.
while($linha = $stmt->fetch(PDO::FETCH_ASSOC)){
    printf("id_usuario: %s categoria: %s", $linha['id_usuario'], $linha['categoria']);
}

ficando assim seu método:
public function gerarCardapio(){
    try{
        $cat = "M";
        $sql = "SELECT * FROM alimentos WHERE id_usuario = :idUser AND categoria = :cat AND quantidade >0 ";
        $stmt = DB::prepare($sql);
        $stmt->bindParam(':idUser', $_SESSION['user_id']);
        $stmt->bindParam(':cat', $cat);
        $stmt->execute();//Executa o comano SQL
        # Apenas um exemplo de uso, pois não sei os nomes das colunas.
        while($linha = $stmt->fetch(PDO::FETCH_ASSOC)){
            printf("id_usuario: %s categoria: %s", $linha['id_usuario'], $linha['categoria']);
        }
    }catch (PDOException $e){
        echo $e->getMessage();
    }
}

Você pode ver um exemplo básico em tutorialspoint

Recomendo que leia na documentação como fazer a utilização da função bindParam.
Referências

sprintf
while

Listar todos os dados de uma pesquisa


Intermediate value property implies continuity

Question: Let $g\colon \mathbb{R} \to \mathbb{R}$ be a function with the intermediate value property.
Let $x \in \mathbb{R}$. Suppose to each sequence $ (x_n) $ converging to $x$ there exists a constant $K$ such that
$$|g(x) - g(x_n)| ≤K \sup _{m}|g(x_n) - g(x_m)|$$
Then show that $g$ is continuous at $x$.
What i have done so far is :
Given $(x_n)\rightarrow x$ and $\epsilon>0$ there exists $N\in \mathbb{N}$ such that $x_n\in (x-\epsilon,x+\epsilon)$ for all $n\geq N$..
As $g$ has this intermediate value property, $g$ maps intervals to intervals..
So, $g(x-\epsilon,x+\epsilon)=M$ an interval in $\mathbb{R}$.. I want to write $M$ as $(g(x-\epsilon),g(x+\epsilon))$
See that $g(x_n)\in M$ for all $n\geq N$ we can assume length of $M$ to be $r>0$
Then, $\sup _{n,m}|g(x_n) - g(x_m)|\leq \max\{r,|g(x_n)-g(x_i)|:1\leq i\leq n\}=L$
So, $|g(x)-g(x_n)|\leq L$.. I some how missed that epsilon...
Help me to clear this,,
Comment: Your question's title is a little misleading: the derivative function of any differentiable function always fulfills the I.V. property (Darboux Theorem) yet it can be non-continuous.
Comment: The subscripts on $\sup$ really confuses me, if $n$ is supposed to be fixed then it shouldn't be in the subscript
Comment: @user160738. Ditto for me.
Comment: @user254665 : i have changed it...
Comment: @user160738 : I have chnaged it...
Comment: Why don't you try contradiction?
Comment: @user64066 : I do not know where to start
Answer: Hint: Suppose for a contradiction, the claim is false. This implies for some $\varepsilon_0$ we can find $x_n\in(x-1/n,x+1/n)=I_n$ but $\mid g(x_n)-g(x)\mid\geq \varepsilon_0$. From here, by using intermediate value, you can find another sequence $t_n\in I_n$ such that $g(t_n)=f(x)+\varepsilon_0$ or $g(t_n)=f(x)-\varepsilon_0$. This implies however $g$ takes one of this values infinitely many often, which contradicts with given condition i.e., $t_n\to x$ so there exists $K$ that satisfies given inequality.
Comment: I  just solved it but you beat me by an hour.+1.


Como alinhar uma imagem para a direita com em CSS e HTML?

Question:

@charset="UTF-8";
@import url('https://fonts.googleapis.com/css?family=Krub');
@import url('https://fonts.googleapis.com/css?family=Varela+Round');
/* CSS Document */

header {
 width:1900px;
 height:100px;
 margin:auto;
 background-color:black;
 font-family: 'Krub', sans-serif;
 color:white;
}
body{
    background-color: #363636;
}

nav {
 width:1900px;
 height:50px;
 margin:auto;
 background-color:#ff4425;
 font-family: 'Krub', sans-serif;
 position:absolute;
 display:table;
 top:100px;
 right:0px;
    border:none;
}

.button{
 float:left;
 color:black;
 border:none;
 background-color:#ff4425;
 transition-duration:1s;
 height:50px;
 width:100px;
 font-family: 'Krub', sans-serif;
 align-content: center;
    margin-left: auto;
    margin-right: auto;
}

.computadores{
 float:left;
 color:black;
 border:none;
 background-color:#ff4425;
 transition-duration:1s;
 height:50px;
 width:150px;
 font-family: 'Krub', sans-serif;

}

.computadores:hover{
 background-color:white;
 color:black;
 border: 0.5px solid #2f3542;
 font-family: 'Krub', sans-serif;
 cursor:pointer;
}

.button:hover{
 background-color:white;
 color:black;
 border: 0.5px solid #2f3542;
 font-family: 'Krub', sans-serif;
 cursor:pointer;
 -webkit-transition:1s; /*Chrome e Safari */
}

#crono {
    color:#F26B38 ;
    background-color:#2A2A2A;
    font-family: 'Varela Round', sans-serif;
    font-size: 30px;
    border:none;

}

}

#destaque {
    font-family: 'Varela Round', sans-serif;
    background-color:white;
    color:black;
    display:table;
}

section{
 height:1000px;
 width:600px;
 color:white;
}
atricle.crono{
 height:500px;
 width:300px;

 font-family: 'Krub', sans-serif;
}

.saiba{
    background-color:white;
    color:black;
    border:none;
    width:200px;
    height:100px;
    font-size: 28px;
    font-family: 'Krub', sans-serif;
    transition:0.5s;
    border:5px solid black;

}

.saiba:hover{
    color:white;
    background-color:black;
    border:none;
    width:200px;
    height:100px;
}

#bulldog{
    color:#e84118;
    background-color:#2A2A2A;
    font-family: 'Varela Round', sans-serif;
    border:none;
    margin-left:800px;

}
<!Doctype HTML>

<meta charset= "UTF-8"/>
<title>Alfa Hardware</title>

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

ALFA HARDWARE

<button class="button">INÍCIO</button>
<button class="computadores">COMPUTADORES</button>
<button class="button">NOTEBOOKS</button>
<button class="button">CELULARES</button>
<button class="button">PERIFÉRICOS</button>
<button class="button">SOFTWARES</button>

        NZXT CRONOS

    A NOVA GERAÇÃO DE COMPUTADORES

        <button class="saiba">SAIBA MAIS </button>

Olá, estou com uma dúvida no CSS, onde tento alinhar uma imagem para a direita, já tentei o comando "float:left;", e já usei até mesmo o comando "margin-left", onde consegui mover a imagem para o lado, mas não ficou alinhado. Como eu consigo alinhar a imagem ? Quem puder me ajudar, ficaria muito grato.
OBS: Sou iniciante em HTML.
Comment: Lucas sem o código não da para te dar uma resposta precisa, por favor edite a sua pergunta e inclua seu HTML e CSS
Comment: Desculpa, eu tinha me esquecido de inserir o código.
Answer: Lucas seu código está bem estranho... na verdade está com propriedades CSS aplicadas de forma equivocada, por exemplo sua section está com 600px, de largura, sendo que cada imagem sua tem 700px de largura... assim não tem como ficar uma do lado da outra... Alé disso a palavra article estava escrito errado e o css não estava sendo aplicado no elemento.
Cara vou ser bem sincero com vc, estou vendo que vc está começando. Acho que o basicão vc já sabe, mas pare um pouco para estudar os fundamentos. Estudo FlexBox, Position e Display do CSS que vai te ajudar para o resto da vida. E não tenha medo de começar novamente esse projeto do 0, mas de forma mais organizada no CSS.
Olha ai o seu código, execute em tela toda que vc vai ver que agora fica uma do lado da outra, simplesmente pq agora cabem as duas na mesma linha... Mas se eu fosse vc deletaria tudo e parava pra estudar um pouco mais antes de seguir, pq esse layout nunca vai ficar bom e vai te dar problema no futuro...

@charset="UTF-8";
@import url('https://fonts.googleapis.com/css?family=Krub');
@import url('https://fonts.googleapis.com/css?family=Varela+Round');
/* CSS Document */

header {
 width:1900px;
 height:100px;
 margin:auto;
 background-color:black;
 font-family: 'Krub', sans-serif;
 color:white;
}
body{
    background-color: #363636;
}

nav {
 width:1900px;
 height:50px;
 margin:auto;
 background-color:#ff4425;
 font-family: 'Krub', sans-serif;
 position:absolute;
 display:table;
 top:100px;
 right:0px;
    border:none;
}

.button{
 float:left;
 color:black;
 border:none;
 background-color:#ff4425;
 transition-duration:1s;
 height:50px;
 width:100px;
 font-family: 'Krub', sans-serif;
 align-content: center;
    margin-left: auto;
    margin-right: auto;
}

.computadores{
 float:left;
 color:black;
 border:none;
 background-color:#ff4425;
 transition-duration:1s;
 height:50px;
 width:150px;
 font-family: 'Krub', sans-serif;

}

.computadores:hover{
 background-color:white;
 color:black;
 border: 0.5px solid #2f3542;
 font-family: 'Krub', sans-serif;
 cursor:pointer;
}

.button:hover{
 background-color:white;
 color:black;
 border: 0.5px solid #2f3542;
 font-family: 'Krub', sans-serif;
 cursor:pointer;
 -webkit-transition:1s; /*Chrome e Safari */
}

#crono {
    color:#F26B38 ;
    background-color:#2A2A2A;
    font-family: 'Varela Round', sans-serif;
    font-size: 30px;
    border:none;

}

}

#destaque {
    font-family: 'Varela Round', sans-serif;
    background-color:white;
    color:black;
    display:table;
}

section{
 height:1000px;

 color:white;
}
article.crono{
 height:500px;
 width:300px;

 font-family: 'Krub', sans-serif;
}

.saiba{
    background-color:white;
    color:black;
    border:none;
    width:200px;
    height:100px;
    font-size: 28px;
    font-family: 'Krub', sans-serif;
    transition:0.5s;
    border:5px solid black;

}

.saiba:hover{
    color:white;
    background-color:black;
    border:none;
    width:200px;
    height:100px;
}

#bulldog{
    color:#e84118;
    background-color:#2A2A2A;
    font-family: 'Varela Round', sans-serif;
    border:none;
    /* margin-left:800px; */

}

ALFA HARDWARE

<button class="button">INÍCIO</button>
<button class="computadores">COMPUTADORES</button>
<button class="button">NOTEBOOKS</button>
<button class="button">CELULARES</button>
<button class="button">PERIFÉRICOS</button>
<button class="button">SOFTWARES</button>

        NZXT CRONOS

    A NOVA GERAÇÃO DE COMPUTADORES

        <button class="saiba">SAIBA MAIS </button>

Comment: Só isso aqui já vale o +1 _Cara vou ser bem sincero com vc, estou vendo que vc está começando. Acho que o basicão vc já sabe, mas pare um pouco para estudar os fundamentos. Estudo FlexBox, Position e Display do CSS que vai te ajudar para o resto da vida. E não tenha medo de começar novamente esse projeto do 0, mas de forma mais organizada no CSS_ - Na hora, pode doer um pouco o ego ler isso, mas é um conselho que se for seguido, vai abrir o caminho para o autor realmente se desenvolver como bom profissional.
Comment: @Bacco é uma situação complicada pq a gente nunca sabe como as pessoas vão reagir aos "conselhos" que damos. Mas me arrisquei... e sei que o Lucas entendeu a mensagem, isso me deixa feliz e vejo que sempre vale a pena dar esse feedback, mesmo que alguns não levem na boa no início, talvez em algum momento da vida podem refletir e reconsiderar... []´s
Comment: Indiquei ele a usar bootstrap, fazer um site assim do zero na mão é bem complicado, dá muita dor de cabeça ahah
Comment: Muito obrigado pelo conselho, estou recomeçando o site novamente, é a primeira vez que estou fazendo um site. Faço Técnico em Informática, e o HTML e CSS foram as áreas que eu mais gostei de usar. Muito obrigado por responderem a minha dúvida
Comment: @LucasMarcato legal que vc levou o recado a sério. Encara como uma crítica construtiva ;). "Desenhar" com código realmente é bem legal, e se vc já gostou do HTML e CSS vc vai pegar o jeito rápido, pois eles representam 90% da estrutura do que se vê na tela. Recomece, mas tb para um pouco para estudar, existe muito material disponível por ai, inclusive aulas no Youtube que podem te ajudar. Boa sorte nos estudos!
Comment: Um dos principais problemas no desenvolvimento do site é que eu, que sou iniciante, já acho que vou conseguir fazer um site nivel Corsair, Acer, etc. Tentei me inspirar um pouco nesses sites, mas apliquei de uma forma errada. Obrigado pelos conselhos, fico grato pelas dicas e por tirarem um tempo para me ajudarem.
Answer: Pelo que entendi é isso que você precisa.
Olha o Código a baixo.

CODE
Comment: Ok, primeiro eu indico você a estudar bootstrap, que é um framework muito utilizado no desenvolvimento web, com ele você não vai passar esse tipo de problema, não precisa ficar reinventando a roda. Segundo, eu indico a você estudar tambem CSS FlexBox  aqui https://www.w3schools.com/css/css3_flexbox.asp isso irá te ajudar muito também. Estou meio sem tempo no momento pra arrumar seu código, se precisar de algo é só avisar
Comment: Eu já tentei inserir esse código, mas deu falha.
Comment: Cara, muito obrigado com a recomendação do FlexBox, consegui fazer direitinho aqui. Só o Bootstrap que fiquei meio sem entender, mas o FlexBox funcionou direitinho.
Comment: Bah, que bom. Seguinte, assim que tiver um tempo da uma estudada no bootstrap, no mesmo site que te passei ou em video aulas na internet, tem bastante e vai te ajudar muito.


LinearLayoutManager newly populated items stack from bottom

Question: When a new item is added, it's populated from the bottom of the UI, so I tried some methods from LinearLayoutManager setReverseLayout() == true but items stack from bottom. I tried different combinations of reverseLayout and stackFromEnd, but still no luck, the new item is still populated from the bottom of the UI, second item is populated below the first item, and all the way stack to the top.
What I want is that the first item will be populated on the top of the UI, not bottom, and then the second will be below the first item etc..
        val recyclerView = findViewById<RecyclerView>(R.id.recyclerview)
        val adapter = SomeListAdapter(Some params)

        val llManager = LinearLayoutManager(this)
        llManager.reverseLayout = true
        llManager.stackFromEnd = true

        recyclerView.adapter = adapter
        recyclerView.layoutManager =llManager

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/layout"
    tools:context=".AddressActivity">

    <RelativeLayout
        android:id="@+id/rl_address"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="60dp"
        android:background="@color/black"
        android:backgroundTint="#FEFBDE"
        android:orientation="vertical"
        android:padding="5dp">
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            tools:listitem="@layout/address_item"
            android:layout_above="@+id/ll_addAddress"
            />

        <RelativeLayout
            android:id="@+id/ll_addAddress"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_marginTop="1dp">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <Button
                    android:id="@+id/addNewAddress"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"

                    android:text="Add New Address">

                </Button>
                <Button
                    android:id="@+id/viewAllAddress"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="View all addresses">

                </Button>

                <Button
                    android:id="@+id/welcome_landlord"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="Welcome Landlord" />

            </LinearLayout>
        </RelativeLayout>
    </RelativeLayout>

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/navigation_menu"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_alignParentBottom="true"
        app:labelVisibilityMode="labeled"
        app:menu="@menu/bottom_navigation_menu">

    </com.google.android.material.bottomnavigation.BottomNavigationView>

</RelativeLayout>

Answer: Unless I'm missing something you just want the standard behaviour? Just don't set reverseLayout or stackFromEnd as true, the whole point of those is to reverse the order of items and start filling from the bottom/end.
If your RecyclerView still isn't behaving how you want, it's probably because of how you've set up your layout. You're using a RelativeLayout where ll_addAddress is pinned to the bottom, and then your RecyclerView is positioned above that with android:layout_above="@+id/ll_addAddress". The result is that your RV is pinned to the bottom of the available space.
So because your RecyclerView's height is wrap_content, the top of the RV (which isn't pinned) grows upward as you add items. This means that when you add your first item, it's at the top of the RV by default, but the top of the RV is near the bottom of the space, just high enough to accommodate the item you added. So unless you can see the actual bounds of the RV, it looks like you're adding items at the bottom of it, when you're not. (You can use the Layout Inspector to see this happening on a running app, or add a background to the RecyclerView so you can see what's happening to it.)

The solution is that you really need to pin the top of the RecyclerView to something, so it takes up a fixed space in your layout. It sounds like you already have an expectation of where "the top" is supposed to be, but in your layout it actually depends on the height, which depends on the contents.
This is also gonna cause you problems when you add enough items that the RV needs to actually scroll - it won't, because you're not constraining its height, so it will just continue to grow offscreen. Scrolling views only start to scroll when their height is less than the height of their contents, which requires you to limit that height somehow - setting their height to wrap_content is a red flag.
It's been a long time since I used a RelativeLayout, so you might be able to just align the top with the parent too, but I'd really recommend you use ConstraintLayout instead - it's the modern way to develop flexible layouts, and it allows you to easily do things like constrain the top and bottom to certain views, allowing you to fill the available space. Either way, you have to constrain the height of that RecyclerView somehow


How use setTimeout for *ngIf in angular 10 for the ionic spinner

Question: I'll have an ionic loading indicator that I'll want to show after 2 seconds of loading if the application still loading data from a server else don't show it. This is the html of the spinner.

      <ion-spinner name="dots" color="light"></ion-spinner>

In the page component I'll set isLoading to true each time new posts are loaded. In the setPostData I'll set it back to false. But combining this with the timer doesn't work.
posts: any = [];
timer: any = 0;
isLoading: boolean;

constructor(){...}

getPostData(){
    this.timer = setTimeout(() => {}, 2000);
    this.isLoading = true;

    this.postService.getPosts().subscribe(
        (result) => {
            this.setPostData(result);
        }
    );

}

setPostData(data){
    this.posts = data.posts;
    this.isLoading = false;
}

Answer: I'll found another way to do it. Create a timer(setTimeout) and bind the toggleLoading function. In the setPostData function clear the created timer. So after 2500 miliseconds the loading starts. If 2500 miliseconds is not reached the timer is cleared and the loading dots are not displayed as wished.
posts: any = [];
timer
isLoading: boolean;

constructor(){...}

toggleLoading(){
    this.isLoading = !this.isLoading;
}

getPostData(){
    this.timer = setTimeout(this.toggleLoading.bind(this), 2500);

    this.postService.getPosts().subscribe(
        (result) => {
            this.setPostData(result);
        }
    );

}

setPostData(data){
    this.posts = data.posts;
    if(this.timer) {
        clearTimeout(this.timer);
    }
    this.isLoading = false;
}


mod_ssl: SSL handshake interrupted by system [Hint: Stop button pressed in browser?!] (System error follows)

Question: in my error_log I'm getting following msg

[error] mod_ssl: SSL handshake interrupted by system [Hint: Stop button pressed in browser?!] (System error follows)

IE wouldn't even load page, yet firefox works fine
Comment: What are the versions you are testing on? IE6 had notorious problems with SSL.
Comment: My machine is Windows XP SP3 and IE7
Comment: Did you get any pop ups with authentication problems?
Comment: nope, nothing of that nature
Answer: something was up w/ certificates, after replacing them it start working fine so it was some misconfiguration on my end


MongoDB Mergelist error in Debian 6.0.9

Question: We installed Ubiquiti UniFi 2.4.6 which installs Mongodb 10gen on Debian Squeeze 6.0.9.  This was a clean install, with no other packages installed from the base install (other than SSH).  I was able to successfully install both UniFi and Mongodb, but received the following when running an apt-get update:
Pertinent error:
****Reading package lists... Error!**
****E: Encountered a section with no Package: header**
E: Problem with MergeList /var/lib/apt/lists/downloads-distro.mongdb.org_repo_ubuntu-upstart_dists_dist_10gen_binary-i386_Packages
**E: The package lists or status file could not be parsed or opened.******
I've ran a sudo rm /var/lib/apt/lists/* -vf followed by an apt-get clean && apt-get update with the same error appearing. (I did back up the lists directory.  Any ideas?)
As an aside, I should mention, that I tried to remove unifi and it probably goes without saying it won't uninstall.
Here's a head of downloads-distro.mongdb.org_repo_ubuntu-upstart_dists_dist_10gen_binary-i386_Packages  (removed the links)

mongdb.org
script src="://www.google.(com)/adsense/domains/caf.js" type="text/javascript" >
="://d1vbm0eveofcle.cloudfront.(net)/themes/assets/style.css" rel="stylesheet" type="text/css" media="screen" />
="*://d1vbm0eveofcle.cloudfront.(net)/themes/cleanPeppermintBlack/style5.css" rel="stylesheet" type="text/css" media="screen" />
link='*://fonts.googleapis.(com)/css?family=Libre+Baskerville:400,700' rel='stylesheet' type='text/css'>

root@:/var/l
Full apt-get update:
Get:1 *://security.debian.(org)squeeze/updates Release.gpg [836 B]
Ign *://security.debian.(org)/ squeeze/updates/main Translation-en
Ign *://security.debian.(org)/ squeeze/updates/main Translation-en_US
Hit *://ftp.us.debian.(org)squeeze Release.gpg
Ign *://ftp.us.debian.(org)/debian/ squeeze/main Translation-en
Ign *://ftp.us.debian.(org)/debian/ squeeze/main Translation-en_US
Get:2 *://ftp.us.debian.(org)squeeze-updates Release.gpg [836 B]
Get:3 *://security.debian.(org)squeeze/updates Release [86.9 kB]
Ign *://ftp.us.debian.org/debian/ squeeze-updates/main Translation-en
Ign *://ftp.us.debian.org/debian/ squeeze-updates/main Translation-en_US
Hit *://ftp.us.debian.(org)squeeze Release
Get:4 *://ftp.us.debian.(org)squeeze-updates Release [113 kB]
Hit *://www.ubnt.(com)squeeze Release.gpg
Ign *://www.ubnt.(com)/downloads/unifi/distros/deb/squeeze/ squeeze/ubiquiti Translation-en
Get:5 *://security.debian.(org)squeeze/updates/main Sources [172 kB]
Get:6 *://downloads-distro.mongdb.(org)dist Release.gpg
Ign *://www.ubnt.(com)/downloads/unifi/distros/deb/squeeze/ squeeze/ubiquiti Translation-en_US
Get:7 *://downloads-distro.mongdb.(org)/repo/ubuntu-upstart/ dist/10gen Translation-en
Get:8 *://downloads-distro.mongdb.(org)/repo/ubuntu-upstart/ dist/10gen Translation-en_US
Hit *://ftp.us.debian.(org)squeeze/main Sources
Hit *://ftp.us.debian.(org)squeeze/main i386 Packages
Get:9 *://security.debian.(org)squeeze/updates/main i386 Packages [457 kB]
Get:10 *://ftp.us.debian.(org)squeeze-updates/main Sources/DiffIndex [3,955 B]
Get:11 *://ftp.us.debian.(org)squeeze-updates/main i386 Packages/DiffIndex [3,955 B]
Get:12 *://ftp.us.debian.(org)squeeze-updates/main i386 Packages [5,228 B]
Get:13 *://downloads-distro.mongdb.(org)dist Release
Ign *://downloads-distro.mongdb.org dist Release
Hit *://www.ubnt.(com)squeeze Release
Get:14 *://downloads-distro.mongdb.(org)dist/10gen i386 Packages/DiffIndex
Get:15 *://downloads-distro.mongdb.(org)dist/10gen i386 Packages
Hit *://www.ubnt.(com)squeeze/ubiquiti i386 Packages
Fetched 882 kB in 1s (596 kB/s)
Reading package lists... Error!
E: Encountered a section with no Package: header
E: Problem with MergeList /var/lib/apt/lists/downloads-distro.mongdb.org_repo_ubuntu-upstart_dists_dist_10gen_binary-i386_Packages
E: The package lists or status file could not be parsed or opened.
Answer: You tried to install MongoDB with the Ubuntu installation method, rather than the Debian installation method. Try again and this time use the correct installation method.
Comment: Got it, but I can't even remove the MongoDB gen10 to begin with.  Ideas on how to do that?

MongoDB Mergelist error in Debian 6.0.9


Find the slope of the tangent to the curve for $y=3+4x^2-2x^3$

Question: I am completing a question which asks me to find the slope of the tangent to the curve for $y=3+4x^2-2x^3$ at the point $x=a$. In Klein's book on calculus, he shows that you can find the rate of change for a term with an exponent by multiplying the variable by the exponent e.g. $x^2\to 2x$. I tried this with the equation and my answer was $y'=8a-6a$. However, the solution says that the answer should be $8a-6a^2$. Is the solution wrong?
Answer: Remember that if $y=x^n$ $$\dfrac {dy}{dx}=nx^{n-1}$$
If $y=3+4x^2-2x^3$, then $$\dfrac {dy}{dx}=4\times2\times x-2\times 3\times x^2$$
$$\implies \dfrac {dy}{dx}=8x-6x^2$$
Plugging in $a$, you get $8a-6a^2$.
NOTE: $\dfrac {dy}{dx}$ is the rate of change of the function $y$ with respect to $x$.
Comment: Thanks I stupidly forgot that $$\dfrac {dy}{dx}=nx^{n-1}$$ makes perfect sense now.
Comment: @Anobody, glad I could be of some help.
Answer: Rate of change of $2x^3=2.3x^2=6x^2.$
Answer: Apologies if this contribution is unnecessary, but here is a common quick proof of the derivative short cut (the power rule) that you are making use of. Although I am sure the book you are using contains one as well, I emphasize understanding the proofs of these shortcut techniques because when I was a student that is what helped me grasp calculus myself.
$$y = x^{c}$$
$$ \implies ln(y) = c\cdot ln(x) $$
$$ \implies \frac{1}{y}\cdot\frac{dy}{dx} = \frac{c}{x} $$
$$ \implies \frac{dy}{dx} = \frac{c}{x} \cdot y $$
$$ \implies \frac{dy}{dx} = \frac{c}{x} x^{c} $$
$$ \implies \frac{dy}{dx} = cx^{c-1} $$
Note that this proof uses implicit differentiation technique so it assumes you have already proven the chain rule / log rule, it can be down without assuming calculus however. Hopefully this was of some assistance.
Comment: Thanks, I haven't yet covered the chain rule/log rule. The proof in my textbook uses the binomial theorem to prove the rule. This was useful and I will return to it once I cover the chain rule.
Comment: Yes the binomial theorem is another excellent way to prove product rule without using calculus! This specific technique I posted might also come in handy in other places down the road... such as deriving strange functions such as $f(x) = x^{x}$. Cheers!


Java SLF4J warning when starting hive on WINDOWS 10

Question: I am trying to start HIVE 3.1.2 on Hadoop 3.3.0 on my windows 10 PC for training purpose (yes I know linux is better ;-) but someone has to do it anyway). I have the following error message
it looks related to how SLF4J works (I guess) but since I am not a java (or any other language) dev I have no clue how to fix it
For what it worth I do not have an IT background so be gentle and talk to me as if I was 10y/o
Could any one help (BTW it is running on java 8)
$ hive
<code>SLF4J: Class path contains multiple SLF4J bindings.

SLF4J: Found binding in [jar:file:/C:/zztop/hadoop/hive/lib/log4j-slf4j-impl-2.14.0.jar!/org/slf4j/impl/StaticLoggerBinder.class]

SLF4J: Found binding in [jar:file:/C:/zztop/hadoop/hive/lib/slf4j-log4j12-1.7.25.jar!/org/slf4j/impl/StaticLoggerBinder.class]

SLF4J: Found binding in [jar:file:/C:/zztop/hadoop/share/hadoop/common/lib/slf4j-log4j12-1.7.25.jar!/org/slf4j/impl/StaticLoggerBinder.class]

SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.

SLF4J: Actual binding is of type [org.apache.logging.slf4j.Log4jLoggerFactory]

WARNING: sun.reflect.Reflection.getCallerClass is not supported. This will impact performance.
Exception in thread "main" java.lang.NoClassDefFoundError: Could not initialize class org.apache.logging.log4j.util.PropertiesUtil

at org.apache.logging.log4j.status.StatusLogger.<clinit>(StatusLogger.java:71)

at org.apache.logging.log4j.LogManager.<clinit>(LogManager.java:60)

at org.apache.logging.slf4j.Log4jLoggerFactory.getContext(Log4jLoggerFactory.java:45)

at org.apache.logging.log4j.spi.AbstractLoggerAdapter.getLogger(AbstractLoggerAdapter.java:46)

at org.apache.logging.slf4j.Log4jLoggerFactory.getLogger(Log4jLoggerFactory.java:30)

at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:281)

at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:301)

at org.apache.hadoop.util.RunJar.<clinit>(RunJar.java:55)
</code>
Comment: Do you understand  the error messages?
Comment: My « understanding » is rather a deduction and googling... I understand Java do not know which file to pick as there are several between Hadoop and hive. Assuming my understanding is correct, how can I help Java to figure out which one to choose?
Comment: So, this isn't an error, and doesn't prevent Hive or Hadoop from actually working. You just might not get the correct logging output
Comment: Sorry Onecricketeer, missed this one. Hive is not even starting after firing up the error message. May be the Root cause is because hive is under the same directory as Hadoop .??. I mean Hadoop and Hadoop/hive
Answer: What you are seeing is a misconfiguration of the logging framework, which it detects and complains about, including a link to http://www.slf4j.org/codes.html#multiple_bindings which explains the following:

SLF4J API is designed to bind with one and only one underlying logging
framework at a time. If more than one binding is present on the class
path, SLF4J will emit a warning, listing the location of those
bindings.
When multiple bindings are available on the class path, select one and
only one binding you wish to use, and remove the other bindings. For
example, if you have both slf4j-simple-2.0.0-alpha0.jar and
slf4j-nop-2.0.0-alpha0.jar on the class path and you wish to use the
nop (no-operation) binding, then remove slf4j-simple-2.0.0-alpha0.jar
from the class path.

It is not uncommon to see this problem, when combining multiple things together that bring their own logging backend.  The solution is to figure out why (the jars are listed) and only leave one binding.
Comment: Thanks Thorbjorn. I noticed there was 2 similar jars, one into hive path and the other one into the Hadoop path. I removed one and tried to restart hive. The error message was then the same but with the 2 following jars log4j-slf4j vs slf4j-log4j. So should I remove all the 4 jars used by Hadoop and hive and stored in their respective directories ?
Comment: They each have a specific purpose about how pipe logs in through the slj4j api and out again.  I would suggest reading the slf4j documentation, as this is a little bit cumbersome due to historic reasons.  You may want to add the complete list of jars in your deployment to your question.
Comment: I will add the list of jars. Would like to thank you man for taking the time. Will update with the list of jar as soon I will be back home
Comment: Hi Thorbjorn: sorry for my weak knowledge but how do you remove a jar from a classpath...?
Comment: @lucTiber You open the file explorer and remove the file. However, that might make things worse if something depends on that file
Comment: Oh... that's it. I thought there was some Java ish magic... let si how it flies....
Comment: Thanks by the way onecricketeer
Comment: Hi Folks, removing the files make it only worst (from warming messages perspective) - here are the message I get (too many charachters so kept only what looks like most relevant):                                                    java.lang.NoClassDefFoundError: Could not initialize class org.apache.logging.log4j.util.PropertiesUtil
...Exception in thread "main" java.lang.NoClassDefFoundError: Could not initialize class org.apache.logging.log4j.util.PropertiesUtil
Comment: I am adding the following open question : how could it be possible I cannot have hive working on hadoop ... Am I missing something ... or worst (sorry this is me getting upset about 2 core bricks of the hadoop echo system cannot work at all )


K-mean clustering with unknown k

Question: How do I perform k-mean clustering with unknown k? I also need to provide a confidence interval for k. I am thinking in the line of putting a Poisson prior on k. Does that make sense? Does there exist any research on this topic?
Updated question:
I have multinomial discrete data - yes/no/maybe. 1000 question answered by 100 people. I have to find number of distinct groups, and a CI for that number.
Comment: I found this answer over at stackoverflow, which also has pointers to some theoretical work on the problem of choosing $k$: http://stackoverflow.com/questions/1793532/how-do-i-determine-k-when-using-k-means-clustering
Comment: This is too broad to be answerable as stated. Can you narrow your question? You can also ask a series of questions, linking each to the previous in turn. You may want to [search](http://stats.stackexchange.com/search?tab=votes&q=k-means%20k%20is%3aquestion) the site & read many of the existing threads that are related to your questions.
Answer: When you do k-means, it should be noted that the more the number of clusters you consider, the better your fit necessarily is (to understand why note that the more the number of clusters, the closer you are going to be to one of the centers)
There is no theory behind how to pick k in k-means. It is more a heuristic. What people generally do is they keep increasing the number of clusters till they notice an "elbow" in the MSE improvement i.e. they keep including clusters until they find a cluster n such that the fit obtained on using n+1 clusters is not substantially better than the fit obtained using n clusters
A real tricky situation is when there is no clear elbow, in which case other (equally hand wavy) heuristics are used to infer k.
I hope this convinces you that the question as it stands makes no sense.
Comment: Thanks for your comment. Let me clarify my problem little bit. I have multinomial discrete data - yes/no/maybe for 1000 question for 100 people. I have to find number of distinct groups, and a CI for that number.
Answer: You can use a quality mesure of k to choose it.
The state of the art internal evaluation method (based on data used for clustering) is the "silhouette coefficient"
The silhouette coefficient is a value between -1 and 1, mesuring how similar an object is to its own cluster (cohesion) compared to other clusters (separation).
The silhouette coefficient for a point i is defined as
(
the lowest average dissimilarity from i to any cluster other than that including i,
minus
the average of the dissimilarity from i to all points in its cluster
) divided by the max of both.
Consider dissimilarity as a distance.
The best k should be giving the best silhouette coefficient
A confidence interval might be linked to the difference between the silhouette coef. of the best two K ...
Regarding variables including discrete data or not, it should be normalized before clustering, that is, converted into values on a comparable scale.
External evaluation methods might give better result and confidance but I can't say ...but would need to provide a reference dataset.

K-mean clustering with unknown k


Does this definition of $e$ even make sense?

Question: This sprung from a conversation here. In Stewart's Calculus textbook, he defined $e$ as the unique solution to $\lim\limits_{h\to 0}\frac{x^h-1}{h}=1$. Ahmed asked how do you define $x^h$ is not by $\exp(h\ln(x))$ and I'm not sure.
Does this definition of $e$ even make sense?
Definition here:
Answer: The definition of $e$ as the unique number such that $$\lim_{h \to 0}\frac{e^{h} - 1}{h} = 1$$ makes sense, but there are few points which must be established before this definition can be used:

Define the general power $a^{x}$ for all $a > 0$ and all real $x$. One approach is to define it as the limit of $a^{x_{n}}$ where $x_{n}$ is a sequence of rational numbers tending to $x$ (this is not so easy).
Based on the definition of $a^{x}$ above show that the limit $(a^{x} - 1)/x$ as $x \to 0$ exists for all $a > 0$ (this is hard) and hence the limit defines a functions $f(a)$ for $a > 0$.
The function $f(x)$ defined above is continuous, strictly increasing and maps $(0, \infty)$ to $(-\infty, \infty)$ (easy if previous points are established).

From the last point above it follows that there is a unique number $e > 1$ such that $f(e) = 1$. This is the definition of $e$ with which we started. And as can be seen this definition must be preceded by the proof of the results mentioned in three points above. All this is done in my blog post and in my opinion this is the most difficult route to a theory of exponential and logarithmic functions. Easier routes to the theory of exponential and logarithmic functions are covered in this post and next.
Comment: arguably it is the most difficult but irritatingly it is also the must intuitively and direct to what we think the definitions "mean".  Intuitively $b^n$ is b multiplied by itself n times so "obviously" $b^{n/m}$ is the m-th root of b to the n and as x = lim q then $b^x$ is the limit of $b^q$.  I mean "duh" and obviously d(b^x)/dx = $C_b*b^x$ so there must be some $e$ where $C_e = 1$ and obviously $e^x$ means $e^x$ and $\ln x$ is just a logarithm.  That's obviously what it all "means".  It's a pity this is the freaking *hardest* approach.
Comment: @fleablood: as I say in my blog post "the most intuitive and obvious approach".
Comment: That's a nice blog post btw.
Answer: $b^x$ can be defined as $\lim_{q\in \mathbb Q \rightarrow x}b^q$. (Isn't it usually so defined?)  Or alternatively one can define $e = \lim_{h\in \mathbb Q\rightarrow 0}\frac {x^h - 1}{h}$.
I think it's legit and not circular.
Comment: Of course, this assumes there is a limit.
Comment: It works; $b^q$ is defined for rational $q$ in the "usual" way, and you can force the limit to exist using a monotonicity argument. It is essentially the same argument that is used to prove that the only memoryless distributions, i.e. the ones with the property $P(X>t+s|X>t)=P(X>s)$, are the exponential distributions.
Comment: I think defining new notions of limit is bit complicated and non-standard. The standard calculus texts define limits of functions of real variable and limit of functions of integral variable (sequences). If $x_{n}$ is a sequence of rational numbers with limit $x$ then we can define $a^{x}$ as the limit of sequence $a^{x_{n}}$. The notion of $\lim_{x \in \mathbb{Q} \to a}$ can be made precise by an appropriate definition but it is not very commonly seen.
Comment: This isn't a new definition of limits at all.  For every real $x$ there is a rational sequence of {$q_n$}$\rightarrow x$ so we define $b^x$ as $\lim b^{q_n}$.  That's all my notation of $\lim_{q\in \mathbb Q\rightarrow x}$ means.  We do have to clear up that such a real sequence of {$b^{q_n}$} converges but that's pretty standard and mechanical as Ian points out.  (Actually it's a pain in the ass, but never mind...)
Comment: The actual difficulty is establishing the uniqueness: why is $\lim_n b^{q_n}$ the same for any given $q_n \to x$?
Comment: True.  It's a pain.  But it can be done. need to establish for any $\epsilon > 0$ then there are rational $r < q < t$ such $b^q - \epsilon < b^r < b^q < b^t < b^q + \epsilon$ (assuming $b > 1$; equivalent but "flipped" if 0< b < 1).  Then as all $q_n \rightarrow x$ all $b^{q_n}\rightarrow c$ for the same c.  No-one's saying it's not a pain.  But it is a *valid* consistent non-circular definition.
Comment: @Ian: if $q_{n}, r_{n}$ tend to $x$ then $s_{n} = q_{n} - r_{n} \to 0$ and we need to show that $b^{s_{n}} \to 1$. This is easy.
Comment: @ParamanandSingh Yes, though you don't even need to localize, you use the same monotonicity argument anywhere.


Como usar um projeto GitHub como base para um novo?

Question: Estou tentando usar o projeto do angular-phonecat como base para um projeto novo, e fazer modificações em cima dele, pq a estrutura é bem parecida com o que eu quero desenvolver e assim não teria que configurar e baixar tudo que preciso(npm, bower). Porém sempre que crio um novo repositório, fica como se fosse uma cópia do  repositório original e não consigo commitar minhas modificações para meu projeto.
O que estou fazendo:

Fork do projeto angular-phonecat
Clone do meu fork
Crio um novo repositório no GitHub
Mudo o origin: git remote set-url origin git://github.com/meu-repositorio-criado
git fetch --prune (Pesquisei que isso apaga as branches, mas não deu certo para o que eu quero)
git push

Depois do push, o projeto do novo repositório fica igual ao angular-phonecat origial e eu não consigo enviar meus commits. O que fazer? Quero que o meu projeto seja independente, só com o 'esqueleto' do outro.
Answer: Faça o seguinte.
Clone o projeto e exclua a pasta .git em seguida, de forma que ele não mantenha as informações do Git após ser clonado:
git clone https://github.com/camilaavilarinho/angular-phonecat.git [nome-do-projeto] && rm -rf [nome-do-projeto]/.git

Crie um repositório para esse novo repositório, no Github. E então, informe no seu projeto qual o caminho do repositório remoto (esse que você acabou de criar):
git remote add origin [novo-caminho-do-projeto]

Depois disso, basta comitar e subir as alterações, que você não modificará mais o projeto original.
Comment: Essa opção --bare está pegando outros arquivos (hook, info, objects...) e não os arquivos do projeto (app, e2e-tests, scripts...)
Comment: Desculpe, é verdade, eu tinha um conhecimento errado da opção `--bare`. Alterei a resposta de forma que funcione para o que você precisa. :)


Control structures are failing me

Question: I am trying to make a simple Arduino game that keeps track of the number of times a button has been pressed. There are two buttons, one for each user, and whoever is closest to the random number that the Arduino picks, wins. "winning" being a light comes on next to the winers button. However I am stuck in what seems to be a rut—before I go further, I will divulge that I am just barely two weeks old into the whole arduino/C++ environment so my knowledge is pretty low.
Basically what I want to happen is that the game lasts a certain amount of time, lets say 5 seconds, then after the five seconds, all the button pushes are tallied and compared and a winner is picked. Then the game resets itself and we can play again. Where I am getting stuck at is in the timing function. I originally was subtracting a gameClock variable from the millis() function however I have read that it is bad practice to reset the millis() function. Perhaps my code will give you a better understanding of what I am trying to accomplish.
#include <Bounce.h>
  //Using Arduino UNO
  #define RBUTTON 2
  #define RRLED 3
  #define RGLED 4
  #define MBLED 5
  #define LGLED 6
  #define RLLED 7
  #define LBUTTON 8

  Bounce BounceR = Bounce(RBUTTON, 5);
  Bounce BounceL = Bounce(LBUTTON, 5);

  int lastStateR = 0;
  int lastStateL = 0;
  int switchLCount = 0;
  int switchRCount = 0;
  long gameClock = 5000;

  void setup() {
    //LED from left to right
    pinMode(RBUTTON, INPUT);
    pinMode(RRLED, OUTPUT); //Red
    pinMode(RGLED, OUTPUT); //Green
    pinMode(MBLED, OUTPUT); //Blue
    pinMode(LGLED, OUTPUT); //Green
    pinMode(RLLED, OUTPUT); //Red
    pinMode(LBUTTON, INPUT);
    Serial.begin(9600);

  }

  void loop() {
    BounceR.update();
    BounceL.update();
    int total = switchRCount + switchLCount;

    int valueR = BounceR.read();
    int valueL = BounceL.read();

if (valueL != lastStateL) {
  if (valueL == HIGH) {
      switchLCount++;
      Serial.print("Left button:");
      Serial.println(switchLCount);
      Serial.print("Total: ");
      Serial.println(total);
    }
}
  lastStateL = valueL;

if (valueR != lastStateR) {
  if (valueR == HIGH) {
      switchRCount++;
      Serial.print("Right button: ");
      Serial.println(switchRCount);
      Serial.print("Total: ");
      Serial.println(total);

    }
}
  lastStateR = valueR;

  }

Comment: You need to ask an actual question.
Comment: It's helpful to ask you question in the following format. "I want to do `X`. I tried `Y`, but when I ran it I saw `Z`. What should I do differently to see `X`?"
Comment: Wow, an Arduino question that isn't about using Serial correctly.  Still the basic loop problem, you only read the button state when you enter the loop.  And then loop again by yourself without ever updating the state.  So you can never see the button's being pressed.
Answer: You really should look at the arduino.cc forums for help on this stuff. There's a whole archive of knowledge, plus many people who have a lot of arduino experience.
There are basically 3 problems with your sketch.  First, as you said, the gameClock is not working like you want it to.  Just using a counter isn't going to cut it, even at only 16Mhz, the arduino is going to zip right through it in a lot less that 5 seconds. You need to actually time it.
Second, your button 'debouncing' is broken.  Debouncing buttons is actually quite tricky.  Fortunately, many many people have already solved the problem.  Check the arduino libraries, the forum and the playground.  The problem here is that you never set the lastDebounceTime variables to anything.
Finally, your sketch only reads the buttons once per game.  That throws everything else off.
It kills your debouncing and messes up the button press count.
I'll stop now to give you a chance to work it out.  Post another comment if you want more help.
Comment: Sorry for the such a delayed response, got all carried away with the holidays. :) So I have updated my code to make use of the "Bounce" library found on the arduino site. To my knowledge, it is functioning properly. I know that I didn't really give a clear cut answer as to what exactly I needed help with, so here is what I need. I need to be able to effectively create a "gameClock" that sets a time for the game. Once the time is up, the button counters are reset and we can play again. I updated my code above.
Comment: Much better. Now we can focus on the original question.  I'm not going to write the code for you.  When a game starts, read and store the value of millis() as the start time.  To see if the game is over, subtract start time from millis(), then compare to game time.

Control structures are failing me


What significance does the Key have on a composition?

Question: I'm struggling to understand how the key signature effects a composition.
If you took an average person and played them the national anthem in any key (as long as you stay major of course) they would recognize it right away as the same song - this to me alone gravitates me think the key is a rather trivial choice when composing...
Overall question: What is a tonal composer considering when choosing a key and what does it change about the piece?
I understand that a piece is modulated to accommodate for a vocal/instrument range, but do different keys evoke different emotion than others even when the piece is the same?
Comment: http://music.stackexchange.com/questions/3486/does-it-really-make-difference-to-play-a-song-in-a-different-key
Comment: http://music.stackexchange.com/questions/15221/whats-the-point-of-keys-other-than-c-and-am
Answer: Whooooo, this is a doozie of a question! There are several approaches to this answer, some given in topo morto's comments, but I'll focus on two others:
Historical Reasons
Most modern instruments today use what is called 12-tone equal temperament. (Even wind instruments, tympani, etc. tune based on this system.) This means that that each tone is precisely 100 cents apart from the next one. C is 100 cents away from C♯, which is 100 cents away from D, etc. This wasn't always the case; throughout history there were various tuning systems. We call these "temperaments" because the pitches are "tempered" to fit into a particular system. In the Pythagorean system, perfect fifths were emphasized, which meant that major thirds were out of whack. In "concentric" systems, the system emphasized the most-used keys, meaning that keys like F♯ were basically unusable.
Thus, when past composers were using particular tuning systems, different keys could actually sound different. The "quality" of C major was different than the quality of E♭ major, and so the choice of key could have been a deliberate choice. Or if a composer knew he wanted the second section of the piece to modulate down a major third, he'd have a limited number of original tonics where both keys would be successful in a given tuning system.
But as I said, today we have 12-tone equal temperament. However, some instruments just work better in some keys. Orchestra brass will sound fuller and richer in a key like D♭ major than they will in B major, and (good) composers will use this to their advantage.
Some Remarks on Cognition
You're right that we'd all recognize the national anthem no matter what key it's in. We call it "absolute pitch" (some erroneously call it "perfect pitch") when someone can instantly recognize a pitch, a tonal level, etc. But here's something interesting! A study took several famous songs---for example, the Jeopardy! theme---and played it at two different pitch levels for a group of listeners (musicians and non-musicians alike). The majority of listeners could discern which recording was at the "actual" pitch level. (I'll try to find the source for this.) Long story short, there is good reason to believe that absolute pitch is really just long-term pitch memory, and not some innate ability to just grab pitches and keys out of thin air.
In other words, there could be cognitive reasons for using particular keys, but I would say we're still a little too early in our understanding to say for sure.
Comment: @KolobCanyon I reckon the problem is that most people can only _notice_ if an entire recording is in a different key; it doesn't mean they can also "imagine" the pitch of individual notes therein without actually having that recording as a context. However, I think quite a lot of people get it more or less right if they actually _sing_ a piece.
Comment: Ahem. **Some** modern instruments use 12-edo temperament, namely those that can only produce a discrete set of different pitches. For the majority of instruments, not that much changed tuning-wise – they are and were always able to play the correct just intonation, but it would always be more difficult in some keys than others.
Comment: When people tell me perfect pitch is innate I never really believed it. It sounds like you found evidence that it may not be. For example, If you knew a song was in C like "Let it be", you could just think of that root note and build every other pitch from your memory of the song.
Comment: In the last bold part, Richard is referring to the Levitin effect.
Comment: @Dekkadeci Did Daniel Levatin really name that after himself?
Answer: Sometimes the range of the instruments dictate particular keys, sometimes it is better, for playing and the sound, that certain instruments play songs in certain keys. And, yes, the vocal tessitura has a big influence on a song's key.
I guess that when a composer is writing something new, he is messing about in one key initially, probably well aware of the physical constrictions it has on the instruments he has in mind.
But as far as a song sounding very different in one key as opposed to another, probably not. Having said that, some guitar-based songs will use the guitar friendly keys of E or A, emphasising the open strings, so changing their keys will lose some authenticity. I remember having to play the intro to the Big O's 'Pretty Woman', which had been transposed to Ab, from the original A. Starting that intro almost an octave too high on guitar spoiled it somewhat, but the horns seemed happier to play in Ab rather than A.
Answer: "I'm struggling to understand how the key signature effects a composition".
I think Richard answered the muaical questions.
One thing else to consider.
It is the singer that sets the key.  If a singer can't sing a song in the key of G, but but his/her voice sounds best in B, then that will be the key played.  I think it is singer preference what key signature is used.
Also, you should strive to play a song in any key requested.
Comment: Every key has it is own fingering pattern on piano and strings. Many virtuoso pros prefered black keys for fast fluent music (Chopin, Liszt, for example).  You should play in all keys fluently on any chosen instrument. Some orchestra instruments are in one key (B or B flat or E flat) only. Every history period had it`s popular pitch. The majority of guitar and lute music are in the keys of open strings (or half step down). Keys of D minor and C minor seem more sad and dark to me, D major and G major are much more brighter and alive....
Comment: The real crux concerning singer is not so much, where she/he sounds best, but whether he/she will be able to reach to highest and lowest notes at all. Compared to that more ease in the fingerings or a brighter sound for the instrumentalists is negligible.