Cache rebuild causes an error with missing plugin

Question: On rebuilding the cache, a Drupal 8 website goes down and displays the message "The website encountered an unexpected error. Please try again later." I used drush cr to rebuild the cache, which shows the following error message.

The "field_item:boolean" plugin does not exist.

I also tried to rebuild the cache right after installing a new Drupal 8 site without any additional module, and it shows the same error.
How can I get the site back to working?
Comment: @GiorgosK drush entity-update is not helping. But after clearing cache_discovery table via phpmyadmin site is up and running
Comment: If you can't access the dblog of drupal then see your apache logs and post here what you find
Comment: When the plugin discovery fails in downloaded code, then this is most times a download error, so the first thing you should try is to remove the code base and download it again.
Comment: @4k4 It is not a download error. This happens on every drupal 8 project.
Comment: @GiorgosK Drupal\Component\Plugin\Exception\PluginNotFoundException: The "field_item:boolean" plugin does not exist. in Drupal\Core\Plugin\DefaultPluginManager->doGetDefinition() (line 52 of /var/www/html/drupal_8/web/core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php).  is the error I get
Comment: @Nabil what php version do you have `php -v` ? try running `drush entity-update` see if it helps.  If you have contrib modules disable them.  What exact version of drupal do you have ?
Comment: @GiorgosK php version is 7.1.9 , drupal 8.4.4
Answer: This morning I had similar problem and drush cr was actually not clearing the discovery cache but after
drush sql-query 'TRUNCATE TABLE cache_discovery;'

I was able to get rid of this error


phpMyAdmin Password

Question: I have a MYSQL database through yahoo hosting and am unable to login with my username and password.  don't know if it's been changed or what. I wanted to know if there was a way to maybe configure the phpMyAdmin config files for a fixed user, so I can go in and set a new password. Let me know if this is possible or any other way that doesn't involve a shell because yahoo doesn't offer that. I need a way to get into my database.
Thanks
Comment: Kind of a question better suited for server fault.  This has nothing to do with programming.
Answer: If you don't have shell or ftp access to the mysql servers my.cnf file (I doupt it) there is no way to recover/fix your password. You can possibly contact yahoo support, but I doubt there is much they could do either.
Or try this.
http://help.yahoo.com/l/us/yahoo/smallbusiness/webhosting/mysql/mysql-16.html

phpMyAdmin Password


Instanciar o objeto de um Map apenas quando necessário baseado em um regex

Question: Eu tenho uma Factory que instancia o PARSER responsavel para extrair as informações de um determinado formato de fatura. Para determinar o formato da fatura eu uso regex. Eu dou um loop em cada regex adicionado ao Map e verifico se o regex é encontrado dentro do texto dessa fatura, se for encontrado, então instancia o PARSER responsavel pela extração dos dados dessa fatura.
Pra isso, eu criei um Map de Class e String, onde String é o regex. Foi necessário utilizar Class pois não posso instanciar esse PARSER antes de saber se realmente é ele mesmo que vai ser o PARSER responsavel pois existem algumas lógicas no construtor de cada PARSER.
public class InvoiceParserFactory
{
    private static final Logger logger = LoggerFactory.getLogger(InvoiceParserFactory.class);

    private static Map<Class<? extends InvoiceParser>, String> map = new HashMap<>();

    static {
        map.put(xxx_PARSER.class, "regex_xxx");
        map.put(yyy_PARSER.class, "regex_yyy");
        map.put(zzz_PARSER.class, "regex_zzz");
        //...
    }

    public static InvoiceParser getParser(InvoicePdfReader reader)
    {
        String invoiceText = reader.getText();

        for (Map.Entry<Class<? extends InvoiceParser>, String> entry : map.entrySet()) {
            Class<?> clazz = entry.getKey();
            String regex = entry.getValue();

            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(invoiceText);

            if (m.find()) {
                try {
                    Constructor<?> constructor = clazz.getConstructor(String.class);
                    return (InvoiceParser) constructor.newInstance(invoiceText);
                } catch (Exception e) {
                    logger.error("Can't instantiate parser.", e);
                }
            }
        }

        throw new InvoiceException("Can't find parser.");
    }
}

Dúvida
Essa é a melhor prática para essa finalidade? Particularmente eu achei uma gambiarra. Alguma sugestão para melhorar/refatorar o código? Talvez utilizando features do Java 8?
Problema
No futuro, vou precisar além do regex, realizar alguma outra condição, então teria que refatorar completamente esse Factory para suportar que além de um regex, seja possível usar outras lógicas para instanciar o PARSER correto ou algo similar a isso. Qual a melhor prática nesse caso?
Comment: Particularmente não achei uma gambiarra não. Claro que ela tem limitações e não é o código mais bonito que já vimos, mas acredito que você deva pensar nestas limitações quando elas realmente te incomodarem (como no caso que citou). Vamos aguardar para ver se alguém propõe uma ideia melhor. Por enquanto vou pensando aqui em uma alternativa.
Answer: Eu não acho gambiarra, embora tenha minha opinião pessoal quanto ao uso de reflection em produção (que deve ser moderado, o que no seu caso eu acho que é). Mas esta é só minha opinião. Vamos ao código:
Há uma limitação clara no código, que é o fato de todos os parsers serem obrigados a ter um construtor que recebe uma String (pois você está usando clazz.getConstructor(String.class)). Se você tomar este cuidado, não haverá problema.
Se no futuro você tiver outras lógicas além da regex para construir o parser, eu sugiro que você crie uma ou mais classes que encapsulem esta lógica:
public class LogicaCriacaoParser {
    public boolean condicoesSatisfeitas() {
        // retorna "true" se todas as condições para criar o parser são satisfeitas
        // pode ser a regex, e o que mais você precisar
    }
}

Neste caso o seu map teria instâncias de LogicaCriacaoParser (ou de subclasses dela, se preferir):
private static Map<Class<? extends InvoiceParser>, LogicaCriacaoParser> map = new HashMap<>();

static {
    map.put(xxx_PARSER.class, new LogicaCriacaoParser());
    map.put(yyy_PARSER.class, new Subclasse1LogicaCriacaoParser());
    map.put(zzz_PARSER.class, new Subclasse2LogicaCriacaoParser());
    //...
}

Assim, em cada subclasse de LogicaCriacaoParser você poderia implementar sua lógica específica para criar cada parser (dentro do método condicoesSatisfeitas()), podendo ser somente regex, ou regex + o critério que você precisar.
O ponto positivo é que você pode criar a lógica que quiser dentro desta classes (e de suas subclasses), e seu modelo não fica preso a uma lógica única, como por exemplo regex.
Para usar, seria algo do tipo:
LogicaCriacaoParser logica = entry.getValue();

if (logica.condicoesSatisfeitas()) {
    // cria o parser
}

Alternativa (sem o map, nem reflection)
Na verdade você nem precisaria ter o map, e também é possível eliminar o uso de reflection.
A própria classe LogicaCriacaoParser poderia ter um método que retorna o parser específico, caso a condição seja satisfeita. Se preferir, pode deixar a classe abstrata e deixar que cada subclasse cuide do seu caso particular:
public abstract class LogicaCriacaoParser {
    // retorna "true" se todas as condições para criar o parser são satisfeitas
    // pode ser a regex, e o que mais você precisar
    protected abstract boolean condicoesSatisfeitas();

    // possui a lógica para criar o parser
    protected abstract InvoiceParser criarParser();

    // cria o parser se as condições forem satisfeitas
    public InvoiceParser getParser() {
        if (condicoesSatisfeitas()) {
             return criarParser();
        }
        // retorna null se as condições não forem satisfeitas
        return null;
    }
}

Repare que somente o método getParser() é público, pois é o único que as outras classes precisam conhecer.
Com isso, você precisa ter subclasses que sabem criar um parser específico:
// logica para criar XXX_Parser
public class LogicaCriacaoXXX_Parser extends LogicaCriacaoParser {
    protected boolean condicoesSatisfeitas() {
        // verifica as regras para criar o XXX_Parser (regex, etc)
    }

    protected InvoiceParser criarParser() {
        // retorna o XXX_Parser (usando new ao invés de reflection)
    }
}

Assim, você cria uma subclasse para cada parser diferente (yyy, zzz, etc), cada um implementando sua lógica específica.
Então, você teria apenas uma lista com todas as lógicas de criação de parser:
List<LogicaCriacaoParser> logicas = new ArrayList<>();
logicas.add(new LogicaCriacaoXXX_Parser());
logicas.add(new LogicaCriacaoYYY_Parser());
// etc.

E para criar um parser, você faz um loop nesta lista, até achar algum parser que satisfaz as condições:
for (LogicaCriacaoParser logica : logicas) {
    InvoiceParser parser = logica.getParser();
    if (parser != null) {
        return parser;
    }
}

// se não encontrar nenhum, lança o InvoiceException

Claro que há algumas melhorias, como alterar os construtores de cada classe de lógica para receber parâmetros, os próprios métodos para verificar as condições e criar o parser também podem receber parâmetros (que poderiam ser usados na construção do parser, por exemplo), etc.
Mas pelo menos você não está usando reflection (que pelo jeito você não se sentiu confortável usando, e eu te entendo), e você não fica dependente de cada subclasse de parser ter um construtor específico que recebe uma String (já que cada subclasse de lógica pode criar o parser usando new).


Change an Array of Dates to an Array of Strings in Different Date Format - JavaScript

Question: I seem to be going around in circles on this one. Essentially, I have an array of strings that are in the following format ["2017-08-24", "2017-08-29", "2017-09-13". I have another array that is comprised of dates in the conventional Date format.
I need to convert this array of dates (that are in the standard Date format) into the same format as my string array so that I can check them against each other.
Here is my code so far:
var stringDates = ["2017-08-24", "2017-09-11", "2017-12-05", ...]
var datesArray = [Wed Aug 23 2017 00:00:00 GMT+0100 (BST), Thu Aug 24 2017 00:00:00 GMT+0100 (BST), Fri Aug 25 2017 00:00:00 GMT+0100 (BST), Sat Aug 26 2017 00:00:00 GMT+0100 (BST)]

Does anyone have any experience with this? Thanks in advance!
Answer: You can convert a standard date to your format by doing the following:
var myDate = new Date(yourNormalDateHere)
var formatted = (myDate.getMonth() + 1) + "-" + myDate.getDate() + "-" + myDate.getFullYear()

Answer: You can have a function to convert the Date to a String:
function dateToString(date){
  return date.getFullYear() + "-" + (date.getMonth()+1) + "-" + date.getDate();
}

Now just push it to your array of dates:
between.push(dateToString(date));

Comment: @dreamkiller Then you should [**edit your question**](https://stackoverflow.com/posts/45824960/edit) and add this information there. Note that you don't need to add a **edit** or **update** section: you can reword the entire question if needed, if that makes things more clear.
Comment: Like @hugo said, this to be more specific with your questions. Somethinglike: I.e I have this array: [..... , ....., ... ] and need to turn it into [..... , ....., ... ].
Comment: Could you please share how your array looks like now and what is the expected result?
Comment: Sorry, I should have been more specific. My Between array needs to have every item changed to the date format and string type that I need and then placed back into an array. That's what I'm struggling with, to do this for all items in the array...
Comment: Any thoughts Mauricio?
Comment: could you put also the expected result array?


CentOS server doesn't allow more than one FTP connection at a time

Question: I'm still exploring server administration and networking (I'm an intern) and I've set up an FTP server at our company and set up a user account for all the workers here. Problem is I can connect one person every 15 minutes.
I connect one user then disconnect that user. Then if I try to reconnect(even using the same user), it will connect until it accepts to login, then it times out. I use FileZilla and this is what I get when connecting:
Status: Connecting to **********...
Status: Connection established, waiting for welcome message...
Response:   220 Welcome to ******* FTP service.
Command:    USER *******
Response:   331 Please specify the password.
Command:    PASS *******
Error:  Connection timed out
Error:  Could not connect to server

I use vsftpd and here is the config file:
# Example config file /etc/vsftpd/vsftpd.conf
#
# The default compiled in settings are fairly paranoid. This sample file
# loosens things up a bit, to make the ftp daemon more usable.
# Please see vsftpd.conf.5 for all compiled in defaults.
#
# READ THIS: This example file is NOT an exhaustive list of vsftpd options.
# Please read the vsftpd.conf.5 manual page to get a full idea of vsftpd's
# capabilities.
#
# Allow anonymous FTP? (Beware - allowed by default if you comment this out).
anonymous_enable=NO
#
# Uncomment this to allow local users to log in.
local_enable=YES
#
# Uncomment this to enable any form of FTP write command.
write_enable=YES
#
# Default umask for local users is 077. You may wish to change this to 022,
# if your users expect that (022 is used by most other ftpd's)
local_umask=022
#
# Uncomment this to allow the anonymous FTP user to upload files. This only
# has an effect if the above global write enable is activated. Also, you will
# obviously need to create a directory writable by the FTP user.
#anon_upload_enable=YES
#
# Uncomment this if you want the anonymous FTP user to be able to create
# new directories.
#anon_mkdir_write_enable=YES
#
# Activate directory messages - messages given to remote users when they
# go into a certain directory.
dirmessage_enable=YES
#
# The target log file can be vsftpd_log_file or xferlog_file.
# This depends on setting xferlog_std_format parameter
xferlog_enable=YES
#
# Make sure PORT transfer connections originate from port 20 (ftp-data).
connect_from_port_20=YES
#
# If you want, you can arrange for uploaded anonymous files to be owned by
# a different user. Note! Using "root" for uploaded files is not
# recommended!
#chown_uploads=YES
#chown_username=whoever
#
# The name of log file when xferlog_enable=YES and xferlog_std_format=YES
# WARNING - changing this filename affects /etc/logrotate.d/vsftpd.log
#xferlog_file=/var/log/xferlog
#
# Switches between logging into vsftpd_log_file and xferlog_file files.
# NO writes to vsftpd_log_file, YES to xferlog_file
xferlog_std_format=YES
#
# You may change the default value for timing out an idle session.
#idle_session_timeout=600
#
# You may change the default value for timing out a data connection.
#data_connection_timeout=120
#
# It is recommended that you define on your system a unique user which the
# ftp server can use as a totally isolated and unprivileged user.
#nopriv_user=ftpsecure
#
# Enable this and the server will recognise asynchronous ABOR requests. Not
# recommended for security (the code is non-trivial). Not enabling it,
# however, may confuse older FTP clients.
#async_abor_enable=YES
#
# By default the server will pretend to allow ASCII mode but in fact ignore
# the request. Turn on the below options to have the server actually do ASCII
# mangling on files when in ASCII mode.
# Beware that on some FTP servers, ASCII support allows a denial of service
# attack (DoS) via the command "SIZE /big/file" in ASCII mode. vsftpd
# predicted this attack and has always been safe, reporting the size of the
# raw file.
# ASCII mangling is a horrible feature of the protocol.
#ascii_upload_enable=YES
#ascii_download_enable=YES
#
# You may fully customise the login banner string:
ftpd_banner=Welcome to ********** FTP service.
#
# You may specify a file of disallowed anonymous e-mail addresses. Apparently
# useful for combatting certain DoS attacks.
#deny_email_enable=YES
# (default follows)
#banned_email_file=/etc/vsftpd/banned_emails
#
# You may specify an explicit list of local users to chroot() to their home
# directory. If chroot_local_user is YES, then this list becomes a list of
# users to NOT chroot().
#chroot_list_enable=YES
# (default follows)
#chroot_list_file=/etc/vsftpd/chroot_list
#
# You may activate the "-R" option to the builtin ls. This is disabled by
# default to avoid remote users being able to cause excessive I/O on large
# sites. However, some broken FTP clients such as "ncftp" and "mirror" assume
# the presence of the "-R" option, so there is a strong case for enabling it.
#ls_recurse_enable=YES
#
# When "listen" directive is enabled, vsftpd runs in standalone mode and
# listens on IPv4 sockets. This directive cannot be used in conjunction
# with the listen_ipv6 directive.
listen=YES
#
# This directive enables listening on IPv6 sockets. To listen on IPv4 and IPv6
# sockets, you must run two copies of vsftpd whith two configuration files.
# Make sure, that one of the listen options is commented !!
#listen_ipv6=YES

pam_service_name=vsftpd
userlist_enable=YES
tcp_wrappers=YES

Comment: Need more details... What FTP server service are you running (Filezilla as well?), whats your config filelook like...
Comment: VSFTPD and config is in post
Comment: You're vsftp.conf looks good. Were the timeout settings already commented out? If not have you restarted the VSFTPD service since the change? Can you reproduce the same behavior using a different FTP client? When you get the Connection timed out error can you run "telnet FTPHOST 21"; does it timeout as well? I'm going to assume you have IPTables running, have you added a rule to your chain to allow for FTP access?
Comment: I didn't edit the timeout settings so those are the defaults. I've restarted the VSFTPD service and restarted server several times. I'll check for another FTP client. telneting works with a user, but it seems to take about a minute to login. yes, I have port 21 open in iptables.
Comment: I think I may have found the reason. It simply seems to take a very long time to connect. I increased the timeout time in filezilla from 20 seconds to 60 and it now seems to connect. Now I just have to find out why it's taking so long to connect.
Answer: Glad it's working (somewhat) Are you connecting via Hostname or IP? Is the connection time the same for both? If it's different for hostname, could be a DNS issue. Also try using the regular FTP command line utility and see if you're getting the same behavior. Could just be something funky with Filezilla
Comment: Connecting via IP, I've yet to set yup a hostname.  Thanks for the help.
Answer: max_clients=100
max_per_ip=100
#connect_from_port_20=YES

Are the differences between my and your setup / config.
Is there a firewall blocking other ports?
FTP May switch to a other port after connection was build up.


PHP 5.6 SoapClient passing decimal bug

Question: I'm trying to parse an PHP array to SOAP XML with the SoapClient function.
I have to parse a decimal number to SOAP. My PHP array looks lik this:
$contactparams = array(

"DECIMALVARIABLE"=>0.00

);

When executing the SOAP call I'm getting the error thrown that I should use a decimal number with 2 decimals. My guess it that the PHP function converts the 0.00 to plain 0.
Example of the error thrown:

Fatal error: Uncaught SoapFault exception: [soap:Client] Invalid
  number 2dp value (0)

When I use 0.01 it works just fine.
I've already tried to parse it as a string "0.00" & 0.00.""
I've also tried the number_format function to create the 0.00 but with the same result.
Any ideas how to solve this riddle would be greatly appreciated.
Comment: what is the type for the field in the soap contract (wsdl)?
Comment: Not sure what you mean exactly but:  Maybe the integration link is of more value: http://samacom.dyndns.org:5912/davewslink/integration.wsdl
Comment: When you do "0.00" what does the error look like?
How about trying to throw in a space at either end?
Comment: I think `var_dump(0.00)` shows that there is nothing to be done about this. PHP seems to treat zero as an integer. Maybe a packet capture with Wireshark would confirm what goes out over the wire. Are you in WSDL mode?
Comment: Is there a way to convert the php array into another type of array before passing it through the SOAP function?
Answer: After hours of searching for a solution I've finally found a devious one...
When entering the value 0.001 SOAP's functions changes this to the correct value of 0.00
SO:
$contactparams = array(

"DECIMALVARIABLE"=>0.001

);

GIVES:
DECIMALVALUE=0.00

Not quite a clean solution, but one that works..
Answer: this dirty trick can help you understand is this error really related to you decimal variable
<?php

class MySoapClient extends SoapClient
{
    public $decimalValue;
    function __doRequest($request, $location, $action, $version) {
        if (is_null($this->decimalValue)
            throw new Exception("you forgot to set decimalValue");
        $request = str_replace('#decimalValuePlaceHolder#', $this->decimalValue, $request);
        $ret = parent::__doRequest($request, $location, $action, $version);
        $this->__last_request = $request;
        return $ret;
    }
}

// usage
$contactparams = array(
    "DECIMALVARIABLE"=>'#decimalValuePlaceHolder#',
);

$client = new MySoapClient(); // initialize this as prev SoapClient
$client->decimalValue = "0.00"; // or number_format($someNumber, 2); // any decimal variable
$client->callFunction(); // call you function as you did before

Comment: and then you can use this to solve your case. adjust str_replace to your needs and you will be able to send desired values
Comment: Using `str_replace()` suggests it would just send it as a string, which is already stated does not work.
Comment: I am already positive that this error relates to my decimal variable. Thanks anyway
Answer: Fields of the type "shortnumber2dp" must be delivered with 2 decimals : 0.00 and not 0
Make sure that you don't pass an empty string in number_format
echo "A. ".number_format(null, 2)."\n";
// output 0.00
echo "B. ".number_format(0, 2)."\n";
// output 0.00
echo "C. ".number_format('', 2)."\n";
// error

Fix this issue
if(empty($value)){$value = 0;}

Comment: Hi peter, when doing a print_r of my PHP array I'm getting the correct values: [DECIMALVARIABLE] => 0.00, however when converting the php array to SOAP I think they adjust the 0.00 value to plain 0
Comment: @JoeriMinnekeer are there equivalent types that you can pass this variable? e.g. `decimal` in type="omnis:shortnumber2dp"
Comment: If by any chance your situation has to do with this manual http://www.omnis.net/download/manuals/Omnis_Programming.pdf then if i was in your position i would try another type such as number 2dp and floating to see if there is no issue when using those types. If you still get problem then i would advise to post your soap class,function,code to make your question more complete.

PHP 5.6 SoapClient passing decimal bug


How to parameterize a quadric surface of the form $ax^2+by^2+cz^2=yz$

Question: I am trying to find the solutions of an equation of the form,
$$ax^2+by^2+cz^2=yz$$
For $(x,y,z)\in\mathbb{R}^3$, where $a,b,c$ are real and non-zero. So far i've considered dividing it up into cases depending on the sign of the constants, so that the LHS would represent an ellipsoid or hyperboloid.
Of course the LHS would only become that if we added say 1 to both sides, however then this isn't as simple of solving $f(x)=g(x)$ but looking at the intersections of $y=f(x)$ and $y=g(x)$, as these would then become 4 dimensional functions.
If anyone could give any tips or advice i'd greatly appreciate it.
EDIT: By 'solve', I mean find the solution space, so how to parametrically describe this surface.
Comment: $ax^2 + b\left(y-\frac{z}{2b}\right)^2 + \left(c - \frac{1}{4b}\right)z^2 = 0$ (if $b\neq 0$).
Comment: The type of the surface depends on the signs of the coefficients. If $4bc = 1$, we have a quadric $ax^2+b\eta^2=0$ (with a change of coordinates, $\eta=y-z/(2b)$), and that is the $z$-axis if $a$ and $b$ have the same sign, and the union of two planes intersecting in the $z$-axis if the signs are opposite; in the original coordinates, the figure is sheared. If $4bc\neq 1$, we have an equation $ax^2+b\eta^2+\gamma z^2=0$, and that is a single point (the origin) if all signs of the coefficients are equal, and an elliptic cone if not all signs are equal. Again shear for original coordinates.
Comment: Yours is the equation of a _quadric_: except some cases (I didn't check), the solutions are many ...
Comment: What do you mean by _solution_ of the equation ?
Comment: I am asking just which is the solution space: $\Bbb {R}^3$ ?
Comment: Oh sorry, I will specify that. Yes, $\mathbb{R}^3$
Comment: Hmmm ok, thanks, so I should be able to parameterize it?
Comment: Sure, quadrics are rational parametric surfaces.
Comment: @TonyPiccolo: Excellent, I will have a go at that.
Comment: @DanielFischer: I did get that result, how would you recommend getting from that to some way of describing the surface?
Comment: @DanielFischer: Thank you! That is very helpful.
Answer: Because this is a homogenous equation, substitute $(x,y,z)=(x,ux,vx)$ to obtain
$$a+bu^2+cv^2=uv\iff bu^2-uv+cv^2=-a.$$ ($\Delta =1-4bc$). If you want rational solutions, suppose you already have some point on the curve $(u_0,v_0)$. Put $(u,v)=(u'-u_0,v'-v_0)$ to obtain
$$bu'^2-2bu'u_0-u'v'+v_0u'+u_0v'+cv'^2-2cv'v_0=0,$$
at which point substitute $v'=u't,$ thus $$bu'^2-2bu'u_0-u'^2t+v_0u'+u_0u't+cu'^2t^2-2cu'v_0t=0$$or$$(b-t+ct^2)u'-2bu_0+v_0+u_0t-2cv_0t=0$$ and $$u'(t)=\frac{2bu_0-v_0+(-u_0+2cv_0)t}{b-t+ct^2}.$$ Otherwise you want a parametrization that's not necessarily rational. So we're looking to find
$(u,v)$. Factor the left hand side like so:
$$b\left(u-\frac{1+\sqrt{1-4bc}}{b}v\right)\left(u-\frac{1-\sqrt{1-4bc}}{b}v\right)=-a$$ and assume $$bu-(1+\sqrt{1-4bc})v=-aw$$$$u-\frac{1-\sqrt{1-4bc}}{b}v=-\frac{a}{w}$$ when $\Delta \geqslant 0,$ or notice for $\Delta<0$ that
$$(lu+mv)^2+(nu+ov)^2=(l^2+n^2)u^2+2(lm+no)uv+(m^2+o^2)v^2$$ so that
$$l=\sqrt{b}\sin\alpha ,n=\sqrt{b}\cos\alpha$$
$$m=\sqrt{c}\sin\beta ,o=\sqrt{c}\cos\beta$$ where
$$\cos(\alpha-\beta)=-\frac{1}{2\sqrt{bc}}, \text{ so }\alpha-\beta\in\left(\frac{\pi}{2},\frac{3\pi}{2}\right)$$ or equivalently all other intervals differing by $2\pi k$. Either way you end up with parametrizations. You could even let $$\tan \frac{\alpha}{2}=\tau,\tan\frac{\beta}{2}=\tau'$$ to tie it all together. You can analogously derive the case for the hyperbolic sine and cosine for the form $X^2-Y^2.$


Estimate for $|x_n-A|$ for a Cauchy sequence $(x_n)$ satisfying $|x_{n+1}-x_n|<Cr^n$ for some constant $C$, and $\lim_{n \rightarrow \infty} x_n=A$.

Question: Find an estimate for $|x_n-A|$ in terms of $n$ and $r$, where $(x_n)$ is a Cauchy sequence satisfying $$|x_{n+1}-x_n|<Cr^n$$ for some constants $C$,
$0<r<1$, and $\lim_{n \rightarrow \infty} x_n=A$.
How can I use the concept of Cauchy and its convergence to find the estimate?
Answer: Knowing that
$$|x_{n+1}-x_n|<Cr^n$$ for all $n \in \mathbb N$, you get for $m \gt n \in \mathbb N$
$$\begin{aligned}\vert x_m - x_n \vert &\le \vert x_m - x_{m-1} \vert + \dots + \vert x_{n+1}-x_n \vert\\
&\le Cr^{m-1} + \dots + Cr^n\\
&\le Cr^n + C r^{n+1} + \dots\\
&= \frac{Cr^n }{1-r}
\end{aligned}$$
Now, in this inequality that is valid for all $m \gt n$ make $m \to \infty$. You get
$$\vert x_n - A \vert \le \frac{Cr^n }{1-r}.$$


Hermitian Operators and the Spectral Theorem

Question: I understand that in a finite-dimensional vector space $V$, a diagonalizable linear operator $T: V \to V$ decomposes $V$ into a direct sum of its invariant eigenspaces, on each of which it restricts to a scalar multiple of a projection. The Spectral Theorem says that this occurs if $T$ is Hermitian, and I'm trying to piece together a geometric intuition for the proof.
Here's my thinking: we know that the eigenspace $E$ of some eigenvector $v$ is $T$-invariant, but we need something extra (presumably involving the Hermiticity of $T$) to show that its orthogonal complement $E^{\perp}$ is also invariant: that is, we know that $Tv$ will stay inside $E$, but Hermiticity is required for $Tw$ (for some $w \notin E$) to stay outside of $E$. Once this is done, we can just restrict to $E^{\perp}$ and play the same game there, so that by induction we separate out $n = \dim{V}$ orthogonal directions to get our eigenbasis.
So what is it about Hermiticity that "stabilizes" $E^{\perp}$ under $T$? I'm not looking for a rigorous proof, but rather a natural explanation of the geometrical significance of self-adjointness. More generally, why does requiring $T$ to be normal make the Spectral Theorem biconditional?
Comment: What do you mean by "why does requiring T to be normal allow allow us to reconstruct its normality from an eigenbasis?"
Comment: If an operator is Hermitian, then it's diagonalizable; however, $T$ must be normal, i.e. $T^* T = TT^*$, for this "if" to become an "iff." My question is about what adjoints mean geometrically, so I thought that perhaps normal operators afford a more natural interpretation. My main question, however, is still about self-adjointness. I've edited my original question to reflect this.
Comment: Ah, thanks for the edit.
Answer: I think that this is a great question that is usually unasked and unanswered. This is quite unfortunate because it has a very simple answer:

We can use the adjoint operator $T^{*}$ to detect $T$-invariant subspaces of codimension one.

Let me show you how this works. Assume $W \subseteq V$ is a codimension one subspace (geometrically, a hyperplane). Let us choose a normal vector $0 \neq w^{\perp} \in W^{\perp}$ to $W$. If the vector $w^{\perp}$ is an eigenvector of $T^{*}$ then $W$ is a $T$-invariant subspace. To see why, let $w \in W$ and compute
$$ \left< Tw, w^{\perp} \right> = \left< w, T^{*}w^{\perp} \right> = \left< w, \lambda w^{\perp} \right> = \lambda \left< w, w^{\perp} \right> = 0 $$
which shows that $Tw \in W$.
Stated differently, this observation shows that any eigenvector $w$ of $T^{*}$ gives us a $T$-invariant codimension one subspace $W = \operatorname{span} \{ w \}^{\perp}$.

Given the result above, what kind of condition we can impose on an operator $T$ which guarantees that if $v \in V$ is an eigenvector of $T$ then $W = \operatorname{span} \{ v \}^{\perp}$ is $T$-invariant? Well, we can try and guarantee that if $v$ is any eigenvector of $T$ then $v$ is also an eigenvector of $T^{*}$ (possibly with a different eigenvalue).
One condition which guarantees the above is $T = T^{*}$ because then $v$ is trivially an eigenvector of $T^{*}$ with the same eigenvalue. A less trivial condition which guarantees the above is $TT^{*} = T^{*}T$ because then if $v \in V$ is an eigenvector of $T$ with eigenvalue $\lambda$ then $v$ is an eigenvector of $T^{*}$ with eigenvalue $\overline{\lambda}$.
So what is the difference between the real and the complex case? The usual proof of the spectral theorem for the real and complex case goes like this:

Find one eigenvector $v \in V$ of $T$ and set $E = \operatorname{span} \{ v \}$.
Show that $E^{\perp}$ is $T$-invariant.
Restrict $T$ to $E^{\perp}$ and repeat the argument above for $T|_{E^{\perp}}$

When $V$ is complex, step one is trivial and doesn't use any property of $T$. To get step $(2)$, we use $T^{*}T = TT^{*}$. Step three is then again trivial because if $T$ was normal on $(V, \left< \cdot, \cdot \right>)$, then $T|_{E^{\perp}}$ will be normal on $(E^{\perp}, \left< \cdot, \cdot \right>|_{E^{\perp}})$.
When $V$ is real, step one is not trivial. The condition $T^{*}T = TT^{*}$ which is enough for step two to carry unfortunately doesn't guarantee that $T$ has even one eigenvector so we can't start the argument. However, the stronger condition $T = T^{*}$ does guarantee that $T$ has at least one eigenvector (this is a non-trivial result). This condition is also enough for step two and step three is again trivial.
Answer: This is more of an extended comment about some hidden algebraic structure having to do with the normal operator property. This is not a direct answer because this isn't "geometric", though it fits into a larger blocks of conceptual intuition (representation theory), which is maybe close to what you mean anyway...:
If $T^* T = T T^*$,then the algebra $A = \mathbb{C}[T,T^*]$ is commutative.
From Schur's lemma we know that the irreducible finite dimensional representations of $A$ are 1 dimensional. See * below.
Then if $W$ is an $A$ invariant subspace of $V$, so is its orthogonal complement (easy computation, using that $T$ and $T^*$ fix this subspace, $<Tv, w> = <v,T^*w> = <v,w'> = 0$, and the same for $T^*v$...).
Hence, if $W$ is more than one dimensional, it isn't irreducible, so has an invariant subspace, and splits around it. By induction on dimension can prove that $V$ decomposes into orthogonal irreducibles, which are necessarily one dimensional.
These one dimensional invariant subspaces are necessarily eigenspaces of both $T$ and $T^*$, and this gives the spectral decomposition.
*Digging back into where $T^*T = TT^*$ is used here, it is in the application of Schur's lemma. Because of normality, $T$ and $T^*$ are both intertwiners for any $A$ module, and hence must act by scalars on irreducible $A$ modules (here we use the existence of an eigenvector, which requires working over $\mathbb{C}$). This implies that irreducible $A$ modules are 1 dimensional.
(About generalization to infinite dimensions : Unfortunately, the proof I know of Schur's lemma in the infinite dimensional setting requires the spectral theorem, since there isn't always going to be an eigenvector, so I don't think this argument generalizes to give intuition about that case... though if someone knows an extension I'd love to hear it.)


How to use background-clip border-box correctly

Question: For some reason I don't understand background-clip: border-box. I can do it using an additional parent div, but would prefer not to. See:

#bgbox {
  width: 500px;
  height: 150px;
  background: blue;
}

#bgbox__inner {
  width: 300px;
  height: 150px;
  margin: auto;
  background-color: #BADA55;
  background-image: url(https://i.imgur.com/tBEjfgJ.png);
  background-clip: border-box;
}

The background should span the borders as well. Why it does not happen?
Comment: there is no border in your code, share the code where you are trying to use it. Note that border-box is the default value of background-clip
Comment: I was looking for margin-box which is nonexistant. Sorry about that
Answer: A little bit of theory:
using background-clip you can control 3 ways of background image inside an element

background-clip: content-box shows bg image only in content area, ignores padding and border.
background-clip: padding-box shows bg image in padding area, ignores border.
background-clip: border-box shows bg image in border area, if border color is transparent.
In your case, to get the result you shouldn't use background image in child element. Lets add it to parent block and make it 100% width. Because the is no way to affect margin area or any parent area from a child.

    body {
      margin: 0;
      padding: 0;
    }
    #bgbox {
      width: 100%;
      height: 150px;
      background: blue;
      background-image: url(https://i.imgur.com/tBEjfgJ.png);
      background-clip: padding-box; /*not nesessery if there is no border or padding*/
    }

    #bgbox__inner {
      width: 300px;
      height: 150px;
      margin: auto;
      background-color: #BADA55; /* can be removed */
      padding: 0 100px;
    }

1

Comment: `background-clip: padding-box;` is useless here, remove it and you will have the same output
Comment: I'm just asking, which result do you need to reach. May be you don't need background-clip an all.
Comment: I am not the asker (if you want clarification, consider the comment section instead)
Comment: It's just a MVP, I have to have it for whole page width unfortunately
Comment: I'm terribly sorry, but still don't understand the goal that we should reach. Could you illustrate it via image or something?
Comment: Body as parent, variable width, inner container with auto margin fixed width, but container background should span as far as body tag.
Comment: Just edited an answer. I hope, there is an answer. It is impossible to affect the parent padding using background-clip of a child.
Comment: After edit it makes sense I wasn't right in my way of thinking, thank you


Finding generators of an automorphism group?

Question: I'm trying to construct a homomorphism $\theta:C_2 \rightarrow AutC_{17}$. To do this I need to map the generator of $C_2$ (call it $a$) to a generator of $AutC_{17}$, but to do this I need a way of finding generators of an automorphism group.
Does anybody know a method of doing this?
Many thanks.
Comment: $C_{n}$ is the cyclic group of order $n$, i.e. $C_{3}={(a, a^2, a^3 =1)}$
Also I probably should have mentioned that I'm looking for non-trivial homomorphisms, so excluding mapping $a$ to the identity.
Thanks for your replies so far.
Answer: The automorphism group of $C_{17}$ is isomorphic to $C_{16}$.  If you want to embed $C_2\cong\langle y \rangle$ into it, then letting $C_{16}\cong \langle x \rangle$, you can just send $y\mapsto x^8$.  Of course, this isn't very satisfying, and you probably want to actually construct the automorphism itself; this requires some explanation.
If you've taken number theory, you've seen $(\mathbb{Z}/17\mathbb{Z})^\times$, the group of units modulo $17$.  If you've run into finite fields, you know that the additive group of $\mathbb{F}_{17}$ is isomorphic to $\mathbb{Z}/17\mathbb{Z}$ and the multiplicative group of $\mathbb{F}_{17}$ is $(\mathbb{Z}/17\mathbb{Z})^\times$.  If you haven't seen either of those yet, it turns out that if you multiply the integers in a cyclic group of prime order rather than adding them, you get a group as long as you remove $0$ (since it has no multiplicative inverse).  You can read about this in any elementary text on modular arithmetic (including Wikipedia).
What I am getting at is that there is a rather elegant description of the automorphism group of a cyclic group by multiplications of its elements.  If we take an $a\not= 0\in \mathbb{Z}/17\mathbb{Z}$, we can define the function $\theta_a:\mathbb{Z}/17\mathbb{Z}\rightarrow \mathbb{Z}/17\mathbb{Z}$ by $\theta_a(x)=ax$.  Noting that $$\theta_a(x+y)=a(x+y)=ax+ay=\theta_a(x)+\theta_a(y)$$ and that $\theta_a(x)=ax=0$ implies that $x=0$, we see that this is an automorphism of $\mathbb{Z}/17\mathbb{Z}$.
We can show that such automorphisms form a group under composition.  $$(\theta_a\theta_b)(x)=\theta_a(\theta_b(x))=a(bx)=(ab)x=(\theta_{ab})(x)$$ so $\theta_a\theta_b=\theta_{ab}$.  (Here, you can see the isomorphism to $(\mathbb{Z}/17\mathbb{Z})^\times$ popping up in the subscript: the map $\theta_a\mapsto a$.)  The rest of the group axioms are verified easily.  It turns out that this group of $\theta_a$'s constitutes the entire automorphism group of $\mathbb{Z}/17\mathbb{Z}$.
So, finding a nontrivial embedding of $C_2$ into $C_{17}$ reduces to finding an element $a\in (\mathbb{Z}/17\mathbb{Z})^\times$ with order $2$.  Noting that $16\equiv-1\mod{17}$, you see that the map is $\phi:C_2\rightarrow \text{Aut}{C_2}$ by $\phi:y\rightarrow \theta_{16}$.  Of course, this method will work to find the automorphism group of $C_p$ for any prime $p$, and the automorphism group of any cyclic group $C_n$ can be described similarly as long as the $a$'s in $\theta_a$ correspond to units modulo $n$.  (For a good time, try forming the semidirect product of $C_n$ by $\text{Aut}{C_n}$ - you now know how to make a holomorph.)
Comment: Wow. I really didn't expect such an in depth explanation but I understand it now, thank you so much for your help!
Answer: You seem to be trying some groups semi-direct stuff. Now, in order to get a non-trivial homomorphism as you want you must map the generator of $\,C_2\,$ to an element of the same order in $\,\operatorname{Aut}(C_{17})\cong C_{16}\,$ .
If $\,C_{17}=\langle\,b\,\rangle\,\,,\,\,C_2=\langle\,a\,\rangle\,$  ,then you can always try the nicest, cutest automorphism of an abelian group: the involution $\,x\to x^{-1}\,$ , thus:
$$f:C_2\to\operatorname{Aut}(C_{17})\,\,,\,f(a)(b):=b^{-1}$$
If you're really going on semidirect products, you can write this as $\,b^a:=b^{-1}\,$
Comment: @Traxter: You could also take $$f:C_2\to\text{Aut}(C_{17})\\ x\longmapsto f_x\in \text{Aut}(C_{17})$$ with $f_x(y)=y^x=y^l$ and $(l,17)=1$ and $l^2\equiv 1\; \; \text{mode 2}$. +1 for really the cutest map.


Poisson Fun exercise question

Question: Based on your understanding of the Poisson process, determine the numerical values of  $a$  and  $b$  in the following expression.
$$ \int_{t}^∞ {λ^6τ^5e^{−λτ} \over 5!}dτ= \sum_{k = a}^b{(λt)^ke^{-λt} \over k!} $$
Find the following
$a=$
$b=$
I can't seem to figure out what is a and b in Poisson process!
Answer: Poisson processes are typically used to describe a series of event occurrences. Here, we have one with event rate $\lambda$, where the number of events occurring in $t$ seconds is a Poisson random variable with mean $\lambda t$. So, the RHS of the equation can have the following meaning: the probability of number of events occurring in $t$ seconds is between $a$ and $b$, inclusive.
Poisson process have another useful property: the time between consecutive events are independent and exponentially distributed RVs, with rate $\lambda$ again. These are called inter-arrival times. More importantly, if you sum $n$ of these independent exponential RVs, you get a Gamma RV with $\alpha=n,\beta=\lambda$ which has the meaning "the time required to have $n$ number of events". The LHS of the equation resembles the Gamma distribution very much, with $\alpha=6,\beta=\lambda$, and since the integration is from $t$ to $\infty$, it means the probability of the time required to have $6$ events being larger than $t$, which also means the probability of having 5 or less events in $t$ seconds.
If you combine these two meanings, what will be $a$ and $b$?

Poisson Fun exercise question


Is there a counterexample such that : $X$ is a topology space , every infinite subset of $X$ has a limit point but $X$ is not compact .

Question:
$X$ is a topology space and $A=\{x_1 , x_2 , ... , x_n , ... \}$ is a subset of $X$ , $y$ is a limit point of $A$ .
  Can we show that for each $N$ , $y$ is also a limit point of $A'=\{x_N ,x_{N+1}, ... \}$ ?

It is obvious that the conclusion hold when $X$ is a metric space . But it might not be valid for all topology space since if it is true , then we can use it to prove : If every infinite subset in $X$ has a limit point , then $X$ is compact . (Which is not true for all topology space )
Suppose there is family of open sets $O_1,\ldots,O_n,\ldots$ such that $X \subset \cup O_n$ but there is no finite subcovering. Construct the sequence $A=(x_n)$ such that $x_n \in X \setminus \bigcup_{i=1}^n O_i $ . But our assumption $A$ has an limit point $x$ , we say that $x \in O_N$ for some $N$ . Let $$A'=\{x_N ,x_{N+1}, ... \}$$ then we can see $x$ is not a limit point of $A'$ , since $x \in O_N $ but $O_N$ contains no element of $A'$ .
My question:
Is there any counterexample such that : $X$ is a topology space , every infinite subset of $X$ has a limit point but $X$ is not compact .
Comment: Ah very nice. Just thought about it some more, and I think you might want to consider spaces where compact and sequentially compact are not equivalent. For example, https://www.andrew.cmu.edu/user/calmost/pdfs/sasms_F04.pdf and https://math.stackexchange.com/questions/152447/compactness-sequentially-compact
Comment: The real numbers?
Comment: @AlkaKadri I think $N$ is an infinite set of $R$ which has no limit point .
Comment: Do you know about ordinal numbers? Well-ordered sets?
Answer: That $x$ is a limit point of $A$ implies that it is a limit point of $A\setminus F$, where $F \subseteq A$ is finite, will hold in any $T_1$ space (so when singletons are closed). That answers the first part of your question.
In a $T_1$ space, being a limit point of $A$ (every neighbourhood of $x$ intersects $A\setminus\{x\}$) is equivalent to $x$ being an $\omega$-limit point of $A$ (every neighbourhood of $x$ contains infinitely many points of $A$).
"Every infinite set $A$ has an $\omega$-limit point" is in general spaces equivalent to "every countable open cover of $X$ has a finite subcover", i.e. countable compactness, which for metrisable spaces indeed is equivalent to compactness but in general not: consider $\omega_1$, the first uncountable ordinal in the order topology, or $\{0,1\}^\mathbb{R}\setminus \{\underline{0}\}$, which are countably compact but not compact. The first is also sequentially compact, first countable, hereditarily normal etc., so even for very nice spaces these notions need not be equivalent.


Getting Input Fields from Gravity Forms on Woocommerce

Question: Gravity Forms Product Add-ons for Woocommerce displays the form inputs of a user in the cart and checkout. I want to display these form fields in the user's Account page with their orders. I've been trying for a week and can't seem to get the right php code put together. How can I do this?
My code as it stands is like so:
<code>$form_id = RGFormsModel::get_form_id('Domains');
$form = GFFormsModel::get_form_meta($form_id);
$field = GFFormsModel::get_field($form, 1);
$leads = RGFormsModel::get_leads($form['id']);

foreach($leads as $lead)
{
    foreach($field as $field_id)
    {
        $value = rgar($lead, (string) $field_id);
        echo $value;
    }
}
</code>
This returns all entries for the field I want, however, I only want to return the entry that was submitted with that particular product. Help?
Here's a quick example for clarity on what I'm looking for. A user buys a shirt and selects size large from a Gravity Form that was attached to the product. On the cart and checkout pages, it says beneath the product title "Size: Large". I want to add that same text to the "My Account" page with their order.
Answer: The way I solved a similar problem may not be the best in coding practices but it works. It takes custom data associated with the order from Gravity Forms and displays it under the shipping address in WooCommerce individual order page:
<code><?php
add_action('woocommerce_admin_order_data_after_shipping_address', 'ips_show_signs_in_admin_under_shipping', 10, 1);
/*
function to put in functions.php of the theme to add custom gravityforms data to customer order page in admin area.
*/
function ips_show_signs_in_admin_under_shipping($order)
{
    global $woocommerce, $post;
    $order_items = $order->get_items(apply_filters('woocommerce_admin_order_item_types', array( 'line_item')));
    foreach($order_items as $item_id => $item)
    {
        if ($metadata = $order->has_meta($item_id)) //not a comparison, so one equal sign. so if there is any data in there it would assign it and thus making it true, if no data it would be false
        {
            foreach($metadata as $meta)
            {
                // Skip hidden woocommerce core fields just in case
                if (in_array($meta['meta_key'], apply_filters('woocommerce_hidden_order_itemmeta', array(
                    '_qty',
                    '_tax_class',
                    '_product_id',
                    '_variation_id',
                    '_line_subtotal',
                    '_line_subtotal_tax',
                    '_line_total',
                    '_line_tax',
                    )))) continue;
                if (is_serialized($meta['meta_value'])) continue; // Skip serialised meta since we dont need it incase its in there
                $meta['meta_key'] = esc_attr($meta['meta_key']); //just to make sure there is no surprises in there
                $meta['meta_value'] = esc_textarea($meta['meta_value']); // using a textarea check for surprises (sql injection)
                if ("Signpost Address" === $meta['meta_key']) //here comes the custom data from gravity forms
                {
                   echo $meta['meta_value']; //this is what i was after from gravity forms collected with order
                }
            } //closes --- foreach($metadata as $meta)
        } //closes --- if ($metadata = $order->has_meta($item_id))
    } //closes --- foreach($order_items as $item_id => $item)
} //closes --- function
?>
</code>
Edit: This code searches the order meta data
Answer: I have added the above code in my functions.php file and unfortunately this hasn't worked for me. I have looked all over for a solution to this and this seems to exactly be what I'm after. Do i simply replace "Signpost Address" with say "Blanket Size" if that were one of my gravity form options?
Comment: The code I pasted is specific to a project that does what you seek. However since my project was about Signpost Addresses , and yours is about something entirely different you need to modify if ("Signpost Address" === $meta['meta_key']). Download a plugin called Adminer. Export the database as a sql text file, and search text file.


Why @ in Objective C

Question: I'm coming to Objective-C from Java.  I gather Strings are:
NSString *greeting = @"Hello";

What I'm wondering is why do I need the @ symbol, as opposed to just:
NSString *greeting = "Hello";

I can't seem to find an answer for this.
Comment: Because all the other characters were used.  (Which is the same reason that `@` is used in email addresses.)
Comment: Also see http://stackoverflow.com/questions/25749/what-does-the-symbol-represent-in-objective-c
Answer: "Hello" is C string expression or in other words C array of char. @"Hello" is instance of class NSString.
So, this would be correct :
NSString *greeting = @"Hello";
char *greeting2 = "Hello";

Answer: Objective-C is a real superset of C. as "Hello" is a C construct (c array of chars, aka C-String), it must be usable as that in Objective-C too. There-for to separate C-Strings from NSString objects, a symbol is needed to allow literal creation during compile time.
Actually the @-Symbol is used throughout Objective-C to distinguish Objective-C related things from C. (@selector(), @[], @{}, @try/@catch/@finally)
Answer: With @"Hello" you get an NSString literal, an object. With "Hello" you get a C string literal. Similarly, there is special syntax for creating NSArray, NSDictionary and NSNumber literals:
// Instantiate an array with objects a, b, c
NSArray *myArray = @[a, b, c];

// Instantiate a dictionary (a map) with k1, k2, k3 as keys and o1, o2, o3 a
NSDictionary *myDictionary = @{k1: o1, k2: o2, k3: o3};

// Instantiate a number with int 1234
NSNumber *myNumber = @1234;

Source: http://clang.llvm.org/docs/ObjectiveCLiterals.html

Why @ in Objective C


TypeError: undefined is not an object (evaluating 'parentOutlet.peekState')

Question: I have a multi-page angular-nativescript application (with a sidedrawer and a page-router-outlet). When I first launch the application I can navigate between pages on the sidedrawer just fine, but after a few minutes (like 10), trying to navigate from one page to another crashes the app with this message:

JavaScript error:
  file:///app/tns_modules/nativescript-angular/zone-js/dist/zone-nativescript.js:826:78: JS ERROR Error: Uncaught (in promise): TypeError: undefined is not an object (evaluating 'parentOutlet.peekState')
  upsertModalOutlet@file:///app/tns_modules/nativescript-angular/router/ns-location-strategy.js:506:41
  file:///app/tns_modules/nativescript-angular/router/ns-location-strategy.js:128:44
  forEach@[native code]
  pushStateInternal@file:///app/tns_modules/nativescript-angular/router/ns-location-strategy.js:111:54
  pushState@file:///app/tns_modules/nativescript-angular/router/ns-location-strategy.js:85:31
  pushState@file:///app/tns_modules/nativescript-angular/router/ns-platform-location.js:49:40
  pushState@file:///app/tns_modules/@angular/common/bundles/common.umd.js:511:45
  go@file:///app/tns_modules/@angular/common/bundles/common.umd.js:286:45
  setBrowserUrl@file:///app/tns_modules/@angular/router/bundles/router.umd.js:4007:33
  file:///app/tns_modules/@angular/router/bundles/router.umd.js:3960:40
  file:///app/tns_m<\M-b\M^@\M-&>
* JavaScript call stack:
  (
  0   UIApplicationMain@[native code]
  1   start@file:///app/tns_modules/tns-core-modules/application/application.js:272:26
  2   run@file:///app/tns_modules/tns-core-modules/application/application.js:300:10
  3   bootstrapNativeScriptApp@file:///app/tns_modules/nativescript-angular/platform-common.js:185:26
  4   bootstrapApp@file:///app/tns_modules/nativescript-angular/platform-common.js:103:38
  5   bootstrapModule@file:///app/tns_modules/nativescript-angular/platform-common.js:87:26
  6   anonymous@file:///app/main.js:7:57
  7   evaluate@[native code]
  8   moduleEvaluation@:1:11
  9   promiseReactionJob@:1:11
  )
  * Terminating app due to uncaught exception 'NativeScript encountered a fatal error: Error: Uncaught (in promise): TypeError: undefined is not an object (evaluating 'parentOutlet.peekState')
  upsertModalOutlet@file:///app/tns_modules/nativescript-angular/router/ns-location-strategy.js:506:41
  file:///app/tns_modules/nativescript-angular/router/ns-location-strategy.js:128:44
  forEach@[native code]
  pushStateInternal@file:///app/tns_modules/nativescript-angular/router/ns-location-strategy.js:111:54
  pushState@file:///app/tns_modules/nativescript-angular/router/ns-location-strategy.js:85:31
  pushState@file:///app/tns_modules/nativescript-angular/router/ns-platform-location.js:49:40
  pushState@file:///app/tns_modules/@angular/common/bundles/common.umd.js:511:45
  go@file:///app/tns_modules/@angular/common/bundles/common.umd.js:286:45
  setBrowserUrl@file:///app/tns_modules/@angular/router/bundles/router.umd.js:4007:33
  file:///app/tns_modules/@angular/router/bundles/router.umd.js:3960:40

It's pretty reliably reproducible but I have to wait like 10 minutes each time
Comment: looking in the source code, it seems like dialogs are the issue. Are you using these? Perhaps your implementation is wrong, and you are not closing them properly
Comment: have you updated nativescript to the last version?
Comment: Yea, I'm on nativescript 5.1.0 and angular 6.1.0
Answer: Seems like the problem was related to how I was handling the routing between angular versions. In angular 4 I was using the <router-outlet> and had tkMainContent in a <StackLayout> that was surrounding it. When I switched to using <page-router-outlet> in angular 6 I needed to move the tkMainContent to inside the <page-router-outlet>
Comment:
So this is not okay?
Comment: It's been a long time since I looked at this, but based on my answer I would think the syntax you said is fine
Comment: This is the configuration I have that is working:

``` enableSwipeBackNavigation="false">
     ```
Answer: I had the same error, and I found that it was caused because I used this in main.ts file:
platformNativeScriptDynamic({createFrameOnBootstrap: true}).bootstrapModule(AppModule);

Changing this to:
platformNativeScriptDynamic({createFrameOnBootstrap: false}).bootstrapModule(AppModule);

or
platformNativeScriptDynamic().bootstrapModule(AppModule);

solved the problem.
This error particularly appeared while trying to load a Modal that uses the root view to show the modal.
According to the NativeScript documentation, you should use createFrameOnBootstrap in cases where your application does not use page-router-outlet, as without it you will not get the default Page and Frame, which means you will not be able to inject them in your components or show the ActionBar.
My application had page-router-outlet, so setting createFrameOnBootstrap: false solved this issue.


Can I change pager.inc theme?

Question: can I theme output of includes/pager.inc using drupal template system?
I want invert page links, I don't want any edit on pager.inc or CSS.
maybe invert items passed to theme_pager function
Answer: Not sure what you are asking here, you can override theme_pager() like any other theme function in Drupal. It is however quite a bit of code.
It's also relying on global functions, so you probably can't simply call the original fuction with reverted arguments.
Comment: yes, but I had this problem: http://drupal.org/node/457242, as you can see i solve it by remove theme registry row from cache table

Can I change pager.inc theme?


How do I connect my bass to my Macbook pro for effects processing?

Question: Anyone have any suggestions on how I can connect my bass to my Macbook for effects processing? What I want to do is connect my bass to the MBP, then from the MBP to my Amp. Can't quite figure out how to do this, because I only have an Audio Out jack on the computer.
For effects I want to use Garage Band, but I'm open to other suggestions for performance oriented software as well.
Comment: http://music.stackexchange.com/questions/2032/using-an-electric-guitar-with-garageband then? http://music.stackexchange.com/questions/11167/how-necessary-is-an-usb-audio-interface -- but it seems to me the first answer in the dupe tells you what you need -- a USB audio interface.
Comment: Welcome to music.se. Please search the site for existing answers before posting questions. This question has been answered several times. It's worth noting, there's nothing about a bass that makes the answer different than for an electric guitar. Nor is there much difference between a PC and a Mac in this respect.
Comment: When typing my question, I was hoping to see another in the results. Must have missed that one. I'll check to see if that has what I need.
Comment: @slim Thanks, but that actually didn't help me entirely. I need hardware options. More specifically preferrable connections from **Bass > MBP > Amp**
Answer: Ok, I found an answer. I have an existing Rocksmith Cable from the game and I can use that with my MAC and Garageband.
I found a procedure on youtube what will add the Rocksmith cable as an Aggregate device.
Now I can jam with GB on my Mac plugged into my amp! SWEET!!
Thanks @slim for your help.


Do the maximal intervals of an ODE solution vary continuously?

Question: Consider the following Cauchy problem (which we will denote by IVP$_{x_0}$ )
$$\dot {x} = F (x)$$
$$x(0) = x_0,$$
where $F:U \subset \mathbb {R}^n \rightarrow \mathbb {R}^n $ is a $\mathcal {C}^{\infty}$ function, and $U $ is an open set.
Let $\varphi (t,x)$ be the flow of the above differential equation, i. e. $\varphi $ satisfies the conditions:

$\frac {d \varphi }{dt}(t,x) = F (\varphi (t,x))$.
$\varphi (0,x) = x$, $\forall$ $x $ $\in$ $U $.
$\varphi (t,x) $ is the maximal solution of the IVP$_{x}$.

For each $y$ $\in$ $U$ fixed, we can associate this value to an open interval $\left(- \omega_{y}^ {(1)}, \omega_{y}^{(2)}\right)$ corresponding to the domain of the maximal solution of the IVP$_y$, i. e, $\left(- \omega^{(1)}_{y}, \omega_{y}^{(2 )}\right)$ is the domain of $g (t) = \varphi (t,y).$
Now, I would like to know if
\begin{align*}\Psi : U &\rightarrow \mathbb {R} \\
x &\mapsto \min \left\{\omega_{x}^{(1)} , \omega_{x}^{(2)},1\right\}
\end{align*}
is a continuous function. Does anyone know how I prove this?
EDIT: I found an easy counter-example:
Define $U := \left(-\frac{1}{4},\frac{1}{4}\right)\times \left(-\frac{1}{4},\frac{1}{4}\right) \setminus \{0,0\}$. Consider the function
\begin{align*}F: U& \rightarrow \mathbb{R}^2\\
 u& \mapsto  (1,0),
\end{align*}
then trivially $\Psi$ is not continuous, this example is particularly interesting because $F$ has no singular points.
Answer: In general it is not continuous.
Simplest example: in the line consider $F$ with a single zero such that all other solutions nonglobal. Say $F(x)=x^2$.
The best that you can say is that $$\left\{\left(x,\omega_x^{(1)},\omega_x^{(2)}\right):x\in\mathbb R^n\right\}$$ is an open set (see for example Hale's ODE book).
Comment: I have already replied, in a complete manner, it is quite inappropriate to change the question. Please avoiding doing this!
Comment: It's true, I forgot to say that the field has no singular points, I will edit the question
Comment: I know, I'm sorry
Comment: I returned the question to the original version, I thought it would not be fair if you did not receive the credits for your answer. Do you think I should create a new post with the question formulated correctly, or rather forget about it?
Comment: You certainly should never forget about a question! We all like to learn.


Consultar se SLUG já existe

Question: Gostaria de saber como eu faço pra consultar se um SLUG já existe no banco de dados e, caso exista, como incrementar +1 ao fim da string, ficando:
site.com/artigo/titulo-de-teste1
site.com/artigo/titulo-de-teste2
site.com/artigo/titulo-de-teste3

Tentei utilizando SELECT:
$slug = $_POST["slug"];
 $slug = slug($titulo, '-');
 $consulta = mysqli_query($conecta, "SELECT * FROM conteudo WHERE slug LIKE '$slug%'");

$listaSlugs = mysqli_fetch_array($consulta);
 if($slug == $linha && $listaSlugs >0){
echo 'encontrou slug';
// aqui eu quero fazer com que $slug fique com +1 caso haja algum identico no banco
// ex: se encontrar titulo-teste, fique titulo-teste1, titulo-teste2 }
else { // continua o codigo.. com INSERT}

Li algo sobre criar o campo como unique e Tentei de diversas formas, mas não consegui, porque não sei como deve ser o tipo do campo (VARCHAR, TEXT, etc..)
Comment: mostre como tentou fazer o select
Comment: $slug = $_POST["slug"];
    $slug = slug($titulo, '-');

$consulta = mysqli_query($conecta, "SELECT * FROM conteudo WHERE slug LIKE '$slug%'");
$listaSlugs = mysqli_fetch_array($consulta);

if($slug == $linha && $listaSlugs >0){
echo 'encontrou slug';
// aqui eu quero fazer com que $slug fique com +1 caso haja algum identico no banco
// ex: se encontrar titulo-teste, fique titulo-teste1, titulo-teste2
}
else
{
// continua o codigo
Comment: coloca isso na pergunta.. edite a pergunta..
Comment: Pronto Daniel Omine!
Comment: Comecei a fazer e estava quase postando uma resposta. Mas então percebi que a coisa não é tão simples assim. se tiver paciência, outro dia postarei algo mais conciso. Pensei que fosse simples, mas não é tão simples assim, dentro das condições que apresentou.  Fiz algo com uma instrução SQL parecida com a resposta do Lucas, ao invés do `LIKE` troquei por `=`, mas é justamente isso que percebi que é um erro pois dessa forma nunca encontrará um incremento existente. É justamente essa a parte mais complexa.
Comment: Eu consegui fazer uma comparação da seguinte forma:
if($slug == 'teste') {
echo "O slug $slug já existe";
} else {
//continua o código..
}

O verdadeiro problema foi quando eu tentei comparar com os slugs j á existentes no banco de dados..
Comment: Exato.. hehe isso vai dar um trampo e requer tempo. Não disponho desse tempo agora, mas gostei do desafio. Se nenhuma outra pessoa postar antes, vou tentar postar alguma solução. Mas não fique esperando que eu venha entregar a resposta pronta pois não posso comprometer e prometer nada. Pensei em algo como, verificar a data de cadastro. A lógica seria também filtrar pela data do mais recente. Se não possui data de cadastro ou algum outro campo onde podemos verificar que é o registro mais novo, vai complicar.
Comment: Não é possível só consultar se o valor da string $slug já existe na coluna slug em meu banco de dados?
Postei o código no pastebin, dê uma olhada se puder.
http://pastebin.com/vdr3mtzw
Comment: não rola.. a coisa é complexa. Você pode reduzir a complexidade de uma  solução adicionando um campo que identifique a "idade" do registro. A lógica é conseguir identificar qual o registro mais recente. Sugiro um campo id numérico de auto incremento ou um campo de data (date_created). Particularmente usaria data.  Mãos na massa! Procure resolver o seu trabalho.
Comment: Eu pensei que fosse a mesma coisa de um sistema de cadastro, que se o usuario já existir ele não armazena.. no meu caso eu só quero, caso exista, incremente um numero no final.
Comment: Incrementar um número numa primeira ocorrência é simples. O problema é se precisar de um segundo incremento. Exemplo de slug "slug-teste". Suponha que já exista, então o novo ficaria como "slug-teste1". Agora suponha que novamente tente cadastrar "slug-teste". Como vai conseguir saber se já não existe o "slug-teste1"? E a coisa vai embora, "slug-teste2", "slug-teste100", "slug-teste2000".. Sacou? O modelo de negócio de um cadastro de usuário é bem diferente da lógica do negócio que vc quer. Talvez precise mudar a lógica do negócio ou fazer o que sugeri ou encontrar alguma outra solução. Enfim.
Comment: Tem alguma ideia diferente do incremento em cada slug?
Se houver algo que me facilite, algum termo ao final, não sei, algo do tipo.. estou aberto a sugestões!
Comment: em primeiro lugar, não gosto da ideia de incremento e tampouco da técnica de usar o slung como identificador de um registro. Poderia usar Id numérico único. Assim, eliminaria esse problema com slung. Com ID numérico como identificador, as URLs teriam que ficar como `site.com/artigo/1/titulo-de-teste`. Quando houver um nome exatamente igual a um existente, não conflitaria a URL devido ao ID: `site.com/artigo/2/titulo-de-teste`
Comment: outra técnica muito utilizada é diferenciar as URLs pela data de cadastro. Seria algo assim `site.com/artigo/20151207/titulo-de-teste`. Quando surgir um titulo igual, porém em dia diferente , ficaria assim `site.com/artigo/20160201/titulo-de-teste`. Sacou? A lógica nisso é que dificilmente será cadastrado um mesmo titulo no mesmo dia. Mas isso depende muito do seu modelo de negócios.  Por fim, há N soluções. Aqui nos comentários forneci diversas dicas e acho que é o suficiente para vc se virar. Afinal isso é o seu trabalho.
Comment: De qualquer forma, obrigado por ajudar.
As chances de ocorrer uma duplicação de slug serão mínimas. Porém, é sempre bom estar preparado e por isso decidi postar a dúvida, só não imaginei que fosse tão complexa.
Answer: Primeiramente, para manter a consistência do banco de dados, você poderia adicionar a restrinção UNIQUE para a coluna 'tabela.slug', dessa forma seria impossível haver dois slugs iguais nesta tabela. Agora o outra solução é verificar se o slug a ser inserido já existe, para evitar que uma exceção seja disparada. No momento lembro de duas:
1 - Selecionar a primeira slug na tabela que corresponda com a slug esta tentando inserir:
SELECT slug FROM table WHERE slug = $slug LIMIT 1

Se o resultado por vazio, significa que você pode inserir a slug.
2 - Adicionar um bloco try-catch para capturar a exceção caso ela ocorra. Se ocorrer, você retornará um aviso ao usuário de que o título já existe e que ele deve altera-lo.
Uma dica: No exemplo que citou na pergunda você adicionou a variável $slug diretamente na query, o pode ocasionar em uma vulnerabilidade de SQL Injection, portanto, passe a utilizar Prepared Statements para evitar esse problema, pelo menos nos casos mais comuns, nível 1 e 2.
@update
Primeiramente vamos começar convertendo todas as iniciais de cada palavra do título para maiúscula, por padronização, já que o usuário pode digitar tudo minísculo. Uma função para isso seria:
function title($str)
{
    return mb_convert_case($str, MB_CASE_TITLE, 'UTF-8');
}

Usuário informa o título "aprenda a divulgar sua empresa nas redes sociais".
O retorno da função será "Aprenda A Divulgar Sua Empresa Nas Redes Sociais".
Para o slug, podemos utilizar a seguinte função:
function slug($title, $separator = '-')
{
        $title = toAscii($title);
    $flip = $separator == '-' ? '_' : '-';

    $title = preg_replace('!['.preg_quote($flip).']+!u', $separator, $title);

    $title = preg_replace('![^'.preg_quote($separator).'\pL\pN\s]+!u', '', mb_strtolower($title));

    $title = preg_replace('!['.preg_quote($separator).'\s]+!u', $separator, $title);

    return trim($title, $separator);

}
Passando o título para a função slug, obteremos a seguinte string:
"aprenda-a-divulgar-sua-empresa-nas-redes-sociais"
O arquivo completo das funções necessárias pode ser encontrado aqui e elas foram retiradas daqui. Apenas trasformei o paradigma, de orientado a objetos para procedural, que é o que está utilizando, pelo menos é o que penso.
Agora precisamos saber quantos resultados para esse slug existe na tabela X do banco de dados Y, referente a coluna slug.
SELECT COUNT(*) as num FROM tabela WHERE slug LIKE '%aprenda-a-divulgar-sua-empresa-nas-redes-sociais%'

Com esse número em mãos, podemos fazer alterar o slug a ser inserido na tabela:
$slug = $slug . '-' . $num;

"aprenda-a-divulgar-sua-empresa-nas-redes-sociais-1"
Daí fazemos a inserção no banco de dados.
Uma outra maneira, bem mais adotada, é adicionar um número baseado na data e tempo ou outra numeração que garanta a unicidade do slug.
Ex:
$slug = strrev(date('dmYHis')).$slug;

Também tornar único na tabela a combinação do slug com data de criação do registro, desse modo slugs iguais seriam permitidos. E quanto a URL, o que faço para diferencia-las?
www.mysite.com/posts/{slug}/{id}
www.mysite.com/posts/aprenda-a-divulgar-sua-empresa-nas-redes-sociais/1547
www.mysite.com/posts/aprenda-a-divulgar-sua-empresa-nas-redes-sociais/1550
olhardigital.uol.com.br/noticia/o-facebook-pretende-livrar-seu-feed-de-noticias-de-virais-que-voce-nao-quer-ver/53511
ou
www.mysite.com/posts/{id}-{slug}
www.mysite.com/posts/1547-aprenda-a-divulgar-sua-empresa-nas-redes-sociais
www.mysite.com/posts/1550-aprenda-a-divulgar-sua-empresa-nas-redes-sociais
Nesse último caso você precisaria de uma função para separar o slug da id, utilizando o id para resgatar os dados no banco de dados.
Comment: Desculpe a ignorância, mas não sei se reparou que eu pedi ajuda para converter o campo SLUG(TEXT) para UNIQUE, pois quando tento sempre dá erro..
Comment: Desculpe-me também, respondi sem compreender o que precisava. Se o que precisa é à respeito da geração de slug a partir da quantidade de tuplas que possuem a mesma substring na tabela, então editarei a minha resposta. Ex: um usuário cadastra um post com o titulo "Formas de Ampliar Seu Negócio Online" (o slug seria "formas-de-ampliar-seu-negocio-online"), e depois de um tempo, o mesmo ou outro usuário decidem criar um post com o mesmo título, o que resultaria no slug "formas-de-ampliar-seu-negocio-online-1". Correto?
Comment: Perfeitamente correto!
Porém, já não faço mais ideia de como transformar o campo slug(text) em UNIQUE, muito menos de como saber se a slug já existe na coluna SLUG do meu banco de dados.
Tem alguma forma de entrar em contato?
Comment: Se precisar de ajuda nesse problema: firstname.lastname@example.com.

Consultar se SLUG já existe


How do I manage 404s for old paths?

Question: We moved to Drupal from another CMS about a year ago, and we still get 100s of "page not found" log entries each day for paths that were for our old site that don't exist on the new site. By checking IPs, I have concluded that most of these are from Google's indexer, but not all.
I add redirects when I can, but most of the links are to some meaningless tokenized path that our old CMS used. I feel like there is probably something I should be doing to flag bad paths for Google/SEO/whatever.
Is there a best practice for what to do with old broken links?
Answer:
Is there a best practice for what to do with old broken links?

Redirect as much links as you can to existing pages using URL aliases.
Find out what pages are linking to your website on the old URLs, see if you can get them adjusted by contacting the webmaster (using a backlink indexing tool like Open Site Explorer or Majestic SEO).
For other links you have the HTTP 404 status code. Sometimes you just can't redirect the links...
Comment: Cool, thanks for those tools. They will helpful. I had a feeling that this wasn't as simple as "install this module"!
Answer: If most of the broken links are coming from search engines, I highly recommend installing and XML sitemap module.

The XML sitemap module creates a sitemap that conforms to the sitemaps.org specification. This helps search engines to more intelligently crawl a website and keep their results up to date. The sitemap created by the module can be automatically submitted to Ask, Google, Bing (formerly Windows Live Search), and Yahoo! search engines.

And if you're not using Redirect for your redirects, I would recommend it, as it simplifies creating the redirects.
Comment: When the search engine finds a link to your website on a different site, it will eventually be crawled, unless blacklisted. Having a sitemap doesn't help with this, you'll have to contact the webmaster of the site that's linking to you. A sitemap is a tool that helps bots discover (new) links.
Answer: Not sure if it is the "best", but another practise is to prevent the problem from happening where possible. To do so, use the Rules module, as described in my answer to "How to use the Rules module to implement a custom redirect for an outdated URL?". It includes a sample rule (in Rules export format), which is using Rules Event "Drupal is initializing" (that's the clue to make it work).
That answer also explains how by using the Rules URL Argument module, you can even further enhance such redirects.

How do I manage 404s for old paths?


why wont my plot come out properly (plots in R)

Question: I have a simple data frame that I made by binding two columns from another larger table (with cbind). Both my columns have numeric values. Column 1 (education) has 5 possible values (1=no school, 2=high school, 3=undergrad, 4=masters, 5=PhD). Column 2 (answer) has 4 possible answers. I want to make a plot that shows me the instances of the answers, that somehow visualizes that for instance there were 500 people who had level 2 education and answered 2, whereas 100 people who had level 3 education answered 2, and only 10 people with level 4 education answered 2. And then 1000 who had level 3 education answered 5, and 100 who had level 4 education answered 5 etc etc.
When I use "table" the numbers come out right:
    1   2   3   4   5
1  75 142 206  71  41
2 179 432 570 250 139
3 177 503 669 417 254
4 113 235 342 292 227

But no plot I've tried shows anything useful. I've tried plot, boxplot, hist, mosaicplot... do I need to use another plot? Is there something else going on?
Answer: For fun, a base graphics alternative:
m = matrix(c(75, 142, 206,  71,  41,
             179, 432, 570, 250, 139,
             177, 503, 669, 417, 254,
             113, 235, 342, 292, 227), nrow=4, byrow=T)

barplot(t(m), names.arg=1:4, legend.text=c("no school", "high school", "undergrad","masters","PhD"), args.legend=list(x='top', inset=c(0,-0.3), ncol=2, cex=0.6))

Answer: Is this what you are looking for?
library(reshape2)
library(ggplot2)
df <- read.table(text=("1   2   3   4   5
1  75 142 206  71  41
2 179 432 570 250 139
3 177 503 669 417 254
4 113 235 342 292 227"), header = T)
df$Answer <- 1:4
df <- melt(df, "Answer")
df$variable <- factor(df$variable, labels = c("no school", "high school", "undergrad","masters","PhD"))
names(df)[2] <- "Education"
ggplot(df, aes(x = Answer, y = value)) +
geom_bar(stat = "identity", aes(fill = Education)) +
ylab("Answer frequencies")

Comment: Yes! That's exactly what I am looking for. I was sure that I could do that without libraries. I guess it's time I learn how to use ggplot. Thank you so much for this. I'll study your code.
Comment: What if I changed 1 into a string like "no education" etc for all levels, would that then allow me to plot my data differently or would it be the same?


Java Image over image has white b/g even though it's a png

Question: As seen below, I have a BufferedImage over another BufferedImage.  They are both pngs and I would like there to be no background on the overlayed image.  I'm sure there's so way to do this, but am unsure of where in the api.
Here's the method in question:
<code>private static BufferedImage finalizeImage(BufferedImage originalImage, String tokenImage, Integer occurrences, int height, int width, int type){

    //Font font = new Font("Courier New", Font.PLAIN, 12);
    BufferedImage resizedImage = new BufferedImage(width, height, type);
    Graphics2D g = resizedImage.createGraphics();
    FontMetrics fm = g.getFontMetrics();
    int strWidth = (fm.stringWidth(tokenImage));
    int imageWidth = resizedImage.getWidth();
    int textBegin = (imageWidth - strWidth) / 2;
    //g.setFont(font);
    g.drawImage(originalImage, 0, 0, width, height, null);
    g.setColor(Color.black);
    int textHeight = (fm.getAscent() + (TOKEN_HEIGHT - (fm.getAscent() + fm.getDescent())) / 2);
    g.drawString(tokenImage, textBegin, textHeight);

    //for multiple occurrences
    try {
        BufferedImage numOnSubscript = ImageIO.read(Thread.currentThread().getContextClassLoader().getResourceAsStream("images/ui/tokens/subscript.fw.png"));
        g.drawImage(numOnSubscript, width - 20, height-20, 20, 20, null);
        g.setColor(Color.white);
        g.drawString(occurrences.toString(), width - 16, (height-20)*2 - 1);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    g.dispose();

    return resizedImage;

}
</code>
Here is what is happening.
Answer: I found my problem.  Of course, it's the silliest thing.  I had a white background on as default in fireworks :-/


Curl vs requests python 3

Question: I am doing a curl post request to a service:
curl -v --data "cp4=2765&cp3=350&method%3AsearchPC2=Procurar" https://www.ctt.pt/feapl_2/app/open/postalCodeSearch/postalCodeSearch.jspx

I can see that it successful because we have a div with the results in the response body:
...

Rua Sacadura Cabral

Ímpares de 11 a 233

Galiza

2765-350 ESTORIL

...

The wired thing is that if I do it with python + requests, it doesn't give me the expected result as the curl above does, I even tried to set the user agent to the same as curl:
import requests as r

headers_p = {
    'User-Agent': 'curl/7.47.0',
    'Host': 'www.ctt.pt'
}

payload = {'cp4': 2765, 'cp3': 350, 'method':'',  'searchPC2': 'Procurar'}
req_p = r.post('https://www.ctt.pt/feapl_2/app/open/postalCodeSearch/postalCodeSearch.jspx', data=payload)
print(req_p.text) # doesn't have the the same content as the curl, I need the html block above

But it fails, the server doesn't send me the results html block
Comment: `headers = {'Content-Type': 'application/xml'}` use this snippet and pass this as part of `r.post` as `headers=headers` . See if you are getting output.
Comment: Thanks @Haranadh. Nop, didn't work. The curl, the one that works, sends `Content-Type: application/x-www-form-urlencoded` on the request header
Comment: you can print the response object and see the data. I am able to run in the `python3` also. I can see some data. But not seeing specific html content as part of result.  My python version is `Python 3.4.3`, installed in venv.
Comment: I know that @KeerthanaPrabhakaran, is there something unclear about the question? I just saying it's diferent from the curl request, I want the same response body, with the block html posted above
Answer: In case you have a proxy configured at your environment, define it at your session/request as well.
For example with session:
    my_proxies = {
        'http': 'http://myproxy:8080',
        'https': 'https://myproxy:8080'
    }

    session = requests.Session()
    request = requests.Request('POST', 'http://my.domain.com', data=params_template, headers=req_headers, proxies=my_proxies)
    prepped = session.prepare_request(request)
    response = session.send(prepped)

see documentation:
request http://docs.python-requests.org/en/master/user/quickstart/
session http://docs.python-requests.org/en/master/user/advanced/
Another option can be the security, in case you use have a problem with the ssl, add verify=False
For example:
    response = requests.get('http://my.domain.com', verify=False)

Answer: When I try the following i am getting output.
import requests as r
from requests import Response

headers = {'Content-Type': 'application/xml'}

payload = {'cp4': 2765, 'cp3': 350, 'method':'',  'searchPC2': 'Procurar'}
given_url = 'https://www.ctt.pt/feapl_2/app/open/postalCodeSearch/postalCodeSearch.jspx'
req_p = r.post(given_url, data=payload, headers=headers)

print req_p, req_p.text

Try to parse the content as you need. I am getting the output.
I tried to change the headers = {'Content-Type': 'application/x-www-form-urlencoded'} still i am getting some output.
Note: I am using python2.7
Comment: Thanks. The problem remains, I'm getting the out as well, just it doesn't give the html I want, unlike curl that It's outping the expected, I just need to why/how to make it work, and why it works with curl but doesn't with requests.
Answer: Please use the below code as the server is searching for json format.
import requests as r
import json
from requests import Response
headers = {'Content-Type': 'application/json'}
payload = {'cp4': 2765, 'cp3': 350, 'method':'',  'searchPC2': 'Procurar'}
data_json = json.dump(payload)
given_url = 'https://www.ctt.pt/feapl_2/app/open/postalCodeSearch/postalCodeSearch.jspx'
req_p = r.post(given_url, data=data_json, headers=headers)
print req_p, req_p.text

Curl vs requests python 3


How to install packages with pip and a requirements.txt file ignoring some packages

Question: I'm doing a script to automatize the downloading and the installation of a repository from GitHub. However, my environment needs some special dependencies which aren't specified in requirements.txt file. So, my goal is:

Download the repository with git clone
Install dependencies with pip install -r requirements.txt but
ignoring the bad dependencies
Install ignored dependencies with my correct version of them (I use
wget file.whl and pip install file.whl)

My question is, how can I ignore the packages from the requirements.txt file with the pip install command? I know that I can open file, comment or erase that lines and install with pip, but I want to achieve with a full automatization task.
Comment: if you are programmer then use `Python` to automate it. Write script which will get only good dependencies and write it in new file `.txt` - and use this new file with `pip`. You can also read every line from file and run every line separatelly with `pip install module==version` (ie. using `subprocess.run()` ). And this way you can catch errors and try to install from different place.
Comment: possible duplicate of https://stackoverflow.com/questions/22250483/stop-pip-from-failing-on-single-package-when-installing-with-requirements-txt
Answer: Solution 1:
If the file.whl have the same version as your ignored packages, you can just flip 2 and 3 and it should be ok.
Solution 2:
if the file.whl have a different version than your ignored packages, you can remove them dynamically from the pip file. For example (Linux), using:
pip install -r $(grep -v '^ *#\|^pkg1\|^pkg2' requirements.txt | grep .)
Similar procedure can be done in powershell in windows.
Note: solution 2 code was taken directly from https://www.shellhacks.com/pip-install-requirements-exclude-specific-packages/
Comment: It doesn't work for me. When I execute with my package, an error is generated:
_ERROR: Invalid requirement: '#'_
But you gave me a idea to do it in another way which works:
`grep -v '^ *#\|^torch' requirements.txt | grep . >> requirements2.txt`
`pip install -r requirements2.txt --no-cache`
So thank you.
Comment: Great! Glad that I can help. I am mostly a windows user so I use powershell (which works on windows and linux) most of the time. I just copied the command from the website :)


Statistical hypothesis testing of beta distribution

Question: We have $X_1$ and $X_2$, where $X_i \sim \mathrm{Beta}(\theta,1)$, $f_{X_i}=\theta X^{\theta -1}$ with $0<x<1$.
$H_o: \theta =1$ vs $H_a = \theta = 2$
The rejection region is $C = \{ (x1,x2) \in (0,1)\times (0,1)  ; x_1 \ x_2  \geq \frac{3}{4}  \}$.
I need to proof that $P( \text{error type 1}) = \alpha = \frac{1}{4} + \frac{3}{4} ln( \frac{3}{4})$.
My first idea is to use the power function $\alpha = \Pi_{\gamma}(\theta_o)= P(x_1 x_2 \geq \frac{3}{4} \  |  \ \theta = \theta_1 = 1)$, and I need to know the distribution of $X_1 X_2$, I have found that is complicated to know that distribution.
Answer: It is not difficult to compute the desired probability.  Under the null hypothesis, $X_i \mid H_0 \sim \operatorname{Beta}(1,1)$ is uniformly distributed; thus the probability that the product $X_1 X_2$ is at least $3/4$ is equal to the area in the unit square above the hyperbola $x_1 x_2 \ge 3/4$; i.e., $$\begin{align}
\Pr[X_1 X_2 \ge \tfrac{3}{4} \mid \theta = 1]
&= \Pr\left[(3/4 \le X_1 \le 1) \cap \left(\frac{3/4}{X_1} \le X_2 \le 1\right) \Bigl| \, \theta = 1\right] \\
&= \int_{x_1 = 3/4}^1 \!\!\!\Pr\left[ \frac{3/4}{x_1} \le X_2 \le 1 \, \Bigl| \, (X_1 = x_1) \cap (\theta = 1) \right] f_{X_1 \mid \theta = 1}(x_1) \, dx_1 \\
&= \int_{x_1 = 3/4}^1 \left(1 - \frac{3/4}{x_1}\right) \, dx_1 \\
&= \left[x_1 - \frac{3}{4} \log x_1 \right]_{x_1 = 3/4}^1 \\
&= \frac{1}{4} \left( 1 - 3 \log \frac{4}{3} \right) \\
&\approx 0.034238. \end{align}$$


Como usar getche() com do-while em C?

Question: Eu tenho a seguinte variável :
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

char op;

E estou pedindo para o usuário entrar com um caractere :
printf("\nDeseja realizar novo teste (s/n) ?");
op = getche();

Caso o usuário digitar s o seguinte código irá aparecer :
    printf("\nDigite um número para o dividendo : \n");
    scanf("%d", &dividendo);
    printf("\nDigite um número para o divisor : \n");
    scanf("%d", &divisor);

E caso o usuário digite n, o programa sai, mas caso digite qualquer outro caractere, ele aparece, a mesma mensagem pedindo para para realizar novo teste.
Código :
do {

printf("\nDeseja realizar novo teste (s/n) ?");
op = getche();

}while(getche() != 's' || getche != 'n');

Ele continua rodando o do-while, mesmo se eu colocar os caracteres s ou n, como posso fazer funcionar ?
Answer: Pra ler um caractere, basta usar scanf mesmo.
char ch;
scanf(" %c", &ch);
printf("%c", ch);

Repare que no scanf tem um espaço ants do %c. Isso serve pra indicar que a função ignore todos os espaços em branco adicionais que vem do teclado e leia apenas o caractere. E evite usar getche, eu acho que essa função não é padrão do C.
Edit:
char op;
while (1) {

    printf("\nDeseja realizar novo teste (s/n) ?");
    op = getche();

    if (op == 's' || op == 'n') {
        printf("\n\nVc escolheu '%c'", op);
        break;
    }
}

Comment: Eu prefiro usar scanf também, mas é um exercício da Faculdade, e pede claramente para usar getche, mesmo que eu não queira usar. E está só dando problemas com o getche().
Comment: Tente usar um loop infinito e verificar o caractere com `if`. Teste aqui com o Visual Studio 2015 e funcionou. Atualizei o código.
Comment: Sim, funcionou. Muito obrigado.
Answer: Acho que o problema está no fato de você estar usando a função na condição, quando na verdade você teria que usar a variável na condição do do-while. Tente dessa forma e veja o que acontece:
do {

printf("\nDeseja realizar novo teste (s/n) ?");
op = getche();

}while(op != 's' || op != 'n');

Comment: @Mondial, você fez o import da biblioteca conio? Se não, coloca no cabeçalho do script: #include
Comment: Também não funcionou, ele fica perguntando 3 vezes a mesma coisa, e não da output correto. Ele não consegue pegar o sim ou não, ou outro caractere, e fica um loop infinito.
Comment: Sim, eu fiz o import da biblioteca conio.
Comment: Você ajudou também, muito obrigado.

Como usar getche() com do-while em C?


Remove shadow of triangle from overlapping area above content?

Question: I wanted to remove inner border or box from the box, as shown below
below image:
Note: if possible i want to retain my code with bit addition
Note2: i don't want to remove box-shadow on element or :after

here is my codepen:https://codepen.io/anon/pen/wEwgRR

#messagebox,#messagebox2{
  width:400px;
  height:150px;
  background:red;
  margin: 0 auto;
  position:relative;
  color:#fff;
  padding:12px;
  font-size:18px;
  border-radius:3%;
  box-shadow:0px 8px 9px black;
  margin-top:80px;
}

#messagebox:after{
  content:'';
  position:absolute;
  width:50px;
  height:50px;
  background:red;
  bottom:-25px;
  right:65%;
  transform: rotate(45deg);
  color:#fff;
  box-shadow:0px 5px 9px black;
}

#messagebox2:after{
  content:'';
  position:absolute;
  width:50px;
  height:50px;
  background:yellow;
  bottom:-25px;
  right:65%;
  transform: rotate(45deg);
  color:#fff;
  box-shadow:0px 5px 9px black;
}

   hello world

   hello world

Please help me thanks in advance  !!!!
Comment: Duplicate of https://stackoverflow.com/questions/30299093/speech-bubble-with-arrow/30299094#30299094
Answer:
Create another layer using ::before pseudo element of same width / height as parent.
Apply shadow on this layer instead of parent element.
Add some negative z-index value to place it below the ::after pseudo element i.e arrow.

Demo:

.messagebox {
  width:400px;
  height:150px;
  background:red;
  margin: 0 auto;
  position:relative;
  color:#fff;
  padding:12px;
  font-size:18px;
  margin-top:80px;
}

.messagebox::before {
  box-shadow:0px 8px 9px black;
  position: absolute;
  border-radius:3%;
  content: '';
  z-index: -2;
  bottom: 0;
  right: 0;
  left: 0;
  top: 0;
}

.messagebox:after{
  content:'';
  position:absolute;
  width:50px;
  height:50px;
  background:red;
  bottom:-25px;
  right:65%;
  z-index: -1;
  transform: rotate(45deg);
  color:#fff;
  box-shadow:0px 5px 9px black;
}

.messagebox2:after{
  content:'';
  position:absolute;
  width:50px;
  height:50px;
  background:yellow;
  bottom:-25px;
  right:65%;
  transform: rotate(45deg);
  color:#fff;
  box-shadow:0px 5px 9px black;
}

   hello world

   hello world

Answer: Try this out

.messagebox {
  background: red;
  border-radius: 12px;
  box-shadow: 0 4px 4px 0 rgba(0, 0, 0, 1);
  box-sizing: border-box;
  color: white;
  height: 150px;
  margin: 20px auto;
  max-width: 400px;
  padding: 16px;
  position: relative;
}

.messagebox:after {
  border: 16px solid black;
  border-color: transparent transparent red red;
  bottom: -30px;
  box-shadow: -4px 4px 4px 0 rgba(0, 0, 0, 1);
  box-sizing: border-box;
  content: "";
  height: 0;
  left: 50%;
  margin-left: -16px;
  position: absolute;
  transform: rotate(-45deg);
  transform-origin: 0 0;
  width: 0;
}

Hello World!


Machine learning with weighted / complex survey data

Question: I have worked a lot with various nationally representative data.  These data sources have a complex survey design, so the analysis requires the specification of stratification and weight variables.  Among the data sources that are within my area of study, machine learning tools have not been applied to them.  One obvious reason is that machine learning methods (currently) do not take into account weight and stratification variables.
The goal of the weighted / stratified analyses is to obtain adjusted population estimates, which is different than the goal / purpose of machine learning.  What thoughts do people have about using the nationally representative data sources and ignoring the weight and stratification variables?  In other words, what would be your thoughts if you reviewing a machine learning study that was used nationally representative data but ignored the weight and stratification variables, assuming that the researcher / author was up-front about this methodological decision and was not making claims of nationally representative results?
Thanks in advance!
Comment: not accounting for the clustering variables means you will be more confident of your results than you should be.  not accounting for the weights completely strips the generalizability.  if you are not making representative claims, what then are you making claims of?  :)
Comment: @AnthonyDamico, indeed, that makes sense. However, wouldn't the generalizability be equivalent to convenience samples which are ubiquitous in machine learning studies.  Not using weights prevents would prevent population estimates to be derived, but won't the correlational structure remain intact?  Thanks in advance!
Comment: the correlational structure is the problem: survey data is sampled in clusters, not by srs. so it is often _overcorrelated_ and variances need to be calculated with that in mind.  people create new methods for complex-sample data all the time; look for papers with `survey` and `design-adjusted` keywords and figure out what makes sense  :)
Comment: if you have a linearized design, you could switch it over to a replicate-weighted design with `survey:::as.svrepdesign` and then somehow force your ml algorithm to sample based on the replicate weights alone -- still needs to be run hundreds of times, but it might make dealing with the clusters easier?  :)
Comment: @AnthonyDamico, Thanks for the clarification on the issue of the correlational structure -- that is a helpful perspective. For some relationships, the clustering will most certainly be a problem. Assume that I ignored the issue of clustering in a ML approach but subsequently explored some of the correlational structures with and without the weight and stratification variables using more common regression techniques. Of course, direct comparisons couldn't be made, but it might offer some insight into the extent to which clustering affects the correlational structure. Any thoughts on that?
Answer: I work for a health care company on our member satisfaction team where weights are constantly applied to match the sample to the populations of our service regions. This is very important for interpretable modeling that aims to explain magnitude of relationships between variables. We also use a lot of ML for other tasks, but it seems like you may be wondering if this is important when using machine learning for prediction.
As you hinted most machine learning techniques were not developed for the purpose of explaining relationships, but for predictive purposes. While a representative sample is important, it may not be critical..until your performance tanks.
If algorithms have sufficient samples to learn respondent types, they will be able to predict new respondents' class (classification) / value (regression) well. For example if you had a data set with 4 variables, height, weight, sex, and age, your algorithm of choice will learn certain types of a person based of these characteristics. Say most people in the population are female, 5'4", 35 years old, and 130 pounds (not fact, just roll with it) and we are trying to predict gender. Now say my sample has a low representation of this demographic proportionally, yet still has a high enough number (N) of this type of person. Our model has learned what that type of person looks like though that type of person is not well represented in my sample. When our model sees a new person with those characteristics it will have learned which label (gender) is most associated with said person. If our sample shows that those characteristics are more related to females than males and this matches the population then all is well. The problem arises when the sample's outcome variable does not represent the population by so much that it predicts a different class / value.
So when it comes down to it, testing your predictive ML model on representative data is where you can find out if you have a problem. However, I think it would be fairly rare to sample in such a biased way that prediction would suffer greatly. If accuracy / kappa statistic / AUC is low or RMSE is high when testing then you might want to shave off those people that over-represent demographics of interest given you have enough data.


What instrument is this?

Question:
I thought it was a tuba, and it sounds like one, but looking around for pictures it seems the tuba is a smaller instrument. Is this an unusual type of tuba, or what?
Answer: Looks like a Sousaphone to me.  :)
Comment: i.e. Marching Tuba--and this one is made out of fiberglass instead of brass.
Comment: This. A sousaphone is, for all intents and purposes, a BBb tuba, just arranged differently so you can sling it over the shoulder and march around with it. There is sometimes a difference in the rate of growth of the tubing and certainly a difference in the bell, which can affect the timbre of the instrument, but as the example from the picture is made of fiberglass I would think that would have an even greater effect.
Answer: That is a Sousaphone, but this one is made mostly of fiberglass plastic (except for the small brass pipes and valves.) Other Sousaphones are made with brass parts (sometimes silver plated.) It is not "Home-Made" - Sousaphones are manufactured by several music instrument companies in the US, Europe and Asia.
Sousaphones are usually pitched in BBb (old ones were also available in EEb) but Tubas are made in BBb, CC, EEb and F. (Euphoniums are usually Bb - just slightly smaller than the F Tuba, and Tenor Horns are Eb.)
Answer: i think the man in the photo is a member of "Los luthiers" (a group from argentina). if he indeed is, i bet he built his instrument quite probably based on a tuba. It is not uncommon for them to build their own instruments, with cans, bottles, etc.
Comment: He indeed is from Les Luthiers, I forgot to mention in the question.
Comment: My friend has a Souza exactly like that. I doubt the instrument in the picture is hand made.
Comment: yup a sousaphone indeed as cornbead ninja says
Answer: Looks like a Tuba/Sousaphone.  The smaller Tuba you're referring to is probably a Tenor Tuba/Euphonium.
Comment: More information about the Sousaphone- http://www.en.wikipedia.org/wiki/Sousaphone

What instrument is this?


LanDesk, server patching trouble

Question: I've a server that contains lanDesk and i use it for patching other servers. But i've a trouble with a server (we name it r2d2), in lanDesk it says that the patch is succefull but on r2d2 it says that the patch is not installed.
How can i check it on r2d2 ?
A manual installation is preferable ?
Thank you

UPDATE :
A mate gave me a CMD command that returns all the updates on the server.
<code>WMIC QFE > C:/patches.txt
</code>
But the patch isn't in this list.
Answer: Actually, a manual installation and a reboot worked. The problem came from LanDesk. I'm still looking why LanDesk refused to patch the updates.

LanDesk, server patching trouble