Poor SSL performance with vsftpd

Question: I'm trying to tweak vsftpd to achieve maximum performance for my usage:

I have only one or two clients that connect to the server.
File size is between ~15MB and 1GB.
Typical transfer batch represent between 1 and 2GB of data.

For testing purposes, I'm using a tmpfs on both sides (thus eliminating any disks bottleneck) with a single 1GB file.
When SSL is disabled, performance is good, with a transfer rate at ~120MB/s (reaching the limits of gigabit networking).
With SSL enabled only for control traffic (and not data traffic), performance drops at about 112MB/s, which is still within the acceptable limits.
However, when SSL is enabled for data flows, the transfer speed drops dramatically:

6.7MB/s using 3DES & SHA (ssl_ciphers=DES-CBC3-SHA in vsftpd.conf)
16MB/s using DES & SHA (ssl_ciphers=DES-CBC-SHA)

I didn't tested other ciphers, but from what I can see from the CPU usage during the transfer, it seems that vsftpd is only using a single cpu/core per client. While this can fit for large ftp sites with hundreds of clients, I'd like to avoid this behavior and use more ressources on the server.
On a side note, if you have any ideas regarding other openssl ciphers...
Comment: Try the RC4-MD5 cipher. Seems to be a good balance of performance & security.
Comment: @HTTP500: indeed, way much better. 75MB/s average, albeit still using only 1 core.
Answer: I just read http://unhandledexpression.com/2013/01/25/5-easy-tips-to-accelerate-ssl/ which suggests to run openssl speed. Depending on the results, you might want to pick another algorithm. Sadly, I have no idea how to spread the load of one encryption task to several cores.
Comment: Indeed. I'm using RC4-MD5, but still looking for the solution.

Poor SSL performance with vsftpd


C# - Does DataTable.Merge() add duplicates or update?

Question: I have 2 DataTables. 1 with the current rows in my table from SqlServer and 1 with new rows that I want to add.
I want to do something like:
datatable1.Merge(datatable2);

I am trying to figure out, if duplicates between these two tables exist, will the duplicate be added to datatable1, or will it update the values in datatable1?
I need for duplicates to simply be updated in datatable1, and non-duplicates to be added to datatable1.
Iv searched MSDN and I cant really find a distinct answer.
Comment: you know there are plenty of examples on how to find duplicates in a DataTable have you googled for any... I would check for duplicates first, remove those etc.. then merge your data if still necessary..
Answer: From the last paragraph from the Merge documentaton

When merging a new source DataTable into the target, any source rows with a DataRowState value of Unchanged, Modified, or Deleted, is matched to target rows with the same primary key values. Source rows with a DataRowState value of Added are matched to new target rows with the same primary key values as the new source rows.

It will update any row that has the same primary key. The primary key is set by the DataTable.PrimaryKey property
Answer: The Remarks section if the Merge documentation contains the following paragraph

When performing a merge, changes made to the existing data before the merge are preserved by default during the merge operation. Developers can modify this behavior by calling one of the other two overloads for this method, and specifying a false value for the preserveChanges parameter.

However, the reference source shows
public void Merge(DataTable table)
{
    Merge(table, false, MissingSchemaAction.Add);
}

i.e. it actually calls the other overload with preserveChanges=false.
So looks like you should be getting the desired behavior. But if you want to be absolutely sure, just call explicitly the other overload and pass preserveChanges=false like this
datatable1.Merge(datatable2, false);


Admin log in on site with no logins

Question: I'm working on a site that, in production, will have no logins. We've gone with Drupal to facilitate the creating and editing of content by non-experts.
My question is, in this scenario, what's the best practice for allowing an administrator to log in? Since there no login on the main site, how does an admin access it?
I know there's the standard page mysite.com/user or mysite.com/user/login. Leaving that out there where knowledgeable users could find it seems less than ideal to me.
Is that how people do it? Or is there another way?
Comment: What are you asking here?  There is always going to be Drupal's superuser/root uid 1 user...
Comment: Sorry if I was unclear Jimajamma. jdu's answer addressed my concerns.
Answer: Those pages are, by default, blocked in the Drupal generated robots.txt file meaning that it's very unlikely a "regular user" will stumble on them.
Someone would have to know you were using Drupal, and then type in that URL.  You're right though:  many people will know how to do that.
However, it's not a big deal.  Your admin account password should be strong enough that it cannot be guessed at.  Drupal is quite secure.  You have nothing to fear about leaving that login form where it is unless your passwords are really, really bad.
The amount of effort to re-create the login pages elsewhere does not make any sense in this case.
Comment: Good answer. Don't worry about the "/user" URL. THe security of your Drupal site does not (and should not) depend on the obscurity of your login page.
Comment: Thanks, jdu. That was the reassurance I wanted. Just that it is safe and it's how it's usually done. I couldn't find any info on the subject anywhere.

Admin log in on site with no logins


Finding a maximal ideal of $\mathbb{Z}$x$\mathbb{Z}$

Question: I am currently studying for my first exam in my second course of abstract algebra and cannot seem to understand the reasoning in the following explanation. In finding a maximal ideal of $\mathbb{Z}$x$\mathbb{Z}$, why are we able to state in computing the factor ring (in the following picture) that the left hand side is equal to the right hand side? I guess i'm not understanding how that type of computation is possible.

Let $\mathbb{Z}\times 3\mathbb{Z}$ be an ideal of $\mathbb{Z}\times\mathbb{Z}$. Then compute the factor ring
  $$\begin{align*}
(\mathbb{Z}\times\mathbb{Z})/(\mathbb{Z}\times 3\mathbb{Z}) &\cong (\mathbb{Z}/\mathbb{Z})\times(\mathbb{Z}/3\mathbb{Z})\\
&\cong \{0\}\times\mathbb{Z}_3\\
&\cong \mathbb{Z}_3
\end{align*}$$
  Since $3$ is a prime number, the ring $\mathbb{Z}_3$ is a field, and hence the factor ring $(\mathbb{Z}\times\mathbb{Z})/(\mathbb{Z}\times 3\mathbb{Z})$ is a field.
Comment: Put differently, "clearly" the kernel of $\Bbb Z\times \Bbb Z\to \Bbb Z/3\Bbb Z$, $(x,y)\mapsto x+3\Bbb Z$ is precisely $3\Bbb Z\times \Bbb Z$.
Answer: I think the following lemma solves your question:
Lemma: Let $R,S$ be rings and $I$ an ideal of $R$ and $J$ an ideal of $S$. Then
$$(R\times S)/(I \times J) \cong R/I \times S/J$$
Proof: Define a map $\psi: R \times S \to R/I \times S/J: (r,s) \mapsto (r+I, s+J)$. Clearly this is a surjection with kernel $I \times J$ and the isomorphism follows from the first isomorphism theorem of rings. $\quad \square$
Comment: It is just a straightforward application of the first isomorphism theorem. I added a proof.
Comment: Yes, we know what the image is because the map I wrote down is a surjection. Thus the image is equal to the codomain. And yes, any ring is an ideal of itself. The ideal definition is satisfied trivially.
Comment: It does! Thank you very much. Where did you find this lemma?
Comment: Sorry just one more question: if we are referencing the first isomorphism theorem, don't we need to know what the image is?
Comment: Also, is $\mathbb{Z}$ an ideal of itself?
Comment: Thank you for your time! This cleared up my concerns.
Comment: If this answer helped, you may consider accepting it, letting others know your question is solved.


Google's Closure compiler, make the output file in one line

Question: Is there an option for making the output file of the Closure compiler into one single line?
It is wrapping the code at some point, inserting a new line, and I didn't find an option to change this behavior.
Thanks
Comment: This is a feature.  Some older browsers will choke on ultra-long lines in script files.
Comment: Stephen's comment should probably be an Answer so this question can be marked as Answered and Accepted.
Answer: The answer seems to be NO, it cannot be disabled. It is a feature.
Answer: You can set this using the Java API, 0 is used to indicate no break:
http://www.google.com/codesearch#l5BkQmivP-Y/trunk/src/com/google/javascript/jscomp/CompilerOptions.java&q=lineLengthThreshold%20package:http://closure-compiler%5C.googlecode%5C.com&type=cs&l=1797


How to animate text using JavaScript

Question: I want to implement animated text i.e. moving the text from bottom (half of the page) to the top like marquee. I don't get any good code. Does any one know how this is implemented in JavaScript or jQuery or DHTML?
Thanks in advance
Comment: @alex: +1 for that. It's even worse than "Ajax"... @Hema: If you don't "get any good code", how about writing some? If you can't figure it out, post your attempt here and people can improve on it.
Comment: @Matti Virkkunen: +1 for "do some writing".
Answer: use jquery
<code>  $('#mydiv').animate({
    top: 0
  }, 5000, function() {
    // Animation complete.
  });
</code>
Check the demo here
Comment: Tell me Why dont you use the marquee it self, it is much better than writing these scripts.
Comment: thanks.  i need the text must be move from bottom to top and again( continuously like marquee up direction). Could you please give me an complete answer
Answer: Same code as the answer below but, it sets the TEXT location to be at half the page's height, and then animates it to top:
<code>//Calculate where is HALF of the page (half the window height)
var start_pos = screen.height/2;

//Set starting TOP location
$(".text").css("top", start_pos+"px");

//Animate to the END location, which is 0px
$(".text").animate({ top:0+"px" }, 5000, function() { alert("Animation Complete"); });

</code>

How to animate text using JavaScript


invalid use of incomplete type 'class QGraphicsRectItem'

Question: I'm trying to create movable rectangle and here is my code.but following 3 errors appears.
invalid use of incomplete type 'class QGraphicsRectItem' rect->setFlag(QGraphicsItem::ItemIsMovable, true);

forward declaration of 'class QGraphicsItem' class QGraphicsItem;

incomplete type 'QGraphicsItem' used in nested name specifier

without this line (rect->setFlag(QGraphicsItem::ItemIsMovable, true);) program run without any error.
widget.h
#ifndef WIDGET_H
#define WIDGET_H

#include <QGraphicsScene>
#include <QWidget>
#include <QtCore>
#include <QtGui>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

private slots:
    void on_pushButton_clicked();

private:
    Ui::Widget *ui;
    QGraphicsScene *scene;
    QGraphicsEllipseItem *elipse;
    QGraphicsRectItem *rect;

};

#endif // WIDGET_H

widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include <QCursor>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    scene = new QGraphicsScene(this);
    ui->graphicsView->setScene(scene);

    QBrush redBrush(Qt::red);
    QBrush blueBrush(Qt::blue);
    QPen blackPen(Qt::black);
    blackPen.setWidth(6);

    elipse = scene->addEllipse(10,10,100,100,blackPen,redBrush);
    rect = scene->addRect(-10,-10,100,100,blackPen,redBrush);
    rect->setFlag(QGraphicsItem::ItemIsMovable, true);

}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_pushButton_clicked()
{

}

Comment: add `#include `  or `#include ` to widget.h, that solves your problem.
Comment: I recommend you include the header of each class you use so avoid this kind of silly problems.
Comment: Any time you ever see the compiler tell you that a type is "incomplete", it means that it has seen a forward declaration  e.g.

    class QGraphicsRectItem;

but hasn't seen the full class definition.

So all you have to do is find the header file that contains the full class definition and be sure it is properly included.
Comment: @eyllanesc Thank you very much sir :) problem solved. Sir how can I identify such type of errors. Qt displaying error not helps to me to identify real problem.have any way to identify such errors
Comment: @Joe thank u very much
Answer: You have not included <QGraphicsRectItem> class you are using in your code. Add it at the beginning like:
#include <QGraphicsScene>
#include <QGraphicsRectItem> //You missed
#include <QWidget>
#include <QtCore>
#include <QtGui>


Logistic Regression Limitations

Question: I have been given a problem where I need to create an algorithm to predict a binary variable with 10 coefficients. I have no idea what the relationship is between those coefficients, but I know that there is one. This relationship is likely very complicated. The correct algorithm will likely not only look at each variable as an individual, but how these variables relate to each other: Eg.
if (x > y and z < 0) OR (w < v AND a < b AND c > 5), return 0.
Else, if (insert criteria similar to one above), return 1
It's become pretty clear to me that a human can't really solve this task without using a tedious and excessive amount of guessing and testing. I have decided to use a logistic regression for this task, and I've already programmed a pretty straightforward model using turicreate to do this.
My question is: with enough data, can logistic regression models learn to accurately predict variables by assessing the relationship between coefficients? Is there a better way to do this, such as a decision tree / random forest / boosted tree?
Answer: Unless you invent clever features as highly non-linear functions of $\{X_1,X_2\}$, logistic regression will not be able to separate the two classes visualized below. Logistic regression will have to draw the boundary somewhere. Adding powers of $\{X_1,X_2\}$ will not help in this situation. You will need to know the nature of the two classes to introduce features based on the mod() function.

On the other hand, boosted trees and random forests will do the feature development for you. Automatically. Carefully.
Comment: +1. With the caveat that boosted trees and random forests need a lot of data.
Comment: @Stephan Kolassa Good point. Thank you.
Comment: Thanks! Will a decision tree work for this as well? If so, are they any more efficient in the amount of data that they need?
Comment: Though 1 classification tree could approximate the aforementioned relationship in theory, growing and pruning it would be difficult. Boosting and random forests would be better.

Logistic Regression Limitations


Combining ranges/arrays to feed into IRR

Question: I want to use the IRR function in Excel; however, my inputs exists in a non-contiguous range.
For example, I want to know the return of an asset over time (each row is a time period).

Column A has the cost (cash outflow) of owning the asset/
Column B is the price of the asset (cash inflow if liquidated).

So A1 is cost of owning the asset at time 1, A2
is the cost of owning at time 2 etc.
B1 is the liquidation price of the asset at time 1, B2 is the liquidation price of the asset at time 2 etc.
In Column C, I would like the return for each time period if I liquidate.

So for example C6 is the return of the asset if I liquidate at period 6, C7 is the return of the asset if I liquidate at period 7 etc.  So for C6, the cash outflow would be A1:A5, the cash inflow would be B6.
How do I feed IRR these two inputs?
Answer: From a technique I saw lori_m use
=IRR(IF(1-FREQUENCY(9^9,A1:A5),A1:A5,B6))

As per the simple example below, the FREQUENCYformula is used to mesh together A1:A5with B6. Returning an identical ÌRRto the same cashflows in a continuous range
Comment: Its a little complex ..... `FREQUENCY` is used to look up a very high number against 5 bins (A1:A5) which then returns 5 zeroes (as the data doesnt fit in these bins) and a single 1 (FREQUENCY returns an extra element. So the `IF` part then reads 1-{0,0,0,0,0,1} which then gives five TRUE results (A1:A5) and then 1 FALSE (B6) in a single array of values.
Comment: Can you elaborate what this is doing?
Comment: @agrimpathak Why would you downvote a working answer I took the time to create for your question?
Comment: I don't see how this will work, but still I tried and played around with it, and it didn't work.  And is this suppose to be an array formula?  Also, I think the answer will benefit with a brief explanation.
Comment: It isn't an array formula. It worked as is when I tried it on the same data layout you described.
Comment: Thanks, I confirmed it works and accepted it.  Though conceptually, how is FREQUENCY combining A1:A5 and B6?


get image from uploaded video codeigniter

Question: I am using Codeigniter to develop a website in which one of the features is to upload videos to a folder. There will be a gallery that contains several thumbnails corresponding to each video. Those thumbnails would work as a links to the corresponding video.
I created the gallery following this tutorial(code is available here):
Only changed the accepted files and added to the htaccess these lines:
php_value upload_max_filesize 100M
php_value post_max_size 100M
Here is my question: is it possible to use the present code to get the thumbnails (because I can do that if I upload images) or do I have to use ffmpeg or similar.
Answer: You will have to use FFMPEG-PHP (or similar) to get a thumbnail from a video.
Part of this guide explains how it's done:
https://arjunphp.com/upload-video-convert-flv-using-ffmpeg-codeigniter/
Answer: For pure PHP code I have found the following tutorial on Youtube quite useful as a starting point for my own CI project.
FFMPEG and PHP


The connection was reset when creating a new node

Question: On a localhost environment, when I try to create a new node, I get this message:

The connection was reset.

There is some issue with css, cache and/or registry since when I disable the css aggregation it works for the next node and it stops for the next node creating. In order to work again for a new node it needs enabling the Css aggregation and so on.
Also when I clear caches I get this kind of messages:

The following module has moved within the file system: views_test. In order to fix this, clear caches or put the module back in its original location. For more [warning] information, see the documentation page. bootstrap.inc:1128

Any suggestions?
Thanks.
Answer: There are in fact two issues in your question.
To solve The connection was reset issue, have you tried to run rebuild_registry ?
drush dl registry_rebuild-7.x
drush en registry_rebuild-7.x -y
drush cc drush
drush rr

Some people also reported that with Coder Module but not only, they had to edit httpd.conf, increasing the Apache stack size to 8MB
<IfModule mpm_winnt_module>
   ThreadStackSize 8388608
</IfModule>

For the 2nd issue The following module has moved within the file system, this appeared since Drupal 7.50 release. A straight way to correct these errors is to use Module Missing Message Fixer. You'll find alternatives and full explanations in this DO post.
Comment: Hi,I have both tried registry rebuild and increasing apache stack size but nothing worked. There is no httpd.conf file on apache so I created one but still it didn't work .Doh
Comment: I used the module "Module Missing Message Fixer" but it says "No Missing Modules Found!!! "   I have seen also other people have the same issue
Comment: Check the DO post, I had some of same issues and solved them either by creating a fake module (.info and .module) at the searched place, then `en/dis/uninstall` them...
Comment: Thanks for the help,I only am concerned about the Connection reset issue.THe other issue I just cleared the cache and it worked.
Comment: I am on ubuntu 16.04 and apache server 2.4.18 . I read that newer apache server do not have an httpd.conf file that's why I guess I have none.
Comment: Correct, you conf files should be then into `/etc/apache2/conf-available` dir. I guess you did put yours there or checked if there was any for your current project. Post smthing whenever you got it solved. Good luck :)
Comment: There was nothing there,so I created such a file but still no luck.Thanks anyway for the help.Cheers


Adjoint of integral operator

Question: On the space of $L^2([0,1])$ consider the following operator; $\Lambda u(x)= \int_0^xu(s)ds$ , I want to find the adjoint of this operator.
\begin{align}
(\Lambda u , g)
 & = \int_0^1\Big(\int_0^xu(s)ds\Big)g(x)dx  \\
& = \Big(\int_0^1u(x)dx\Big)\Big(\int_0^1g(x)dx\Big) - \int_0^1 u(x)\Big(\int_0^xg(s)ds\Big)dx
\end{align}
where I did integration by part (is it done correctly?). But I stuck how to proceed for getting $( u , \Lambda^\ast g)$
Comment: Same question [here](https://math.stackexchange.com/q/2825711) and [here](https://math.stackexchange.com/q/1201454).
Answer: You almost got it.  Since $(\Lambda g)'=g$ and $(\Lambda u)'=u$, we have
$$\begin{align}\langle \Lambda u,g\rangle &=\int_0^1\,(\Lambda u)(x)\,g(x)\,\text{d}x
\\&=\big((\Lambda u)(x)\,(\Lambda g)(x)\big)\Big|_{x=0}^{x=1}-\int_0^1\,u(x)\,(\Lambda g)(x)\,\text{d}x
\\&=(\Lambda u)(1)\,(\Lambda g)(1)-\int_0^1\,u(x)\,(\Lambda g)(x)\,\text{d}x
\\&=\left(\int_0^1\,u(x)\,\text{d}x\right)\,(\Lambda g)(1)-\int_0^1\,u(x)\,(\Lambda g)(x)\,\text{d}x
\\&=\int_0^1\,u(x)\,(\Lambda g)(1)\,\text{d}x-\int_0^1\,u(x)\,(\Lambda g)(x)\,\text{d}x
\\&=\int_0^1\,u(x)\,\Big((\Lambda g)(1)-(\Lambda g)(x)\Big)\,\text{d}x=\langle u,\Lambda^\dagger g\rangle\,,
\end{align}$$
where
$$(\Lambda^\dagger g)(x):=(\Lambda g)(1)-(\Lambda g)(x)=\int_x^1\,g(s)\,\text{d}s\,.$$
Answer: I would like to stress the strong analogy of the solution found by @Batominovski with finite dimensional linear operators, that can be useful in some other cases either for forecasting the adjoint or "verify" an already found result (please note the quotes around the verb verify).
What is the discrete equivalent of the "antiderivative operator" beginning at $0$ ?
The antiderivative operator can be placed in correspondence with the $(n+1) \times (n+1)$ lower triangular matrix:
$$ (f \mapsto \int_0^x f(s) ds) \ \ \ \ \ \leftrightarrow \ \ \ \ \ \begin{pmatrix}1&0&0&\cdots &0\\
1&1&0&\cdots&0\\
1&1&1&\cdots&0\\
\vdots&\vdots&\vdots &&0\\
1&1&1&\cdots&1\end{pmatrix}$$
which is applied to column vectors whose entries are discretized values $f_0,f_1,f_2, \cdots, f_n$ of generic function $f$ at points
$$0=\tfrac0n, \ \ \tfrac1n, \ \ \tfrac2n, \ \ \cdots \ \ \tfrac{n-1}{n}, \ \ \tfrac{n}n=1.$$
We know that the equivalent of the "adjunction operation" is matrix transposition :
$$\begin{pmatrix}1&1&1&\cdots &1\\
0&1&1&\cdots&1\\
0&0&1&\cdots&1\\
\vdots&\vdots&\vdots &&1\\
0&0&0&\cdots&1\end{pmatrix}  \ \ \ \ \ \color{red}{\leftrightarrow} \ \ \ \ \  (f \mapsto \int_x^1 f(t) dt)$$
...
(this correspondence $\color{red}{\leftrightarrow} $ being as intuitive as the first one).
For more, see in particular the second example in this question of mine.
Comment: This was a good intuition. thanks.

Adjoint of integral operator


Is there any dump() like function returns a string?

Question: I like Swift's dump() function like this,
class MyClass {
    let a = "Hello"
    let b = "Bye!"
    init() {}
}
let myClass = MyClass()

dump(myClass) // Printed out these lines to Xcode's console
/*
 ▿ MyClass #0
 - a: Hello
 - b: Bye!
 */

But dump() doesn't return a string. It just prints out to the console, and returns 1st parameter itself.
 public func dump<T>(x: T, name: String? = default, indent: Int = default, maxDepth: Int = default, maxItems: Int = default) -> T

Is there any dump() like function returns a string?
Comment: I'd like to log via [SwiftyBeaver](https://github.com/SwiftyBeaver/SwiftyBeaver)
Comment: What's your main goal?
Answer: From: https://github.com/apple/swift/blob/master/stdlib/public/core/OutputStream.swift
/// You can send the output of the standard library's `print(_:to:)` and
/// `dump(_:to:)` functions to an instance of a type that conforms to the
/// `TextOutputStream` protocol instead of to standard output. Swift's
/// `String` type conforms to `TextOutputStream` already, so you can capture
/// the output from `print(_:to:)` and `dump(_:to:)` in a string instead of
/// logging it to standard output.

Example:
let myClass = MyClass()
var myClassDumped = String()
dump(myClass, to: &myClassDumped)
// myClassDumped now contains the desired content. Nothing is printed to STDOUT.

Comment: While i was using Objects, it gives me detail printed output on console. Good addition in swift:)
Answer: try this if you want :
let myClass = MyClass()
print("----> \(String(MyClass))")
print("----> \(String(dump(myClass))) ")

UPDATE:
you can combine the string you like use Mirror:
let myClass = MyClass()
let mirror = Mirror(reflecting: myClass)
var string = String(myClass) + "\n"
for case let (label?, value) in mirror.children {
        string += " - \(label): \(value)\n"
}
print(string)

hope it be helpful :-)
Comment: Hi. I'd like to get a dumped string as a Swift's String type instance. dump() only prints out to the console.


Rotate CSS3 e Tabelas

Question: Estou utilizando dados tabulares em uma tabela e algumas informações com 90 graus (em pé) nas células. Porém o css não se comporta como o esperado e deixa espaços grandes como se o texto estivesse normal na horizontal. Alguém sabe de alguma propriedade que resolva isso?
Segue link aqui para ver como ficou. Apenas coloquei :
 p {
            -webkit-transform: rotate(-90deg);
            white-space: nowrap;
        }

Comment: Acho que ajudaria bastante se você mostrasse o trecho de código CSS pertinente e o resultado atual, dsantoro.
Answer: O jeito é forçar a largura na marra. Adicione:
width: 20px;

Ao parágrafo.
Note que isso faz com que o texto suba um tanto. Para corrigir, é preciso adicionar uma margem acima. Consegui uma boa margem para o seu caso específico com 170 pixels... Outros casos podem precisar de outras medidas. Experimente também com medidas não fixas depois, pois assim terá algo mais reutilizável. O CSS completo do parágrafo fica mais ou menos assim:
p {
    -webkit-transform: rotate(-90deg);
    white-space: nowrap;
    width: 20px;
    margin-top: 170px;
}

Comment: Opa. Isso ajudou bastante ein. Tamo quase lá. Descobri algo sobre isso, esse "issue". Segue link http://www.benknowscode.com/2014/01/css-rotated-text-parent-dimensions-and-spacing-issues.html
Comment: Valeu pelo link! Não costumo usar rotações, mas isso despertou bastante minha curiosidade!
Comment: Também não costumo usar mas as vezes o trabalho nos obriga rs.
Answer: Parte da culpa pode ser da definição padrão da propriedade Display para elementos P.
Tente o seguinte:
 p {
    -webkit-transform: rotate(-90deg);
    white-space: nowrap;
    display:inline-block;
    }

Um Fiddle de demonstração pode ser visualizado aqui.
Comment: O Fizzdle não ta abrindo rs. Mas não resolveu. Não sei se é algo na tabela ou no p. Acho que o CSS não da preparado pra isso.

Rotate CSS3 e Tabelas


asp.net keeps on calling a function in page_load

Question: I've a form (mainpage.aspx), on which there's a button called 'Cancel'. Here's the  code for the button:
<asp:LinkButton ID="btnCancel" runat="server" Text="Cancel" CssClass="btn btn-default" OnClick="btnCancel_Click" />

and the called function
protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("EventList.aspx");
    }

So as you can see, what the button do is simple. Just go to another page. But it seems here that doesn't happen. Every time I click the Cancel button, first it will try to load the code
Response.Redirect("EventList.aspx");

but then somehow it will try to execute the codes below:
if (hdnEventId.Value != "" && hdnEventId.Value != "0")
            {
                LoadEvent();
}

I know this because I put a breakpoint on Response.Redirect("EventList.aspx"); and after that I step into the code above
btw the codes above are located inside
protected void Page_Load(object sender, EventArgs e)

inside the file mainpage.aspx.cs
Answer: That's because Page_Load is called on any postback and you're actually doing a postback by clicking Cancel. The solution is to wrap your non-postback specific code in a IsPostBack check:
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        if (hdnEventId.Value != "" && hdnEventId.Value != "0")
        {
            LoadEvent();
        }
    }
}

Comment: @M_Griffiths Haha always the case, if I had 10 rep for everytime I'd abandoned an answer because someone beat me to it I'd have more rep than Jon Skeet :)
Comment: @mattytommo but the codes that're being called are already inside if (!Page.IsPostBack)
Comment: @mattytommo I already did what you asked but the problem still happens. It still try to load the LoadEvent()
Comment: @imin So when you put a breakpoint in `Page_Load`, it actually hits when you've redirected? And `IsPostback` is false?
Comment: @mattytommo yes, Page_Load is being hit again. And Yes, IsPostBack is false. Just in case, I'm using the URL rewriting module, if that helps.
Comment: @imin So it looks like you're getting redirected back to your main page somehow. There's no redirect set up in your `EventInfo` page is it? What are you URL rewriting in this instance? Is the main page your fallback page for URLs that the rewriter can't match?
Comment: Err.. .sorry I can't fully grasp what u're asking. Anyway yes, the page EventList.aspx is the fallback page for URLs that the rewriter can't match


Why is button three on trumpet almost never used alone?

Question: The trumpet buttons 1,2 and 3 lowers the pitch by 2,1 and 3 halfsteps. So pressing button 1 and 2 gives the same result as only pressing the third button.
So why is the third button so rarely used alone? Why press two buttons instead if you don't have to? I have seen it be used for fast drills that would be almost impossible otherwise, but I cannot understand why it isn't the default for playing the notes E and A.
Comment: In my youth and during the military service I always used the fingersttings like you discribed. One reason is mentioned in my answer. Another reason could be that most pieces for brassbands are in the keys of G,C,F or Bb. and the fingersetting  1,2 insread of 3 is more comfortable. After a time out of some dekades I've started to practice my instrument again and in a Euphonium Bb Solo in D (actually C) I use more often the 3rd valve exactly because of the reasons you're counting.
Answer: Because valve #3 is normally tuned slightly flatter than #1 + #2.  This is to do with the physical fact that each semitone down requires the tube length to increase by the same PROPORTION, not by the same fixed length.
The real situation is complicated by most professional-quality instruments having finger-operated slides on valves #1 and #3, allowing them to be lengthened.  But #3 is still normally adjusted to be longer than the sum of #1 and #2, so it would make notes normally played by #1 + #2 too flat.
On a trumpet without 'triggers', low C# and F#, the only notes requiring #1 + #2 + #3, are, if not un-usable, certainly difficult to play in tune.
Comment: As I'm using three different instruments I have always to compensate the pitch by the lips or other fingerings. Even the natural tone sol (F) of the yamaha euphonium is too high that I play it as1,2 when there is a long note to hold.
Answer: Button=Valve (wind instrument)
Component of brass instruments
Valves are used on brass instruments to change the tube length to allow a chromatic play. When the valve is actuated, the air is passed through an additional pipe loop of a certain length, extending (usually) the air column of the instrument.
The first valve lowers the natural tone by two semitones (12.4%),
The second valve lowers the natural tone by one semitone (6.0%),
The third valve lowers the natural tone by three semitones (19.1%),
Intonation:
If two or more valves are used in combination, the intonation of the sound heard does not correspond to the calculated sum of its intervals, but to a tone that is too high. This is because the additional tube length switched by each valve into the resonator body is only calculated to increase the air column of the open instrument by a certain interval, but does not take into account the air column already extended by another valve.
The intonation when using multiple valves at the same time is therefore basically more or less unclean if no compensation takes place in any form. Quintessence from this realization: The fewer valves are needed, the better the tone is right.
https://als.wikipedia.org/wiki/Ventil_(Blasinstrument)
There are basically as few valves as possible to use.
With the small differences of the "short" valve combination (1 + 2), the compensation is usually done by ear via the approach.
As you're supposing:
The use of the clean handle 3 would be desirable, but in practice usually not possible, since in the fingering tables of the instrumental schools and thus in the training, the combination 1 + 2 in the foreground.
For instruments of rather short overall length like the trumpet, the difference in combinations with the third or first valve is usually compensated by simply pulling out the valve train of the third valve. Therefore cornets, wing horns as well as high-quality tubes and euphoniums have often already standard triggers as an additional intonation aid.
Comment: Would it be unkind to suspect  Albrecht Hügli''s answer reached us via a translation program?  He obviously knows his stuff, but it's coming across rather incomprehensibly.  And surely "calculated to decrease the air column" should be "calculated to INCREASE the air column"?
Comment: No, this wouldn't be unkind at all! This is the source:https://als.wikipedia.org/wiki/Ventil_(Blasinstrument) and ths is even more incomprehensible. You are rightthe term in the original  for "decrease"  was"draws down". It would have been much easier to say it in my own words than to translate the whole stuff by copy paste.
Comment: @LaurencePayne If you feel that an answer can be improved and that you can do it, then feel free to do so. That's how this site works.


the equivalency of two definitions of locally closed sets

Question: here there are 2 definitions of locally closed sets:
$A$  is locally closed subset of $X$ if:
a) every element in $A$ has a neighborhood $V$ in $X$ such that $A\cap V$ is closed in $V$.
b) $A$ is open in its closure (in $X$)
why a) and b) are equivalent?
Answer: For me the definition is the following:
$c)$ $A$ is equal to $U\cap F$ where $U$ is open in $X$ and $F$ is closed in $X$.
Let us prove that this is equivalent to your definitions, that I write again here:
$a)$ For each $x\in A$ there is a neighbourhood $V$ of $x$ in $X$ such that $A\cap V$ is closed in $V$.
$b)$ $A$ is open in its closure $\overline{A}$ in $X$.
The proof is made in the following steps:
$c)\Rightarrow a)$ Just choose $V=U$, which is a neighbourhood of any point of $A$.
$a)\Rightarrow b)$ For each point $x\in A$ we use the given neigbourhood $V$ such that $A\cap V$ is closed in $V$. We can replace $V$ with an open neighbourhood $U\subset V$ (since $A\cap U=(A\cap V)\cap U$ is closed in $U$), and assume that $V$ is open.
The fact that $V$ is open implies that the closure of $A\cap V$ in $V$ is equal to $\overline{A}\cap V$. Indeed, $A=(A\cap V)\cup (A\cap (X\setminus V))$ so $\overline{A}\subset \overline{A\cap V}\cup \overline{A\cap (X\setminus V)}$. As $V$ is open we have $\overline{A\cap (X\setminus V)}\subset X\setminus V$, hence  $V\cap \overline{A\cap (X\setminus V)}=\emptyset$, so we get $$\overline{A}\cap V\subset \overline{A\cap V} \cap V.$$
The other implication being clear, and using the hypothesis that $A\cap V$ is closed in $V$ we get$$\overline{A}\cap V=\overline{A\cap V} \cap V=A\cap V\subset A.$$
Hence, $\overline{A}\cap V$ is a neighbourhood of $x$ in $\overline{A}$ contained in $A$. Doing this for all points of $A$, this shows that $A$ is open in $\overline{A}$.
$b)\Rightarrow c)$ Since $A$ is open in $F=\overline{A}$, there exists an open subset $U$ of $X$ such that $\overline{A}\cap U=A=F\cap U$.
Comment: "That since $A\cap V$ is closed in $V$ then $A \cap V = \overline{A} \cap V$" can you explain why? The closure of $A\cap V$ in $V$ is $\overline{A\cap V}\cap V$, isn't it?
Comment: This works if $V$ is open, and we can assume this. I will edit the post. Thanks for the remark.
Comment: You can directly see the closure of $A\cap V$ in  is equal to $\bar{A}\cap V$, since the closure of union is the union of closure. Therefore $\bar{A}=\overline{A\cap V}\cup\overline{A\cap(X-V)}=\overline{A\cap V}$ and $\bar{A}\cap V=\overline{A\cap V}\cap V$.
Answer: b) $\Rightarrow$ a)
Let $A$ be open in $\overline{A}$. Then $A=\overline{A}\cap U$
for some $U$ open in $X$ and $U$ serves as neighborhood for every
element of $A$. Intersection $A\cap U$ equals $A=\overline{A}\cap U$
which is a subset of $U$ closed in $U$.
a) $\Rightarrow$ b)
Let $N$ be a neighborhood of $a\in A$ such that $N\cap A$ is closed
in $N$. Its closure in $N$ is $N\cap\overline{A}$ so actually we
have $N\cap A=N\cap\overline{A}$. That shows that $N\cap A$ is a
neighborhood of $a$ in the subtopology on $\overline{A}$, and it
is contained in $A\subset\overline{A}$. For any $a\in A$ such a neighborhood
exists, so $A$ is open in $\overline{A}$.
Comment: In b)$\Rightarrow$ a) you can just take $U=A$.
Comment: @RobinBalean $A$ is a set that is open *in its closure*. That does not mean that $A$ is an open set (like $U$). Be aware that e.g. every closed set is open in its closure (because it coincides with its closure). So in general we cannot go for $A=U$.
Comment: Ah - thanks for pointing that out.  I was a bit too hasty.
Answer: Just for the sake of completeness, I will state the complete list of equivalences:

Proposition. Let $X$ be a space and $A\subset X$ be a subspace. The following are equivalent:
(1) There is $U\subset X$ open such that $A\subset U$ and $A$ is closed in $U$.
(1') $A$ is the image of the composition of a closed immersion followed by an open immersion.
(2) There is $F\subset X$ closed such that $A\subset F$ and $A$ is open in $F$.
(2') $A$ is the image of the composition of an open immersion followed by a closed immersion.
(3) $A=U\cap F$, for some $U\subset X$ open and $F\subset X$ closed subsets.
(4) For all $x\in A$ there is an open neighborhood $U\subset X$ of $x$ such that $A\cap U$ is closed in $U$.
(5) For all $x\in A$ there is a neighborhood $U\subset X$ of $x$ such that $A\cap U$ is closed in $U$.
(6) $A$ is open in $\overline{A}$.
(7) There is $U\subset X$ open such that $A\subset U$, $A$ is closed in $U$, and $U\cup \overline{A}=X$.
If any of these equivalent conditions happens, we say that $A$ is locally closed in $X$.
Moreover, if $A$ is locally closed in $X$ and $U\subset X$ is an in (7), then $U=(X\setminus\overline{A})\cup A$ and $U$ is the maximum in open subsets $V$ of $X$ that contain $A$ and such that $A$ is closed in $V$.

The proof of the equivalences (1)$\Leftrightarrow$(1'), (2)$\Leftrightarrow$(2'), and (1)$\Leftrightarrow$(2)$\Leftrightarrow$(3) is immediate. The rest of the equivalences that do not involve (7) were already proven by Jérémy Blanc on his answer.
(6)$\Rightarrow$(7). Since $\overline{A}\setminus A$ is closed in $X$, the set $U=X\setminus(\overline{A}\setminus A)=(X\setminus\overline{A})\cup A$ is open in $X$. It is clear that $\overline{A}\cup U=X$. The closure of $A$ in $U$ equals $\overline{A}\cap U=A$.
(7)$\Rightarrow$(6). We have $X\setminus\overline{A}=U\setminus\overline{A}=U\setminus A$, where the last equality follows since $\overline{A}\cap U=A$, for $A$ is closed in $U$. Hence $U=(X\setminus\overline{A})\cup A=X\setminus(\overline{A}\setminus A)$ is open, so $\overline{A}\setminus A$ is closed. Thus, $A$ is open in $\overline{A}$.
Finally, to see the maximality of $U=(X\setminus\overline{A})\cup A$, let $V$ be an open subset of $X$ containing $A$ and such that $A$ is closed in $V$. Let $x\in V$. If $x\in A$, then $x\in U$. If $x\notin A$, then $x\in V\setminus A=V\setminus\overline{A}\subset X\setminus\overline{A}\subset U$ (the first equality follows from the fact that $A$ is closed in $V$). Hence $V\subset U$.


Filesystem independent way of using glob.glob and regular expressions with unicode filenames in Python

Question: I am working on a library which I want to keep platform, filesystem and Python2.x/3.x independent. However, I don't know how to glob for files and match the filenames against regular expressions in a platform/file-system independent way.
E.g. (on Mac, using IPython, Python 2.7):
   In[7]: from glob import glob
   In[8]: !touch 'ü-0.é' # Create the file in the current folder

   In[9]: glob(u'ü-*.é')
  Out[9]: []

   In[10]: import unicodedata as U

   In[11]: glob(U.normalize('NFD', u'ü-*.é'))
  Out[11]: [u'u\u0308-0.e\u0301']

However, this doesn't work on Linux or Windows, where I would need unicode.normalize('NFC', u'ü-*.é'). The same problem arises when I try to match the filename against a regular expression: only a unicode regular expression normalized as NFD on Mac matches the filename whereas only an NFC regular expression matches filenames read on Linux/Windows (I use the re.UNICODE flag in both instances).
Is there a standard way of handling this problem?
My hope is that just like sys.getfilesystemencoding() returns the encoding for the file system, there would exist a function which returns the Unicode normalization used by the underlying filesystem.
However, I could find neither such a function nor a safe/standard way to feature-test for it.

Mac + HFS+ uses NFD normalization: https://apple.stackexchange.com/a/10484
Linux + Windows use NFC normalization: http://qerub.se/filenames-and-unicode-normalization-forms
Link to code: https://github.com/musically-ut/seqfile/blob/feat-unicode/seqfile/seqfile.py
Comment: I'm pretty sure Windows and Linux don't normalize at all.
Comment: In fact I just checked, and they don't: http://i.imgur.com/lQv35KB.png Linux will also accept sequences or bytes that are not UTF-8
Answer: I'm assuming you want to match unicode equivalent filenames, e.g. you expect an input pattern of u'\xE9*' to match both filenames u'\xE9qui' and u'e\u0301qui' on any operating system, i.e. character-level pattern matching.
You have to understand that this is not the default on Linux, where bytes are taken as bytes, and where not every filename is a valid unicode string in the current system encoding (although Python 3 uses the 'surrogateescape' error handler to represent these as str anyway).
With that in mind, this is my solution:
def myglob(pattern, directory=u'.'):
    pattern = unicodedata.normalize('NFC', pattern)
    results = []
    enc = sys.getfilesystemencoding()
    for name in os.listdir(directory):
        if isinstance(name, bytes):
            try:
                name = name.decode(enc)
            except UnicodeDecodeError:
                # Filenames that are not proper unicode won't match any pattern
                continue
        if fnmatch.filter([unicodedata.normalize('NFC', name)], pattern):
            results.append(name)
    return results

Comment: Great! It looks like this would be a good addition to [glob2](https://github.com/miracle2k/python-glob2), which I can reuse in `seqfile`. I'll test this approach with `seqfile` tonight and see how to best package this with `glob2`.
Comment: I have implemented a slightly modified version of this function here: https://github.com/musically-ut/seqfile/blob/feat-unicode/seqfile/seqfile.py#L23 to work with regexs instead of glob patterns. I intend to test it a bit more before merging it in and releasing a new version.
Answer: This is how I solve the problem:
import unicodedata as U

    # ...

    globPattern = os.path.join(folder, prefix + u'*' + suffix)
    rawRegEx = prefix + u'([0-9]+)' + suffix + u'$'

    # Mac uses NFD normalization for Unicode filenames while windows
    # linux/windows use NFC normalization
    if sys.platform.startswith('darwin'):
        normalizedGlobPattern = U.normalize('NFD', globPattern)
        normalizedRegEx = U.normalize('NFD', rawRegEx)
    else:
        normalizedGlobPattern = U.normalize('NFC', globPattern)
        normalizedRegEx = U.normalize('NFC', rawRegEx)

    allFiles = glob.glob(normalizedGlobPattern)

    # ...

    numFilesRegEx = re.compile(normalizedRegEx, _re.UNICODE)
    numberedFiles = (re.search(numFilesRegEx, f) for f in allFiles
                     if re.search(numFilesRegEx, f))

This seems to pass all tests I could throw at it on AppVeyor (Windows), Travis (Linux) and my laptop (Mac + HFS+).
However, I am not sure whether this is safe or whether there is a better way of writing it. For e.g., I don't know whether it will work on a Mac with a NFS mounted on it.


How enable Taxonomy to work with Basic Pages

Question: When I create an Article I choose an appropriate Tag from my Taxonomy List and save the article. When I click the tag after I save the article I get a list of articles with the same tag.
But how do you make a Basic Page work this way? I've researched Manage Fields and Manage Displays in admin-structure-types-manage and I CAN choose a tag and save it with the Basic Page...but I can't click on a tag on a Basic Page and get a list of all Basic Pages with the same tag.
Can you assist?
Comment: There might be other things to check for, so let me know if my answer does'nt do the trick.
Answer: You probably have your field being displayed as Plain text. To display as links:

Go to your content type and Manage Displays
Find the Tags field and make sure the Format column has the Link value

Note that I'm assuming that you added the Tags field to your Basic Page content type and it's showing up in your page.
Comment: Yep, just what I was about to write.  The other thing I'd mention to the OP is that he might be getting confused once he does get a list of content tagged with the term he clicked.  It will be a list of *all content* in the site tagged with that term (regardless of content type), so it will be a mix of Basic Pages and Articles.
Comment: Thanks, yes, I've got the Tags field:  field_tags, enabled in Manage Fields  and in Manage Display the Tags are in Region: Content, Label: Inline; and Format: Link with the # sign. The tags do appear when I create a Basic Page. But still no joy...I can't seem to get any "Basic Page" to appear when I click a Tag link. I can access a Basic Page by creating a Menu Item...but not a Tag.
Comment: Could you double check your Tag field type? Go to Manage Fields and make sure it is Term reference.
Comment: Now I'm confused, I thought that you could NOT click on them? Can you actually click on them?
Comment: Yes, my Tag Field Type is Term Reference. And yes, I can input a Basic Page and save it. The tag appears at the bottom of the Basic Page. I have input two Basic Pages, both with the same Taxonomy string from my Taxonomy List. But when I click the Tag at the bottom of either of the Basic Pages, I go to a page with the Taxonomy Term at the top, but no content below.
Comment: Sorry, so yes, I CAN click on a Tag and go to a page...with no content.
Comment: It's strange, as this is a Drupal core behaviour. It's hard to tell, but other things to check:
1) Try enabling the bartik theme (in case it's a theme issue)
2) Double check your nodes are marked as "Published"
3) Are you using Views? (if so, there's a View that overrides the default Drupal taxonomy results page)
4) In Manage Display, go to Teaser and check that you have visible fields.


Get the list of available services

Question: Is there a way to get the list of the available services in  Drupal 8?
Answer: The module Devel provides a searchable list (/devel/container/service).
For the command line use Drupal Console:
drupal debug:container

Comment: Or since Drupal Console does not seem to be active anymore, you can use drush to get this information. Make sure the devel module is installed and then run drush devel:services.
Comment: That's perfect ! Thanks for help . Also found another solution we can search it at https://api.drupal.org/api/drupal/services
Comment: Yes, the list online is perfect for core services, but if you search with devel or console locally you'll also get services from installed modules.
Comment: I agree completely,actually I think looking with Devel is better because may be some contributed module provide some service which is not listed online.
Comment: It's too bad the devel list of services doesn't include the methods of those services. :(
Comment: @liquidcms, devel can't replace an IDE.
Comment: @4k4, usually very helpful.. but that's a bit of a silly comment. :(
Comment: @liquidcms, wasn't meant to be a silly comment. Devel is a runtime tool, providing a limited amount of data, collected when Drupal is bootstrapped. Programming with OOP methods on the other hand is what you do in an IDE.
Comment: Devel patch to add in list of service methods: https://www.drupal.org/project/devel/issues/3130469#comment-13577092
Answer: to Enhance  @4k4  answer, because it returns a lot of services names, if you looking for the specified service name, just pass a part of its name
Drush only method
drush eval "print_r(\Drupal::getContainer()->getServiceIds());"

for instances, if you looking for log services
drush eval "print_r(\Drupal::getContainer()->getServiceIds());" | grep "log"

and if you looking for  cache services
drush eval "print_r(\Drupal::getContainer()->getServiceIds());" | grep "cache"

Drush with devel module
Devel module offers a nice shortcut for drush
drush devel:services

or use its aliases:
drush devel-container-services

OR
drush dcs

OR
drush devel-services

Drupal console
drupal debug:container

So drush dcs | grep "PART_OF_SERVICE_NAME" will be a good sample to find a serice
Update
in new version you can just do it with drush dcs PART_OF_SERVICE_NAME
( thanks @Cameron to mention this in comment)
Comment: Drupal console is IMHO not the best answer anymore. Drush can do it without any extra module, and Drush is maintained much better than Drupal console.
Comment: It takes a parameter so 'drush dcs PART_OF_SERVICE_NAME' works.
Comment: @Cameron thanks. I've update the answer with your comment.
Answer: With plain drush, no extra modules required:
drush eval "print_r(\Drupal::getContainer()->getServiceIds());"
If you are searching for a something specific, pipe the output into grep to filter the results, e.g. searching for "views"
drush eval "print_r(\Drupal::getContainer()->getServiceIds());" | grep "views"
Answer: \Drupal::getContainer()->getServiceIds() is the REPL friendly way of doing this. Also you can use that on your module code etc..
The services can be also filtered:
preg_grep('/cache/', \Drupal::getContainer()->getServiceIds());

Answer: If you are interested to see the available services during development in PHPStorm you can enable the SymfonyPlugin which autocompletes for you the service names (and does much more other handy stuff)
It works both in services.yml and when calling $container->get(...).

Comment: Additionally in order for this to work properly you need to set your project as "Drupal project" on PHPStorm. Usually "he" is smart enough to suggest it to you when you create the project the first time. Check this https://www.jetbrains.com/help/phpstorm/drupal-support.html to find out more about Drupal's support on PHPStorm.
Comment: Unfortunately, it seems one cannot stop the animation. It can get a bit annoying.
Comment: I will put it in spoiler.
Answer: A list of services are available on drupal.org
https://api.drupal.org/api/drupal/services/8.9.x
Answer: There is the PHPStorm Metadata module which can be used to get autocompletion for all services (core, contrib and custom) in PHPStorm. And it also can give you that list.

This module allows to export PHPStorm Advanced Metadata in order to
get autocomplete functionality and return type information for next
calls:

Drupal::service()
ContainerInterface::get()
EntityTypeManager::getStorage()

After installing and enabling it, run drush phpstorm-metadata:generate and it will generate a file called .phpstorm.meta.php in your Drupal root directory. Inside there is a list of all available services (core, contrib and custom) mapped to their class.

// ...
'theme_handler' =>  \Drupal\Core\Extension\ThemeHandler::class,
'theme_installer' =>  \Drupal\Core\Extension\ThemeInstaller::class,
'entity.manager' =>  \Drupal\Core\Entity\EntityManager::class,
'entity.memory_cache' =>  \Drupal\Core\Cache\MemoryCache\MemoryCache::class,
'entity_type.manager' =>  \Drupal\Core\Entity\EntityTypeManager::class,
'entity_type.repository' =>  \Drupal\Core\Entity\EntityTypeRepository::class,
'entity_type.bundle.info' =>  \Drupal\Core\Entity\EntityTypeBundleInfo::class,
'entity.repository' =>  \Drupal\Core\Entity\EntityRepository::class,
// ...

Answer: Since Drupal 8 used Symfony so you can run command php vendor/bin/drupal debug:container and this is equivalent in Symfony php bin/console debug:container
Comment: This isn't necessarily true. I would modify the post to add that drupal-console is required.

Get the list of available services


No qualifying bean of type [org.springframework.social.twitter.api.Twitter] found for dependency

Question: In my Spring Boot application I'm trying to implement Twitter oAuth support.
Following this example http://spring.io/guides/gs/accessing-twitter/ I have successfully added Twitter access to my application, so now I have:
HomeController:
@Controller
@RequestMapping("/")
public class HelloController {

    private Twitter twitter;

    private ConnectionRepository connectionRepository;

    @Inject
    public HelloController(Twitter twitter, ConnectionRepository connectionRepository) {
        this.twitter = twitter;
        this.connectionRepository = connectionRepository;
    }

    @RequestMapping(method=RequestMethod.GET)
    public String helloTwitter(Model model) {
        if (connectionRepository.findPrimaryConnection(Twitter.class) == null) {
            return "redirect:/connect/twitter";
        }

        TwitterProfile userProfile = twitter.userOperations().getUserProfile();

        model.addAttribute(userProfile);
        CursoredList<TwitterProfile> friends = twitter.friendOperations().getFriends();
        model.addAttribute("friends", friends);
        return "hello";
    }

}

Application class:
@PropertySources({ @PropertySource(value = "classpath:application.properties") })
@ComponentScan("com.example")
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

So far everything works fine. I can start Application without any issues.
Also, I have a lot of integration tests, for example:
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@SpringApplicationConfiguration(classes = Application.class)
@IntegrationTest("server.port: 0")
public class SearchControllerTest {

    @Value("${local.server.port}")
    protected int port;

    @Test
    public void testSearchResultsWithDefaultPageAndSize() {
        // @formatter:off
        given()
            .when()
                .get(format("http://localhost:%d/api/v1.0/search/%s", port, "RDBMa mosyl"))
            .then()
                .statusCode(200)
                .contentType(ContentType.JSON)
                .body("totalCount", equalTo(4))
                .body("entries.size", equalTo(4));
        // @formatter:on
    }
....
}

Now, after adding of Twitter social functionality, all my tests failed with following exception:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.social.twitter.api.Twitter] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1301)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:813)
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
    ... 43 common frames omitted

Why does this work with Application and fails with tests ? What is wrong with my tests configuration ?
Comment: Also, do you have a `src/main/resources/application.properties` or `config/application.properties`, which defines `spring.social.twitter.appId` and `spring.social.twitter.appSecret`?
Comment: I would recommend starting by removing `@PropertySources` and `@ComponentScan` from your application class. It's annotated as `@SpringBootApplication`, so those just confuse things.
Comment: Yeah.. this is a reason ! I got it after your first comment about application.properties.. I forgot to add spring.social.twitter.* properties to my src/TEST/resources/application.properties . Thank you so much !
Comment: I was getting the same exception, but in my case it was because I didn't include the @WebAppConfiguration annotation. It seems that Spring boot does not instantiate Spring Social classes in the absence of a WebApplicationContext, which I don't get as someone could be interested in cosuming twitter from a command line app and still don't want to manually configure a TwitterTemplate...
Answer: The reason is you don't have a src/main/resources/application.properties or config/application.properties, which defines spring.social.twitter.appId and spring.social.twitter.appSecret.


How to replicate a plot of means for a 2 by 3 by 4 design in R?

Question: I have a graph that I did in SPSS

I would like to replicate this in R.
The data file is here: http://dl.dropbox.com/u/22681355/sendergraphR.csv
UPDATE:
I've figured out how to to it for the other graph:
graph2<-read.csv(file="SendergraphR.csv")
ddr <- recast(graph2,no.GREEN+no.RED+Senderidentity~variable,
    fun.aggregate=mean,id.var=c("no.GREEN","no.RED","Senderidentity"))

qplot(x=no.GREEN,y=Mean_Message,data=ddr,colour=Senderidentity,
    group=Senderidentity,geom="line")+facet_wrap(~no.RED,ncol=1)

Now what I would like to do is to separate this second graph into two columns one looking at the cases where the variable urn1 is blue and the other where its red: here's a graph of how it should look:

I was thinking of doing it the following way:
ddr <- recast(graph2,no.GREEN+no.RED+Senderidentity+urn1~variable,
    fun.aggregate=mean,id.var=c("no.GREEN","no.RED","Senderidentity", "urn1"))
qplot(x=no.GREEN,y=Mean_Message,data=ddr,colour=Senderidentity, group=Senderidentity,geom="line")+facet_wrap(~no.RED,ncol=1) +
    facet_wrap(~urn1, ncol=2)

But this doesn't seem to work. What am I doing wrong?
Comment: There are two problems here. One to calculate the mean probabilities and means, another to plot the results. First problem requires some model, which you do not specify. So it is hard to help you, since we need to guess the model. The second should be easy to do, using ggplot2. Please supply the response variables of your models, then it would be possible to recreate these graphs.
Comment: I would suggest to keep this question here as it already got valiant follow-up and an accepted answer (not that I don't want to close or migrate the 4th Rish post of the day).
Comment: @Daniel, please revert this to the previous question, and ask the new question separately, linking to this one. Also please see the FAQ and properly format the code, now it has an error in it. The answer to your second question is very simple, but you must figure it out by yourself. This site is for learning, not for getting your job done by somebody else. If somebody does not show inclination to learn (as you do), there is no incentive to help.
Comment: @mpiktas on the graph Mean probability of guessing RED is just a bad way of looking at the variable DecisionasReceiver. Basically we're interested in how many chose 1 under different conditions. Similarly on the second graph Mean message just means how many people chose 1 in the DecisionasSender variable. Both datasets contain all the information. Here's how I did it SPSS: http://dl.dropbox.com/u/22681355/graphforreceiver.tiff

http://dl.dropbox.com/u/22681355/sender-graph.tiff These should give you an idea of how its set up. The dataset is the same. THanks!
Comment: at this point this seems not to be a statistics question--- migrate to SO R tag?
Comment: @john, yep this should be migrated. Voting to close.
Answer: This is more or less standard ggplot2 problem. So I will only give an idea how to reproduce this graph. First get the data
dd<-structure(list(no.GREEN=c(1L,1L,2L,2L,3L,3L,4L,4L,1L,1L,2L,2L,3L,3L,4L,4L,1L,1L,2L,2L,3L,3L,4L,4L,1L,1L,2L,2L,3L,3L,4L,4L,1L,1L,2L,2L,3L,3L,4L,4L,1L,1L,2L,2L,3L,3L,4L,4L,1L,1L,2L,2L,3L,3L,4L,4L,1L,1L,2L,2L,3L,3L,4L,4L,1L,1L,2L,2L,3L,3L,4L,4L,1L,1L,2L,2L,3L,3L,4L,4L,1L,1L,2L,2L,3L,3L,4L,4L,1L,1L,2L,2L,3L,3L,4L,4L,1L,1L,2L,2L,3L,3L,4L,4L,1L,1L,2L,2L,3L,3L,4L,4L,1L,1L,2L,2L,3L,3L,4L,4L,1L,1L,2L,2L,3L,3L,4L,4L,1L,1L,2L,2L,3L,3L,4L,4L,1L,1L,2L,2L,3L,3L,4L,4L,1L,1L,2L,2L,3L,3L,4L,4L,1L,1L,2L,2L,3L,3L,4L,4L,1L,1L,2L,2L,3L,3L,4L,4L,1L,1L,2L,2L,3L,3L,4L,4L,1L,1L,2L,2L,3L,3L,4L,4L,1L,1L,2L,2L,3L,3L,4L,4L,1L,1L,2L,2L,3L,3L,4L,4L,1L,1L,2L,2L,3L,3L,4L,4L,1L,1L,2L,2L,3L,3L,4L,4L,1L,1L,2L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1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L,1L)),.Names=c("no.GREEN","no.RED","Messagereceived","Decisionasreceivercode","OptimalResponse"),class="data.frame",row.names=c(NA,-328L))

Then transform it to get the desired statistics:
ddr<-recast(dd,no.GREEN+no.RED+Messagereceived~variable,fun.aggregate=mean,id.var=c("no.GREEN","no.RED","Messagereceived"))

And finaly plot it:
qplot(x=no.GREEN,y=Decisionasreceivercode,data=ddr,colour=no.RED,group=no.RED,geom="line")+facet_wrap(~Messagereceived,ncol=1)

The result will be the following:

I will leave the second graph and the cleaning up of the first one as an exercise :)
Update: There is alternative cleaner way to get the aggregation:
ddr<-aggregate(dd$Decision,by=as.list(dd[,1:3]),mean)

We lose the name of the variable this way, but save some time with not typing three names two times.
Comment: What? You're not doing _all_ his work for him? +1 for that (well, that and the excellent answer)!
Comment: @mpiktas thank you very much! there definitely remains quite a few things to clean up, but this is an excellent lead. My only remaining question is how I can add an additional line with the Optimal variable plotted. thanks again
Comment: @mpiktas I'm trying to reproduce the graph to have only 1,2,3,4 in the bottom. I've added xlim(1,4) but it won't change it, what am I missing?
Comment: @Daniel, I suggest to  read  ggplot2 book. `xlim` only sets the limits, they are fine here. What you want is to change the type of variable. `qplot` assumes that `no.GREEN` is numeric, hence it produces numeric axis. Try changing it to factor and then inspect the results.
Comment: @mpiktas I do want to read the ggplot2 book in the future, but currently I do not have it. I could only download the chapter relating to qplot but it didn't really detail what I should do. I've tried changing it to numeric by adding .class="numeric"but an error always comes up like Error: unexpected ',' in "L,"
Comment: @mpiktas I managed to replicate the other graph which is great, now the only problem remaining is how to get change them to numeric and how to add the optimal lines on top of these. I would really appreciate your help as it's quite urgent
Comment: You want `no.GREEN` as a factor, not a numeric.  `ddr$no.GREEN <- factor(ddr$no.GREEN)`.
Comment: @Aaron thanks so much for your help! this is what happened:http://dl.dropbox.com/u/22681355/RPlot.pdf
Comment: I suspect you're not using the aggregated data.  If it's something else, you'll need a ggplot expert to help you there, sorry.
Comment: @Aaron it works pretty well now thanks! but I still don't know how to fit the extra line. can someone help? also what am I doing wrong with this? colors<-c("#000000","#F8766D","#7CAE00")
> d+scale_fill_manual(values=colors)
Comment: Treat the extra line just like another no.Red; you'll have to reshape your data using `cast` and `melt`.  There are plenty of questions here (and on SO) that you should be able to fine.
Comment: @Aaron see my updated question.
Comment: One question per question, please.  Better to revert this one to how it was and start a new one, linking back to this one.  If you do, stackoverflow.com is probably a better place for questions specifically about R.
Answer: You could also use the lattice library:
A simple version (not shown):
library(lattice)
xyplot(Decisionasreceivercode ~ factor(no.GREEN) | Messagereceived,
       group=no.RED, type="a", data=dd)

Or with better labeling:
names(dd)[3] <- 'Message Received'
xyplot(Decisionasreceivercode ~ factor(no.GREEN) | `Message Received`,
       group=no.RED, type="a", xlab="No. Green",
       ylab="Decision as Receiver Code",
       strip=strip.custom(strip.names=TRUE),
       data=dd,
       auto.key=list(space="right", title="No. Red", cex.title=1))

Comment: See `import.csv` to import your file into R.  The L means only that it's an integer; `import.csv` will automatically decide how best to store it (the defaults can be changed if you like). mpitkas used `dput` to output the data in a way that could easily be used by others, but that's usually something you would do only to help others recreate your code.
Comment: thanks! can you or someone else tell me how to code the data in the form shown above? how do I get the 1L, 1L, 0L, etc ?
Comment: @Aaron, you probably meant `read.csv`? Quick search on rseek.org did not return any hits for `import.csv`.
Comment: Yes, `read.csv`.  Thanks for the fix -- perhaps I was thinking about PROC IMPORT and got mixed up.


Excluir Diretório via Git Bash - Erro: Device or resource busy

Question: Estou tentando excluir um diretório via Git Bash, porém, está dando o erro "Device or resource busy", conforme print abaixo. Não localizei qualquer aplicativo que esteja ocupando este Diretório. Existe algum comando para que eu possa "forçar" a remoção do mesmo?
Comment: Use `rm -rf `
Answer: Para forçar a remoção de um diretório/pasta use:
rm --recursive -f [diretório]

Onde:

f: força a remoção
recusive: irá buscar os arquivos abaixo do diretório passado como parâmetro

Para saber mais sobre o comando:
rm --help


How should I format my cell to have a bulleted list of items

Question: How should I format my cell to have a bulleted list of items. Currently I create the bulleted text in word and paste it in the excel cell, but when I try to add a new item using the enter button it takes me to the next cell but doesn't add a new bullet item. How should I do this?
Answer: Mike Alexander had a post about this last year. His method uses custom "number" formatting on the cells.

Paste in your bullet (he chooses one by using Insert->Symbol)
copy the symbol to the clipboard
format the range/column needing the bullets and use bullet + Space + <code>@</code> as the formatter.

Note that this only works on items in individual cells (it will only put a single bullet at the beginning of the cell.) If you need to add bullets into a single cell, Use Alt+Enter to add a new line character, and copy 'n' paste your bullet character.
Comment: Would be nice to use conditional formatting and only apply the bullet format when some condition on other cell(s) in row is TRUE. Probably can be done -- I just have to go play with Excel conditional formatting again.
Answer: One way would be to dedicate a column for the bullets, say column A for the bullet and column B for the data, and make the bullet appear conditionally on available data in B. e.g. for cell A1 I would use something like:
<code>=IF(ISBLANK(B1),"","●")
</code>
You can then make column A narrow so it will fit in width to the bullet. Also you can copy this formula to a far off row so that any time you write in column B, you'll already have this formula ready in the cell next to it in column A.
Also, if you want to change the bullet's style - go to any empty cell, click on Inset\Symbol, choose your bullet, then you can copy paste it into the equation above.
Answer: Shortcuts:

To quickly add a bullet symbol to a cell, double click in the cell where you want to add your bullet symbol, and then press ALT+7 or ALT+9 using the numeric keypad on your keyboard.
Ref: Insert bullets in a worksheet
Comment: the link has been dead. [Here's an updated link for newer office versions](https://support.office.com/en-us/article/insert-bullets-in-a-worksheet-60274daa-8079-4b40-8f69-0652dbadb4ec)


I am trying to make a search programm but don`t know how to print the username with the fullname

Question: import datetime

tday = datetime.date.today()
username =input('input something:')

class person:
    def __init__(self, first, last, ip, birtyear, birthmonth, birthday):
        self.first = first
        self.last = last
        self.ip = ip
        self.birthyear = birtyear
        self.birthmonth = birthmonth
        self.birthday = birthday
    def fullname(self):
        return '{} {}'.format(self.first, self.last)
    def yearage(self):
          return '{}'.format(tday.year - self.birthyear)
    def monthage(self):
          return '{}'.format(tday.month - self.birthmonth)
    def dayage(self):
          return '{}'.format(tday.day - self.birthday)
    def birth(self):
        b1 = self.birthmonth, self.birthday,
        b2 = self.birthyear
        return'{} {}'.format(b1, b2)
    def ip1(self):
        return'{}'.format(self.ip)

names = ['x1', 'x2']

x1 = person('x1', 'y1', 50000, 2002, 2, 22)
x2 = person('x2', 'y2', 60000, 2004, 4, 24)

flag = 0
for i in names:
    if (i==username):
        print ((username).fullname())
        flag=1
        break

if (flag == 0):
    print("element not found")

Comment: Try `print(f'{username} - {fullname()}')` See [Formatted string literals](https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498).
Answer: You need to add your persons to a list so you can search through it.  Just because you have a variable called x1 does not mean you can use (username).fullname() to refer to that variable.  Python doesn't work that way.
names = [
    person('x1', 'y1', 50000, 2002, 2, 22)
    person('x2', 'y2', 60000, 2004, 4, 24)
]

flag = 0
for user in names:
    if user.first == username:
        print( user.first, user.fullname())
        flag=1
        break

if flag == 0:
    print("element not found")

Comment: I have no idea what you're asking. You should post a new question with your current code.
Comment: Is it also possible if there are more then 1 'x1' to count them?
Answer: The username is just the string the user gave as an input.
It therefore doesn't have the function fullname() you implemented for the person class.
I don't know what you are aiming for, you can either print the hardcoded "x1 y2" in the end or just reply what the user typed in.


Total no. of balanced parenthesis with maximum nesting of $d$

Question: $C_n$(the $n^{th}$ catalan number) counts the number of expressions containing $n$ pairs of parenthesis which are correctly matched
How to count the possibilities if the maximum nesting level is fixed to $d$?
Answer: The answer is described in several equivalent ways in this blog post.  For fixed $d$ the corresponding sequence $C_{d,n}$ satisfies a linear recurrence, and its generating function is "the $d^{th}$ convergent" of a continued fraction representation of the generating function of the Catalan numbers.  Explicitly,
$$C_{d,n} = \frac{1}{d+1} \sum_{i=1}^d 2 \sin^2 \frac{\pi}{d+1} \left( 2 \cos \frac{\pi i}{d+1} \right)^{2n}.$$
(The indexing may be off by one.)


locationManager.location is always nil

Question: I have essentially lifted this code from the internet:
//variables
//location manager
var locationManager:CLLocationManager!
var currentLocation:CLLocation?

//outlets
@IBOutlet weak var whatTextField: UITextField!
@IBOutlet weak var whereTextField: UITextField!
@IBOutlet weak var whenTextField: UITextField!

@IBAction func onCreateEventClick(_ sender: Any) {

    let event = CAEvent(eventId: "123777abc", eventName: whatTextField.text, location: currentLocation)
    event.save { (error) in
        //handle event error
        print(error)
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    if( CLLocationManager.authorizationStatus() == .authorizedWhenInUse ||
        CLLocationManager.authorizationStatus() ==  .authorizedAlways){
        determineCurrentLocation()
    }
}

func determineCurrentLocation() {
    locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestWhenInUseAuthorization()

    if CLLocationManager.locationServicesEnabled() {
        locationManager.startUpdatingLocation()
        //locationManager.startUpdatingHeading()
    }
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    currentLocation = locations[0] as CLLocation

    // Call stopUpdatingLocation() to stop listening for location updates,
    // other wise this function will be called every time when user location changes.
    // manager.stopUpdatingLocation()

    print("user latitude = \(currentLocation?.coordinate.latitude)")
    print("user longitude = \(currentLocation?.coordinate.longitude)")
}

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error)
{
    print("Error \(error)")
}

And at first I was able to see the location (e.g., not nil.). Now however, it is nil every single time. I have tried changing my simulator's location, and I have confirmed that the app in my simulator is sharing location. I also have added a call to startUpdatingLocation() and added the delegate didUpdateLocations and noticed that didUpdateLocationsAny is not called. Any other ideas? Thanks!
Answer: Do you call locationManager's method startUpdatingLocation()? The best place to start updating location is locationManager's delegate method:
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    switch(CLLocationManager.authorizationStatus()) {
    case .authorizedAlways, .authorizedWhenInUse:
        locationManager.startUpdatingLocation()
    case .denied, .notDetermined, .restricted:
        locationManager.stopUpdatingLocation()
    }
}

Comment: How do you understand that the authorization is not allowed if your location manager is not initialized?

Anyway Apple provides very clear documentation: https://developer.apple.com/documentation/corelocation/getting_the_user_s_location/using_the_standard_location_service. I usually follow these steps and everything works good.
Comment: If you still have problems with location service, I can share my code that works.
Comment: I also don't understand this error. If I start updating the location when the authorization changes, I would have to first setup the location manager. Why would I set up the locationManager if the authorization is not allowed?
Comment: And one more thought: the 'didChangeAuthorizationStatus' method appears to be continuously called a loop. Shouldn't it only be called when the authorization is changed?
Answer: The location is usually not available immediately after it being requested, once you set your object as the delegate, you should implement func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) and set currentLocation to the last element of that array.
That method will be called whenever the location is acquired or changes.

locationManager.location is always nil


Parse From Text File into String output

Question: So I have a text file called employees.txt that looks like this...
Billy Madderson, M, 34
Allison McGever, F, 32
Bill Nye, M, 35

I'm trying to write a sed script that will read in the text file then output it in the format
"< name > is a < gender >, and is < age > years old now."
I know I need to set the IFS=, but I'm stuck on how to place the information in the string. Any input is greatly appreciated!
Answer:
I know I need to set the IFS=

I don't see why this would be necessary. As far as I know sed doesn't use IFS at all.
Replace the first , with is a, M/F by man/woman, the second , with and is and so on. The only tricky part is to only replace the M/F in the second column instead of the first M/F you come across. Luckily, after the second column there are no letters anymore, so that simplifies things.
sed 's/, M/ is a man/;s/, F/ is a woman/;s/, /, and is /;s/$/ years old now./' file

For your example the output is
Billy Madderson is a man, and is 34 years old now.
Allison McGever is a woman, and is 32 years old now.
Bill Nye is a man, and is 35 years old now.

Comment: What would happen if instead of 'M/F' for gender it became numbers? Like years with the company? So you had 13.5, 10.2, 11.8 added? How would that change because I'm assuming you can't search and use $ for both the age and years now? Sorry I'm just trying to figure sed out because I didn't think $ work for more than one case.
Comment: `$` is just the end of the line. I used it to *append* text to each line. If you add columns in the middle, that changes nothing on the `$` part. If you add columns at the end, you would have to insert `years old now` in another way, e.g. by replacing a `,`.

Parse From Text File into String output


Como fazer uma IF ler dois tipos de categoria ao mesmo tempo?

Question: Boa noite, bem, desejo saber como posso colocar: if ($this->GetCategoryName() == 'mmorpg' OR 'shots') na mesma linha de código, sem precisar fazer isso:
if ($this->GetCategoryName() == 'mmorpg') {
    if ($this->GetCategoryName() == 'shots') {
        $url = $c_url;
    } else {
        $url = $c_url;
    }
} else {
    $url = U_LANG.'/'.$url_cat;
}

Comment: `if ($this->GetCategoryName() == 'mmorpg' && $this->GetCategoryName() == 'shots') {`
Comment: kkk eae man :D, se tem conta Discord? Sou novo em PHP, ai se poderia ser meu professor rs, ajeitei já o if, era só por o `OR` assim: `or` ai funcionou: `$this->GetCategoryName() == 'mmorpg' or 'shots'`
Answer: Assim:
if ($this->GetCategoryName() == 'mmorpg' && $this->GetCategoryName() == 'shots') {

Mas tem um erro de lógica, se é uma coisa não é outra.
Em PHP você pode usar

&& para AND
|| para OR, será que não é isso que busca?

Mas talvez te interesse mais fazer assim:
$cat = $this->GetCategoryName();
$url = ($cat == 'mmorpg' || $cat == 'shots') ? 'url1' : 'url2';

Ou seja "se a categoria for mmorpg OU categoria for shots, é url1, senão url2"

Note que PHP tem and e or também, mas muda a precedência, veja aqui:

Qual a diferença entre "&&" e "||" e "and" e "or" em PHP? Qual usar?
Comment: Sim, esse 2º método ficou melhor: `$url = ($this->GetCategoryName() == 'mmorpg' || $this->GetCategoryName() == 'shots') ? $c_url : U_LANG.'/'.$url_cat;` obrigado rs
Comment: `Note que PHP tem and e or também, mas muda a precedência.` Sim, realmente.


Search Api Solr - Pointing term links inside a view to its facet

Question: Using Search Api. Solr as a backened. Search pages built with Views. When adding a term field to a view, that term links to the core taxonomy term pages. That term should instead link to it's facet(not adding to the other facets if the user had previously click on other facets).
I have searched high and wide for any documentation or discussion involving this, and only found a few issues that didn't go anywhere. There is hardly any discussion, which I find odd because I would imagine this would be a pretty common request.
Does anyone have any knowledge on this issue?
Answer: Why would you want the fields in the search results to have taxonomy terms that are linked to the facet URL instead of the taxonomy page of the item? It just seems a little redundant, because that's what the facets there are for.
A solution would be to use FacetAPI Pretty Paths and rewrite the output link of the taxonomy term to match the URL of the facet. You'll need the fields term name and id, then format as : www.example.com/search-page/[pretty paths term]/[term name]-[term id]
Comment: Say a user searches for something, then filters by Network, then by tv show.  The view row displays the main stars that are on the show(which are terms).  The user looks at the view results and sees the name of his favorite actor, and says, "I want to see everything that he is in." He clicks on it, and now the view reset all the filters and shows results of everything that actor is in, as if the user just clicked on that actors filter facet.  I have already tried the solution with pretty paths, and once you do that, your facet links point to term pages.  It doesnt work
Comment: For this, you need to use the base URL as the search page, then that activates the facet based on the URL. For example, if the URL of your search page is www.example.com/search, you need to rewrite the taxonomy link to be search/[pretty paths term]/[term name]-[term id], then it will activate just that facet.


How to make a phonegap build app work in background

Question: I need my app to work 24/7 recording the users location every 5 mins.  It works fine while the phone is active but when it isn't the setInterval()'s strecth out to be up to 5x longer than they should.
Using phonegap build, how would I go about making the app work as it should in the background while the phone is idle?
Comment: Both Android and iOS severely limit what apps are allowed to do when running in the background. If apps don't have a good reason to still be doing things in the background, they are typically terminated or given very low priority. Also, good lord; why do you need to track your users so closely?? I am alarmed.
Comment: Only way use native code. In Android, when app is background then js code not execute. In IOS then js code can call from native code to js via javascript interface. I think you should focus build background service from native
Comment: It is an automated timesheet for farmers.  if they are not at home + within the farm it records them as working.
Answer: @Marty,
both Android and iOS and run in the background, but require an extension to the regular config.xml.
To be clear Android apps uses AndriodManifest.xml.
iOS uses, preferences.plist
Both have the ability to go into background. However, in Cordova/Phonegap this is not available directly, you must make an extension. The best explaination are from Cordova and Phonegap Build.
From Phonegap Build:
Start with: Config File Elements. You will need to add <gap:config-file> one for each, then you will also need to add to the first xml element, like this:
 <widget xmlns = "http://www.w3.org/ns/widgets"
        xmlns:android   = "http://schemas.android.com/apk/res/android"
        xmlns:gap   = "http://phonegap.com/ns/1.0"
        id          = "com.bsdmasterindex.googlemapexamples"
        version     = "1.0.0"
        versionCode = "10" >

The most important item being xmlns:android   = "http://schemas.android.com/apk/res/android". This is only for android, of course.
Examples of using this are in my Demo Boiler plates for Phonegap Build - source available at git hub.
Three (3) Phonegap Build Boilerplates for For Android and iO
You will want to look at Boilerplate #2.
This article will help.
7 things you should know about Android Manifest xml file
If you have further question, I suggest you go to google groups. I will soon be dropping Stackoverflow from my readying list. I willl likely drop on Monday.
Jesse
Comment: Thanks for that, but I don't get how I connect my js function from the manifest? can't find anything about that on any of the links
Comment: @Marty.H, There is no Javascript you do. You simply add the appropriate lines in your config.xml and the app is supposed to be able to run in the background. Read the docs (Android & iOS), they work differently, but they both do what you want - run your app in the background. In other words, you are telling both OSs, "please run my app in the background, and not the normal process".
Comment: I have been reading here: http://developer.android.com/guide/topics/manifest/service-element.html and it says I need to add the name of my service to the manifest, but I don't actually have a service to name, how do I get around that?
Comment: Okay. I can see you have not done any Android programming on that level. `config.xml` is a declarative structure, so is  `AndroidManifest.xml`.  With this task, you are "extending" config.xml. In fact, config.xml will become AndroidManifest.xml - in the end. I need to find my examples, I'll get back to this in a few hours.
Comment: Okay: instead, here is your Google lookup: [androidmanifest.xml declare background service](https://www.google.com/search?q=androidmanifest.xml+declare+background+service) If this is not enough, let me know.
Comment: I have not done any android programming what so ever.  by the looks of the articles you pointed me to that is something i'm going to have to learn right?
Comment: Of course, yes, you have to READ this. What did you expect? Background operations is NOT normal programming for phonegap. It is an exception. This is often know as the *one-off* rule.
Comment: Sorry, I misinterpreted your comment where you said "You simply add the appropriate lines in your config.xml and the app is supposed to be able to run in the background.". I had figured this was the case before that comment.  Didn't realize it was so rare.
Comment: @Marty .H, Android is fairly well designed, better than most mobile OS. However, it has to use a truely crappy language known as Java.


Terminated due to Memory Pressure with less then 15MB used

Question: I'm facing a strange problem, the app I'm working on it's constantly killed due to Memory Pressure but it's not really using much as you can see in the screenshoot.
So I'm started to look for "other" issues like memory leaks, implicit casting, but I don't really know how to debug this kind of things, so... does anyone know how to get out of this problem ? :)
Comment: http://stackoverflow.com/questions/19061243/how-can-i-address-an-app-that-started-earlier-but-is-terminated-due-to-memory
Comment: @iDev it's a different problem, here the memory usage it's little, but thanks :)
Comment: which operation you making through caught this exception
Comment: it's a video editing application, I'm using GPUImage. The crash happen after repeating the saving operation few times (the whole video re-processed and color filters are applied)
Comment: In iOS7 (not 6!) my app is being terminated while the user uses Apple's Camera app. My app is not over using memory and using the Camera inside my app is ok. There is no memory warning delivered to my app.
Answer: Typically termination due to memory pressure occurs when the app is suspended by the iOS itself. It happens when your device doesn't have a lot of free memory and it is often a good sign (meaning that this will happen to your app sooner or later when the user closes it).
I would offer you to use Instruments and to find where exactly does your app terminate (if this is the case). The good Instruments tutorial can be found here - http://www.raywenderlich.com/23037/how-to-use-instruments-in-xcode
Comment: I started to handle the memory before arc and I was damn good at it, my app wasn't leaking almost at all... now with arc I feel powerless... by the way, my app is using 10mb...
Comment: @Cesar As you've accepted this answer, can you provide some details on exactly how it helped - i.e. what was the actual solution to your problem?
Comment: @Cesar ARC isn't that dumb at all, it's a fine system but you have to remember a few things when working with CoreGraphics and othe _non-Obj-C_ objects. 10 to 15 MB is absolutely fine. I once had an app that was using up to 150 MB of memory and was running perfectly fine. Try debugging it with Instruments.
Comment: so far I love ARC, but I feel like I have little control :)
I'm using GPUImage framework that use both OpenGL, CoreGraphics and AVFoundation.
Answer: Memory allocated for the GPU (e.g. with glGenFramebuffers) will not show up in any memory instrumentation I can find, but using too much of this memory will count against you for memory pressure.
In my case, I was leaking by having a code path that missed glDeleteFramebuffers.


Bayesian Statistics Theorem

Question: Suppose a voter poll for a presidential election is taken in three states. In state A, we find that
55% of voters support the Republican candidate. In state B, we finnd that 60% of voters support the
Republican candidate. In state C, we find that 45% of voters support the Republican candidate. Of
the total population of the three states combined, 50% live in state A, 30% live in state B, and 20%
live in state C. Given that a voter supports the Republican candidate, what is the probability that the
voter lives in state A?
Comment: Please add the `self-study` tag and read its [tag wiki](http://stats.stackexchange.com/tags/self-study/info), modifying your question as necessary.
Answer: Recall Bayes Theorem $ P(A|R) =\frac{P(R|A)P(A)}{P(R)} $
and the total probability rule $ P(R) =\sum_{i=1}^{n}P(R|X_i)P(X_i) $.
Is there any way to use the total probability rule to fill in the unknown values in Bayes Theorem?
Comment: Sorry about that @Glen_b, does the edit help?

Bayesian Statistics Theorem


How to select all elements with CSS?

Question: I have this html code:

        <link rel="stylesheet" href=".\bulma\css\bulma.min.css">
        <link rel="stylesheet" href="style.css">

Large section

    A simple container to divide your page into sections, like the one you're currently reading.

and this css code:
@font-face {
    src: url(fonts/Lato-Regular.ttf);
    font-family: lato;
 }
 .paragraph {
    font-family: lato;
 }

 @font-face {
    src: url(fonts/AthleticOutfit.ttf);
    font-family: athletic;
 }
 .title {
    font-family: athletic;
    font-size: 100px;
 }

* {
   color: white;
 }

The fonts are actually working, meaning that my css file is found. However, my * { color: white; }  does not work. I cannot figure why... I think this might have something to do with bulma, which works too.
Any idea of how to make this * {} thing work? I expect all my text to be in white color, but it actually shows as grey...
Comment: Try adding `!important` , like `color: white !important`.
Comment: Find out who/where is setting the different color by using your browser's devtools inspect facility. Look at any element that has the wrong color and you will see all the places that tried to set it. (and try to avoid using !important if possible).
Answer: Option 1:
color: white !important
Option 2: add a class "something" to your  then you can utilize precedance.
body.something * {
    color: white !important;
}

Answer: The code works just fine. I tested it myself a couple of times and it works perfectly. Try checking for typos, maybe add a <!DOCTYPE> at the beginning just in case, make sure that nothing in the other style sheet contradicts, or if nothing works, try adding the !important tag after the style for coloring it white, like "color: white !important".
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

How to select all elements with CSS?


Why is dropout causing my network to overfit so badly?

Question: I've been experimenting with various simple neural networks to test their performance. When I use the following architecture, I'm getting some very bad test error, which looks like overfitting.
$$\text{My architecture}: \mathbb{R}^n \ni \texttt{Input}\xrightarrow{\text{affine}} \mathbb{R}^m \xrightarrow{\text{dropout}} \mathbb{R}^m \xrightarrow{\text{Max(0, x) (ReLU)}} \mathbb{R}^m \xrightarrow{\text{affine}} \texttt{Output} \in \mathbb{R}$$

This seems to persist over various values of $n$ and $m$, and over various rates of dropout. (Although with lower probabilities of keeping nodes, it seems to be worse. So the more likely dropout is to happen, the more this seems to occur. The above picture is for dropout probability $.8$ during training.)
I'm planning on doing some more experiments to investigate just what is happening and how it's overfitting. But before I do, I want to make sure I'm not making some stupid mistake in my implementation.
Question: Is there some obvious mistake in my implementation that's making this network perform so poorly?
The guts of my network look like this:
def dropout_network(self, weights, biases, x, noise_on):
    current_dropout_rate = tf.cond(
                    noise_on,
                    lambda: np.float32(1),
                    lambda: self.dropout_rate
                )
    fc1 = tf.add(tf.matmul(x, weights['wl1']) , biases['bl1'])
    fc1 = tf.nn.dropout(fc1, keep_prob=current_dropout_rate)
    fc1 = tf.nn.relu(fc1)
    out = tf.add(tf.matmul(fc1, weights['wl2']) , biases['bl2'])
    return out

The current_dropout_rate business is to allow me to stop the dropout at test time, by feeding in noise_on: False.
One thing that makes me suspicious is that if I replace the dropout layer with other things like batch normalization, or just the identity, nothing like this happens. That's not necessarily suspicious, since of course dropout is very different from these, and I'm using dropout in a very simplified setting. But dropout sure is performing badly.
For reference, the function my network is trying to fit is a randomly selected cubic function $\mathbb{R}^{10} \to \mathbb{R}$. My test data and training data are drawn from a standard normal distribution. Training data is $5000 \times 10$, and test is $1250 \times 10$.
Comment: don't you have the condition inverted?
Comment: @shimao Yes! Glad I asked this question.
Comment: @shimao Any idea why this would cause the network to perform *so* poorly? Just turning on dropout during testing caused it to perform ten times worse!
Answer: I had transposed the conditions on the tf.cond.