How to get "empty line items" in Commerce, similar to Ubercart?

Question: In Ubercart, there is a little feature for adding "empty line items" to an admin created order. This allowed an admin to manually enter a custom title for the line item and a custom amount. Essentially allowing you to add line items without going through the process of creating a product first, then attaching it to the order. Very helpful for creating invoices for custom services. Is there any way I can get this feature in Drupal Commerce?
This is how it looks and works in Ubercart:
Answer: In Drupal Commerce, we made the decision to add line item type dependent callbacks to the line item API. A product line item will function differently from a shipping line item will function ... etc. As a side effect, this means there is no such thing as a "generic" line item, just like there is no such thing as a typeless node.
What needs to happen, if it doesn't already exist, is a small contrib module could be made that adds a basic line item type whose "line item add form" in the order edit page lets you specify all the information needed to manage and display that line item. Where it's gonna break down are things like pricing rules - should these line items have taxes? Should other discounts apply? Or display rules - should these show up on customer order pages?
There is no such feature in core (as you can see, it'd be a small contrib, but it wouldn't be trivial to make), but if it were tested and proved as a concept in contrib, I don't see why we couldn't consider it for inclusion in Commerce 2.x.
Comment: So, how does your Commerce Customizable Product module allow an admin to set whatever customizable items are need to the product when they adds it to an admin created order?
Comment: I just tried do this by creating a custom line item with Commerce Customizable Product. Then setting a textfield for user input (in theory this could be a description of the custom service). Then created a generic custom product. However it appears that adding the product to an admin created order reference the product entity and not the node display, therefore an admin cannot enter text into this field. Essentially it appears that if you have a customizable product then you cannot have something like a phone in order and let an admin create it. It must be done through the add to cart process.
Comment: Seems to me that the Line items field on the order entity should be a node reference, rather than a line item reference with a modified add to cart form.
Comment: any response to this?
Comment: I'm not sure what a node reference would be doing here - there's a line item entity, and that's what's being referenced. Commerce Customizable Products works by inheriting the callbacks from the core Product line item type. It lets you create new product line item types in cases where you need different line item types to contain different fields. The module itself doesn't define any of those callbacks or UI components; it just uses what's in the Product Reference module.
Comment: So, essentially there is no way for an admin to add a customizable product (with the customizations included) to an admin created order? (i.e. customizable products can only be added by the end user going through the cart process)
Comment: Not sure I said that. I'd give it a play - you should be able to select any line item type on the admin order edit form.
Comment: I can select it but I can't customize the product. Say the product was a t-shirt and it allowed the end user to customize it with their own text. Going to admin/commerce/orders/add I can reference and add the product entity, but I cannot add the custom text. However, an end user would be presented with this text field if they were adding this product through the standard add to cart method.
Comment: Ok, yeah, I was just chatting with someone about that drawback in IRC today. I'm pretty sure if you were using the Inline Entity Form widget for the line item reference field instead of the core line item manager widget it would work.
Comment: Ah yes. That gets me one step closer. It allows me to add new products, but I cannot add existing products. Trying to edit the field settings to allow for adding existing products, I am met with "The field Line items is locked and cannot be edited." I manually removed the lock on the field in the DB but it appears that the inline entity form doesn't support "add existing" like it does for product entities and node displays. arg! so close :)
Comment: @RyanSzrama There's a module in sandbox right now for exactly this. Do you have a few moments to review it to get approved? https://drupal.org/node/2093997
Answer: I've just created and submitted a module that might suit your needs. It is currently in sandbox. Let me know!
Comment: Module is now currently active: [Commerce Basic Line Item](https://drupal.org/project/commerce_basic_line_item)
Answer: Maybe a workaround could be to create a generic product and use Commerce Customizable Products. Here is an excerpt about it from the module's project page:

Drupal Commerce allows you to sell customizable products that require customer input when added to the cart. Use cases for this functionality include:

Business cards that require contact information and a logo upload.
Event registrations that require attendee information.
Donations the allow the customer to specify a donation amount.

What do you think about?
Comment: This is as I suggested above in my comment to @Ryan Szrama however the customizable portion of the product is not exposed to an admin created order.


Integers aren't open sets

Question: So I am solving the following question in apostol Determine all accumulation points of the following sets in $R^1$ and decide whether the sets are open or closed (or neither).
All integers:
The set of integers doesn't contain an accumulation point of Z I will do it by contradiction suppose x $\in \mathbb{R}$ is an accumulation point so we must have all balls of radius r > 0 to have points in common with integers in particular consider B(x,x/2) we have $(B(x,x/2) - {x}) \cap \mathbb{Z} = \emptyset$, so set $\mathbb{Z}$ doesn't contain an accumulation point.
Now I want to prove that our set Z is open I proved it is closed since if we consider $\mathbb{R} - \mathbb{Z} = \bigcup_{n \in \mathbb{N}}(n, n + 1)$ is union of open sets which is open. I already see the logic of how to prove that our set Z isn't open since for every open ball we will always have points in irrational numbers but I can't seem to be able to prove it rigorously.
Comment: $\mathbb{Z}$ is closed set in $\mathbb{R}$. Since $\mathbb{Z}$ contains all accumlation points $\phi \subset \mathbb{Z}$ ($\phi$ is subset of any set)
Answer: To prove $\Bbb{Z}$ is not open, you could show that 1) $\Bbb{R} \setminus \Bbb{Z}$ is not closed or that 2) $\Bbb{Z}$ consists of isolated points.
1) 0 is an accumulation point of $\Bbb{R} \setminus \Bbb{Z}$ because it is the limit of the sequence {1/n}, but since $0 \in \Bbb{Z}$, it is not in $\Bbb{R} \setminus \Bbb{Z}$.
2) Let $a \in \Bbb{Z}$ and consider the open ball $B(a,1/2)=(a-1/2,a+1/2)$. Since $\Bbb{Z}\cap B(a,1/2)=\{a\}, a$ is an isolated point of $\Bbb{Z}$, so it is not an interior point of $\Bbb{Z}$.
The argument with the irrational numbers that you mention is another way of showing no point is interior; I think you could say that any open ball around $a \in \Bbb{Z}$ contains irrational numbers because the set of irrational numbers is dense in $\Bbb{R}$, so the ball is not fully contained in $\Bbb{Z}$.
Comment: About 1), you are correct, a set may be both closed and open. What I was using was not that, but the fact that a set is open if and only if it's complement is closed, so showing the complement is not closed proves that the set is not open.
Comment: About 2), an isolated point cannot be an interior point (because a point is isolated in a set if the set does not contain any open neighborhood of the point, and a point is interior in a set if the set contains a neighborhood of the point). The definition of open set I used was that a set is open if every one of its points is an interior point, so showing that *one* of its points is not interior proves that a set is not open.
Comment: I see I wanted to ask a question about showing it using (1) I was thinking about it but I realized we could have a set that is both open and closed so a set being closed doesn't automatically mean that it is not open correct?
Comment: I also wanted to ask how come showing that $\mathbb{Z}$ constiting of isolated points will automatically prove that is not open ??
Comment: Okay good thanks alot I understand everything perfectly now +1
Comment: You're welcome!

Integers aren't open sets


Can delayed animation attributes override existing ones?

Question: Situation

The DOM element initial state is opacity: 0.
I'm adding animation class to a DOM element. Aside of the animation, this class has an initial state of opacity: 1.

.animation {
    opacity: 1;
    animation(fadeIn 1s 200ms ease-in-out);
}

The animation is executed with a delay of 200ms, and has an initial state of opacity: 0.

@keyframes fadeIn {
  0% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}

Problem
When the animation class gets apended to the DOM element, the element becomes instantly visible for 200ms, after which, the fadeIn animation begins by flickering the DOM element back to invisible state. Contrary to this, I would like for the animation (keyframes) attribute opacity:0 to overwrite the animation class attribute opacity:1 and as a result have a smooth fadeIn animation.
Reason for this approach is older-browser support.
EDIT: Added the actual project code ( for clarification purposes )

@for $i from 1 through 3 {
  &.showAddonColumn#{$i} {

      td:nth-child( #{$i + 1} ) {
          display: table-cell;
      }

      @for $j from 1 through 15 {
          tr:nth-child( #{$j} ) {

              td {

                  .checkable {
                      @include transform-origin(50%, 0%);
                      @include animation(leafShow 1s #{$j*100ms} cubic-bezier(.37,0,.16,.94) 1);
                      @include animation-fill-mode(forwards);
                  }
              }
          }
      }
  }
}

Comment: @luqmaan I totally agree on modernizr. It's just that I'm always hunting for the most elegant approach.
Comment: `Reason for this approach is older-browser support.` You can never fix an old browser. Why not work around the whole problem instead and only apply the animations to modern browsers? Modernizr can detect it with cssanimations. http://modernizr.com/docs/#features-css
Answer: You could manually delay the animation itself:
@keyframes fadeIn {
    0% { opacity: 0; }
    17% { opacity: 0; }
    100% { opacity: 1; }
}

and extend the animation:
animation: fadeIn 1200ms ease-in-out;

Comment: I edited the question so we can further clarify the problem. You'll see there why this approach won't cut it.


Convergence speed of perceptron algorithm

Question: I was reading the convergence proof for the perceptron algorithm. It says under the assumption that there are some $R$, $\theta^*$ with $|\theta^*| = 1$ and $\gamma > 0$, such that $y_t(x_t\cdot \theta^*) \geq \gamma$ and $|x_t|\leq R$ for $t = 1, 2, \dots n$, the perceptron algorithm makes at most $\frac{R^2}{\gamma^2}$ errors.
What I didn't fully understand how $\theta^*$ was related to $x_t$ and how it affected the convergence of PLA. If I scale down all $x_t$ by a factor $k$, then I have $|x_t| \leq \frac{1}{k}R$, but what happens to $\theta^*$ and $\gamma$? Does scaling down $x_t$ gives a smaller upper bound and thus PLA converges faster? I personally believe how fast PLA converges is decided by how data is distributed rather than $|x_i|$, is it correct? Any hint or answer is appreciated, thanks in advance.
Answer: If we scale $x_t$ by a factor $m$ (not using $k$ to prevent any confusion with the number of steps), the inequality becomes $$y_t((x_t/m) \cdot  \theta^*)\geq \gamma/m\rightarrow y_t(x_t'\cdot\theta^*)\geq\gamma'$$
$\gamma$ acts like a margin of the boundary, i.e. how far the samples are off. If we scale the samples, the margin is also scaled. The boundary weights are always normalized, i.e. $||\theta^*||=1$, and isn't affected by scale changes in input, e.g. $x+2y=5$ and $2x+4y=10$ are the same line. Therefore, both $R$ and $\gamma$ are scaled the same way and we have $$k\leq \frac{(R/m)^2}{(\gamma/m)^2}=\frac{R^2}{\gamma^2}$$
So, it doesn't converge faster.


Multiple correct question based on permutation group

Question:
I try to solve this the number of permutation in $S_{n}$ for $n\geq 4$ which are product of two disjoint $2$-cycles is $\frac{n(n-1)(n-2)(n-3)}{8}$.
So after putting $n=5$ and $n=4$ I get different answer. Am I right ?
Please help how to solve this. Thanks.
Comment: @MorganRodgers That's not right, for $a_4$ you also have a product of a $3$-cycle and a $1$-cycle. In fact there are $8$ of these, and $3$ products of $2$ $2$-cycles.
Comment: Ohh thanks@Morgan
Comment: @Morgan how to solve this ?
Comment: @derek holt you get correct answer for $a_4$
Comment: But how you did it please explain.
Comment: @Derek how about the product 1-cycle and 1-cycle or 1-cycle and 2-cycle
Comment: @MusaddiqueKhan Yes, $a_4=11$ and $a_5=50$, but you can do the calcualtion yourself.
Answer: There is an ambiguity in the question. If an element remains fixed, does that count as a 1-cycle?
If we assume it does, then for $n=4$ the only possibilities are type $(12)(34)$ (3 possibilities) or type $(123)(4)$ (8 possibilities, 4 ways of choosing the 1-cycle, then 2 ways of choosing the 3-cycle). So we get $a_4=11$.
For $n=5$ the only possibilities are type $(123)(45)$ (10 ways of choosing the elements in the 3-cycle, then 2 possibilities for each choice, total 20), or type $(1234)(5)$ (5 ways of choosing the 1-cycle, then 6 ways of ordering the elements in the 4-cycle). So $a_5=50$.
If we don't count 1-cycles, then:
For $n=4$ the only possibilities are $(12)(34),(13)(24),(14)(23)$. So $a_4=3$.
For $n=5$ the only possibilities are type $(123)(45)$ and type $(12)(34)$. The first has 20 possibilities (10 ways of choosing the elements in the 3-cycle and 2 possibilities for each choice). The second has 15 possibilities (5 ways of choosing which element remains fixed, then 3 $a_4$ possibilities). Hence $a_5=35$.
Presumably we are meant to adopt the first interpretation (count 1-cycles).
Comment: I don't think there is any ambiguity. People are just not reading it carefully. The two possibilities for $n=5$ are a product of a $3$-cycle and a $2$-cycle, and the product of a $4$-cycle and a $1$-cycle. I get $a_5=50$.


Get data from JSON array within JSON array

Question: I'm trying to get data from a JSON array within a JSON array, but am having little success.
So our server returns a JSON array within a variable called 'msg', which look like this when I console.log it
[{"product":"[{\"imgUrl\":\"/p/332401\",\"prodCartQty\":2,\"prodName\":\"Test Product 1",\"productCode\":\"332401\"},{\"imgUrl\":\"/p/332388\",\"prodCartQty\":2,\"prodName\":\"Test Product 2",\"productCode\":\"332388\"}]","category":"gross_MAX_1","totalCategory":1},{"product":"[{\"imgUrl\":\"/p/332401\",\"prodCartQty\":2,\"prodName\":\"Test Product 1",\"productCode\":\"332401\"},{\"imgUrl\":\"/p/332388\",\"prodCartQty\":2,\"prodName\":\"Test Product 2",\"productCode\":\"332388\"}]","category":"gross_MAX_1","totalCategory":1}]

I then have the following code to pull out the product name but keep getting an undefined error - Uncaught TypeError: Cannot read property 'prodName' of undefined
console.log(msg);
var data = $.parseJSON(msg);
console.log(data);

OBJ = {};
OBJ.apply = function(data) {
    $.each(data, function() {
        $.each(this, function(key, value) {
            console.log(value.product.prodName);
        });
    });
};
OBJ.apply(data);

Any ideas where i'm going wrong?
Thanks
EDIT
I've looked at the parsed variable and I get:-
[Object, Object]
0: Object
category: "restrictedItems_ie-standard-gross_MAX_1"
product: "[{"imgUrl":"/p/332401","prodCartQty":2,"prodName":"Test Product 1","productCode":"332401"},{"imgUrl":"/p/332388","prodCartQty":2,"prodName":"Test Product 2","productCode":"332388"}]"
totalCategory: 1
__proto__: Object
1: Object
category: "restrictedItems_ie-standard-gross_MAX_1"
product: "[{"imgUrl":"/p/332401","prodCartQty":2,"prodName":"Test Product 1","productCode":"332401"},{"imgUrl":"/p/332388","prodCartQty":2,"prodName":"Test Product 2","productCode":"332388"}]"
totalCategory: 1
__proto__: Object
length: 2
__proto__: Array[0]

So the data parses fine but now I need to return the data in product or get the object data in Product into a separate object.
Any ideas? thanks
Comment: Your $.each(this, function(key, value) is pretty useless, if you just want to shop up thfe productname
Comment: Could you not change the format of the response at the server? It seems a little odd having JSON data within JSON data.
Comment: from which server side application you're getting `json` i means you would be getting json from controller action or from service(API)?
Answer: Looks like it needs to be unescaped.
If you paste the JSON in a tool like this JSON formatter, you'll be able to see more clearly how it doesn't like the \s.
Comment: looking at my original variable, after I parse it I get:
Answer: Try this. I had to fix the invalid JSON by escaping the trailing quote on each
\"Test Product 1" <<<<
\"Test Product 2" <<<<

var data = [
    {
        "product": "[{\"imgUrl\":\"/p/332401\",\"prodCartQty\":2,\"prodName\":\"Test Product 1\",\"productCode\":\"332401\"},{\"imgUrl\":\"/p/332388\",\"prodCartQty\":2,\"prodName\":\"Test Product 2\",\"productCode\":\"332388\"}]",
        "category": "gross_MAX_1",
        "totalCategory": 1
    },
    {
        "product": "[{\"imgUrl\":\"/p/332401\",\"prodCartQty\":2,\"prodName\":\"Test Product 1\",\"productCode\":\"332401\"},{\"imgUrl\":\"/p/332388\",\"prodCartQty\":2,\"prodName\":\"Test Product 2\",\"productCode\":\"332388\"}]",
        "category": "gross_MAX_1",
        "totalCategory": 1
    }
]

$.each(data,function(_,productArr) {
  var arr = JSON.parse(productArr.product.replace(/\//g,""));
  $.each(arr,function(_,productDetails) {
    // here is a product detail object
    $.each(productDetails,function(name,value) {
      console.log(name,value);
    });
  });
});

Comment: Hi, the json the server return has another json array inside it, I've been told this is the way the server has to return it. How can I work with what the server return? I need to get the info from the product section of the object.
Comment: Is there a way to get just the product array out of the object?
Comment: Hi, that did the trick thanks. I've now got the data in a format I can use. Top man.


How to generate my own patches to update core for security when fuerstnet.de's "Drupal upgrade the easy way" page is out of date?

Question: For Drupal 7, under the current host I'm using (which doesn't provide things like drush), I've found that patching is the easiest approach to updating core. However, the commonly-referenced page which provides the .patch files for doing this ("Drupal upgrade the easy way") has not updated for 7.67, which contains a security-fix.
Rather than go back to the old way of doing things by following all the steps found within UPGRADE.txt, what process can I use to generate a patch for upgrading my own site?
Answer: Per https://www.computerminds.co.uk/articles/quickly-update-drupal-core, Github itself can create patch-files for you. You can use commandline curl or wget to download the appropriate patch easily:
curl 'https://github.com/drupal/drupal/compare/7.66..7.67.patch' > "drupal-7.66-to-7.67.patch"

Alternatively, you can download the tar'd (or zipped) packages for both your current version of Drupal and the target and recursively diff them as described here, resulting in a functionally-identical patch-file.
This can then be tested out in the normal way:
patch -p1 --dry-run < "drupal-7.66-to-7.67.patch"

And then applied if no hunks failed:
patch -p1 < "drupal-7.66-to-7.67.patch"

Note of course that just because patching succeeded, it doesn't mean the successfully-applied patch hasn't broken your site in some way, so be sure to  back up everything (files and Drupal database) before patching, trying this first on your dev site, running tests, etc. before repeating the process for real in production.
Gotcha!
If you've upgraded using fuerstnet.de before, Drupal may falsely continue showing security-update warnings, because at least one package with $file->info['project']=='drupal' and $project['project_type']=='core' will still be considered out of date. That's because some of your .info files may contain extra lines which override standard version-numbers:
; Information added by Drupal.org packaging script on 2019-04-17
version = "7.66"
project = "drupal"
datestamp = "1555533576"

Based off of experience, generating your own patch as described above will not remove this information, since it is not present in the vanilla packages, and the files containing these extra lines won't necessarily fail to patch either, if no changes to the vanilla editions' code occurred in the last update. (Common because .info files don't change very often.)
These extra lines need to be removed (or adjusted, if you prefer) before Drupal will stop complaining that you're behind on core updates, even though you're actually up-to-date.


Can I select a specific data center in Japan for Watson Knowledge Catalog?

Question:
Can I select a specific data center in Japan to deploy to? Can I specifically select TOK4? Japan has three datacenters: TOK02, 04, 05
If the customer can not select, can I know which data center WKC deploy to? : TOK02, 04, 05
Answer: Watson Knowledge Catalog is deployed in the Tokyo MZR that spans the three data centers.  You cannot select a specific data center.
To access WKC deployed in Tokyo data center, use the following link:
https://jp-tok.dataplatform.cloud.ibm.com


Como devo organizar meus controllers utilzando a metodologia SOLID?

Question: Atualmente estou desenvolvendo um projeto e notei que meus controllers estão responsáveis por mais de uma atividade.
Pensando sobre isso lembrei sobre o Hangout da Comunidade Laravel Brazil sobre SOLID.
O problema é que não sei qual a melhor maneira de organizar os controllers... atualmente há o seguinte caso:
ContatosController
Responsabilidades:

CRUD (index, create, store, edit, update, destroy)
Importar contatos de outro sistema por CSV (3 métodos)
Exportar contatos para outros sistemas em CSV (2 métodos)
Buscar contatos através de filtros simples ou complexos (2 métodos)

Como eu deveria organizar este controller?

ContatosController
ContatoImportacoesController ou ContatosIOController
ContatosFiltrosController

Algo assim?

Se algo não foi bem explicado ou precisarem de mais detalhes, me avisem.
Desde já agradeço.
Comment: Relevante: http://qualityisspeed.blogspot.com.br/2014/08/why-i-dont-teach-solid.html
Answer: Existe uma diferença bastante sutil no Princípio da Responsabilidade Única que causa esse tipo de questionamento.
Ter Responsabilidade Única não é restringir o objeto a fazer uma única coisa e sim impedir que ela faça coisas além do contexto mais próximo que se tem como intenção ao iniciar sua codificação.
No seu caso, você tem o contexto de Contatos. Um Controller de Contatos deve controlar tudo sobre Contatos e só.
Mas controlar tudo sobre Contatos inclui tudo o que você citou, desde o CRUD até a busca e a importação/exportação.
Porém, não será o Controller propriamente dito quem importará/exportará os dados, por exemplo. Ele vai apenas intermear a escolha do usuário feita na GUI (View) e o produto final através da Requisição feita.
Nesse caso, o Importador é uma sim classe separada, mas não é um Controller, pelo menos não na definição convencional, pois um Importador deve possibilitar importar não apenas contatos, mas qualquer tipo de informação.
Não estou certo se com métodos você se referiu realmente a métodos de classe ou a formas de importação, mas supondo que tenha sido quanto a formas de importação, isso sequer é responsabilidade do Importador em si.
O Importador por sua vez oferecer uma interface (não visual, claro) para o Controller trabalhar, mas as reais rotinas de importação, ou melhor as estratégias de análise do input (CSV, TXT, XML...) são outras classes mais, todas sob uma interface reguladora.
Em código, teríamos algo mais ou menos assim:
<code>class ContactsController {

    // GUIs

    public function index() {}
    public function create() {}
    public function edit() {}
    public function delete() {}

    public function search() {}

    public function import() {}
    public function export() {}

    // Actions

    public function indexAction() {}
    public function createAction() {}
    public function editAction() {}
    public function deleteAction() {}

    public function searchAction() {}

    public function importAction() {

        $file   = ( isset( $_POST['file'] ) ? $_POST['file'] : NULL );
        $method = ( isset( $_POST['method'] ) ? $_POST['method'] : 'CSV' );

        try {

            $importer = new Importer( $file, $method );

            $data = $importer -> import();

            // Do something with $data

        } catch( ImporterException $e ) {

            die( $e -> getMessage() );
        }
    }

    public function exportAction() {}
}

class Importer {

    private $strategy;

    public function __construct( $strategy, $file ) {

        $strategyClass = sprintf( '%sStrategy.php', $strategy );

        if( ! class_exists( $strategyClass ) {

            throw new ImporterException(

                sprintf( 'Importer Strategy %s does not exist', $strategy )
            );
        }

        $this -> strategy = new $strategyClass( $file );
    }

    public function import() {
        return $this -> strategy -> import();
    }
}

class CSVStrategy implements ImporterInterface {

    private $file;

    public function __construct( $file ) {

        $this -> file =& $file;
    }

    public function import() {

        // Do something with $this -> file and return
    }
}

interface ImporterInterface{

    public function import();
}
</code>

O fragmento de código acima serve unicamente para fins didáticos e, por isso, não foi devidamente testado ou mesmo otimizado, podendo, inclusive, podem apresentar erros de sintaxe
Comment: Certo. Então eu posso manter o que já tenho dentro do controller, a diferença é que ele vai utilizar outros recursos para prosseguir a requisição. Seria mais ou menos isso?
Comment: Pra responder com toda certeza eu precisaria saber se o Laravel tem algum tipo de *coding standards* dentre eles organização e estruturação. Normalmente, se não é (M)odel, (C)ontroller ou (V)iew, não faz parte dos diretórios principais da aplicação. Estes, a partir da raiz do site, costumam ficar num diretório à parte, muitas vezes chamado de **vendor** e subdivididos por desenvolvedor (ZF, Symfony, Smarty...), inclusive seu próprio.
Comment: Certo. Eu preciso entender isso melhor... vou esperar outros pontos de vistas e dar uma pesquisada antes de fechar a questão. De qualquer forma, muito obrigado.
Comment: Vi alguns vídeos do Jeffrey Way no Laracasts e sua lógica bate com alguns pontos que ele apresentou. Desde já agradeço.
Comment: Que bom que pude ajudar :)


filter time stamp to date

Question: I'm using Stripe and the way stripe returns the start and end dates for a subscription are in timestamp such as this
current_period_start: 1465271767
current_period_end: 1433649367

I'm using angular for the presentation layer. Is there a way to convert this time stamp to short date like June 7, 2015?
right now I'm displaying the date like this and it always displays Jan 17, 1970
{{x.current_period_start | date:short }}

Answer: Unix timestamps are in seconds and JavaScript uses milliseconds. Multiply the start and end date values by 1000. Those dates will result in  Mon Jun 06 2016 22:56:07 GMT-0500 (CDT) and Sat Jun 06 2015 22:56:07 GMT-0500 (CDT) respectively.
Untested but this should work in your view:
{{x.current_period_start * 1000 | date:short }}

filter time stamp to date


"PHP Notice: Constant DATE_RFC7231 already defined in /ext/vhosts/public/includes/bootstrap.inc on line 258"

Question: After moving my Drupal site to a new host, I got the following error in the error logs.

[error] 8707#0: *1 FastCGI sent in stderr: "PHP message: PHP Notice:  Constant DATE_RFC7231 already defined in /ext/vhosts/public/includes/bootstrap.inc on line 258

How can I fix it?
My site currently says "The website encountered an unexpected error. Please try again later"
My setup is as follows:

Debian 8
PHP 7.0.21
MySQL 5.6
Drupal 7.54
Answer: Are you certain you're running PHP 5 and not a version of PHP 7? I've only ever seen that error when running PHP 7, and it was due to DATE_RFC7231 already defined in PHP 7.0.19 and 7.1.5.
Either way, the patches in that issue were committed and released with 7.55, so it might be worth trying a core update before anything else.
Comment: I've just tried to update site to Drupl 7.55. I ran draush cc all, and refreshe the site, stil the same error.
Comment: I was also getting this with PHP 7 on a VM on Drupal 7. Downgraded to PHP 5, it went away. This was just this week, too.
Comment: @Chapabu, actually Drupal 7.55 did fix the error for me. Thanks for the help
Answer: I solved following this tutorial:
https://webocreation.com/blog/notice-constant-date_rfc7231-already-defined-in-includes-bootstrap-inc-on-line-258/
Open /includes/bootstrap.inc
Go to line number 258
Comment out the following line:
<code>//define('DATE_RFC7231', 'D, d M Y H:i:s \G\M\T');
</code>
Then add following line:
<code>if (!defined('DATE_RFC7231')) {
define('DATE_RFC7231', 'D, d M Y H:i:s \G\M\T');
}
</code>
Comment: There is not need to edit a Drupal core file: It's enough to update to any Drupal 7 version that is higher than 7.54.


Hook to catch a variable in a POST request to a specific url?

Question: I'm testing an external email collection service that appears periodically at certain time intervals on a site.
When a user completes the form, the application can pass the email address as a variable in a POST request to a specific url.
What hook should I use to catch and process the email address at this one specific url?
I thought of using hook_init() something like the following, but I'm not sure if this is a good way to do something like this?
/**
 * Implements hook_init()
 * Check for variable sent via POST and process if found
 */
function mymodule_init() {
  if (drupal_get_path_alias() == "myurl") {
    if (isset($_POST['email_variable'])) {
      <custom processing>;
    }
  }
}

Notes:

The url is a normal node page that already exists on the site.
The form is externally hosted, so a form alter is not an option.
Comment: Form is in iframe ??
Comment: I don't think so. It's the scrollbox widget you see here: http://sumome.com/ I think it injects the DIV that contains the form somehow in the body of the page.
Answer: You should use the services module to create an endpoint and use the url where is sent as the path to endpoint.
You don't state which type format the data is being posted to your site but the services module can handle many different types.
Also it's not stated exactly what you want to do with the received data but the services module can be set up to process it in a variety of ways.
You can capture it to a databse table etc
or Here's an example of creating a node using services:
http://www.drupalwoo.com/content/blog/drupal-services-creating-node-from-external-form
Answer: Use mytheme_preprocess_node(&$vars, $hook)  in your active theme's template.php file.
function mytheme_preprocess_node(&$vars, $hook) {
  if($vars['nid'] =='node id of that node page'){

 //Add your code to get the data from post using post key
   $data = $_POST['datakey'];// datakey will contain data with which data is posted to this form
 }
}

Please, don't forget to clear drupal cache.
Hope it will help!
Comment: Thanks for this suggestion. Is it possible to implement this approach in a module instead? (I'd rather keep the code in one place). I updated my question to include a possible approach with hook_init, but I don't know is this is a good idea or not.
Comment: Yes preprocess function works in both template and module. I think it will work with init() also but usually we include files and any condition that we want to execute in begining


Inserir um calendário com HTML

Question: Estou a tentar inserir um calendário em HTML, só que esse calendário está a ficar mal. O calendário é esse verde que está nesta página: https://almsaeedstudio.com/preview
So que só me aparecem as tasks e os dias não. Que estou a fazer mal?
CODIGO QUE TENHO:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Home.aspx.cs" Inherits="CegosElearningReports.Report.Home" %>

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Cegos Analytics| Home Page</title>

  <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">

  <link rel="stylesheet" href="../../bootstrap/css/bootstrap.min.css">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css">

  <link rel="stylesheet" href="../../dist/css/AdminLTE.min.css">

  <link rel="stylesheet" href="../../dist/css/skins/skin-black.min.css">

  <link rel="stylesheet" href="../../plugins/iCheck/flat/blue.css">

  <link rel="stylesheet" href="../../plugins/morris/morris.css">

  <link rel="stylesheet" href="../../plugins/jvectormap/jquery-jvectormap-1.2.2.css">

  <link rel="stylesheet" href="../../plugins/datepicker/datepicker3.css">

  <link rel="stylesheet" href="../../plugins/daterangepicker/daterangepicker-bs3.css">

  <link rel="stylesheet" href="../../plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css">

    <form id="form1" runat="server">

        Toggle navigation

              User

                <%--

                  Alexander Pierce - Web Developer
                  Member since Nov. 2012

                    Followers

                    Sales

                    Friends

--%>

                  Profile

                  Sign out

          <%--

--%>

       <%--
--%>

            User
        <%--
--%>

              Home

            Admin Tools

            Reports

            X-Domain Reports

          Home

                       User

                                          Role

  Last Update:

                                      <asp:Button ID="Button1" runat="server" Text="Change Password" Font-Bold="True" Width="134px"/>

                          <asp:Button ID="Button2" runat="server" Text="Sign Out" Font-Bold="True"/>

<link rel='stylesheet' href='//cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.6.1/fullcalendar.min.css' />

Calendar

                  <button type="button" class="btn btn-success btn-sm dropdown-toggle" data-toggle="dropdown">
                    </button>

Add new event

Clear events

View calendar

                <button type="button" class="btn btn-success btn-sm" data-widget="collapse">
                </button>
                <button type="button" class="btn btn-success btn-sm" data-widget="remove">
                </button>

                    Task #1
                    90%

                    Task #2
                    70%

                    Task #3
                    60%

                    Task #4
                    40%

Welcome

              Lorem ipsum dolor sit amet, consectetur adipiscing elit.
              Fusce nisi urna, elementum sed arcu venenatis, ultricies commodo
                  enim.
              Suspendisse sit amet nibh iaculis purus blandit
                      mattis vitae vitae enim.
              Pellentesque mauris mauris,

                      fermentum a libero id, viverra dapibus elit.
                      Morbi malesuada nec sem ut tempus. Praesent nec risus nibh.Pellentesque lobortis, quam vitae ornare convallis,

                      risus leo pellentesque diam, eget rhoncus augue turpis sit amet ante.

               <%--
--%>

To Do List

«

1

2

3

»

                  <input type="checkbox" value="" name="">

                  <input type="checkbox" value="" name="">

                  <input type="checkbox" value="" name="">

                  <input type="checkbox" value="" name="">

                  <input type="checkbox" value="" name="">

                  <input type="checkbox" value="" name="">

              <button type="button" class="btn btn-default pull-right"> Add item</button>

            </form>

    <%--

              --%>

      Version 1.0.0

                             Copyright © 2016-2017 Cegos Analytics. All rights
    reserved.

<%--

--%>

    </form>

Comment: Ta difícil de entender oque você quer, pelo que eu entendi você quer um código que mostre a data atual, correto?
Comment: Não. Quero colocar no meu website um calendario igual ao que esta na página que mandei no link esse verde  https://almsaeedstudio.com/preview. Só que quando copiei so me aparecem as tasks e nao os dias
Comment: Alguem me ajude por favor?~
Answer: Se o calendário que se refere é o desta página, ele está utilizando o FullCalendar para isso.
Para utilizar em seu site, basta fazer o download da página ou utilizar a cnd.
Um exemplo básico ficaria assim:

$(document).ready(function() {

    // page is now ready, initialize the calendar...

    $('#calendar').fullCalendar({
        // put your options and callbacks here
    })

});

<link rel='stylesheet' href='//cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.6.1/fullcalendar.min.css' />

Claro, no site ele está utilizando o outras funções para criar os eventos e modificou o CSS para ficar "mais bonito", mas isso é tudo questão de customização.
Comment: Obrigado pela resposta mas ainda não consegui fazer isso. No meu código o que voce acrescentaria/melhoraria para conseguir obter o calendario? Ainda nao consegui obter o calendario. Obrigado
Comment: @NelsonSoares Em seu código você não está referenciando o FullCalendar em parte alguma. Olhe os scripts que tem na resposta, você precisa deles para ele funcionar.
Comment: @NelsonSoares Adicione a mesma coisa da minha resposta em seu código que irá funcionar, após isso, você terá que estudar o framework para adequar a sua necessidade. Isso não tem como te ajudar assim. Mas vá perguntando de acordo com suas dúvidas.
Comment: Eu ja adicionei o seu código mas mesmo assim não está aparecendo. Eu vou postar o código que alterei para voce dar uma olhada e ver se fiz bem. Obrigado
Comment: @NelsonSoares Você possui duas div's com o `id="calendar"`. O `id` do elemento deve ser único.
Comment: Já eliminei uma div mas ainda não tive sucesso. Coloquei o código como você ve com seu scripts e com os links e ainda nao rola. Me ajuda por favor
Comment: @NelsonSoares Você está usando várias versões do jQuery, o que pode ocasionar conflitos. Nunca coloque os scripts no meio do código, deixe no início ou no final, dependendo do que for usar. Abra o console do navegador (F12) e veja se aparece algum erro.
Comment: Ja coloquei o codigo no final. MAs ainda nao obtive sucesso. Tem de instalar alguma coisa no navegador?
Comment: @NelsonSoares Se não aparece é porque está com algum erro. Aperte F12, vá na aba console, veja o erro que aparece e corrija-o.
Comment: Sim tem dois erros iguais que dizem: Browser Link : Failed to invoke return value callback. Security error: the operation is insecure. São os dois erros iguais. Me ajuda a corrigir @Randrade
Comment: @NelsonSoares Remova tudo que não for `CSS` e que não tiver a ver com o FullCalendar. Algum script seu está impedindo o funcionamento. Depois de funcionar, vá adicionando cada script até achar o problema.
Comment: Ja fiz isso. removi e adicionei novamente. Deixei comentado dois que ele estava dando erro de get. Mas esta ainda me dando um erro de: GMT+001(GMT STANDARD TIME) faile to invoke return value callback. The operation is insecure. Consegue-me ajudar nesse?
Comment: @NelsonSoares Não. Não sei quais arquivos você possui ai e qual está dando esse erro. Aconselho a criar uma página nova com o código da resposta e após estiver funcionando, ir adicionando os restantes de um a um. Em uma página nova, sem nenhum outro arquivo, a resposta irá funcionar.
Comment: Já percebi cara. Mas preciso de sua ajuda. no fullcalendar.min.css e no fullcalendar.min.js e no moment.js esta dando erro aí e diz que é aí que a ligação não é segura. Como resolvo isso? @ Randrade
Comment: ou seja esta dando erro naqueles links que voce postou à pouco
Comment: @NelsonSoares Os links que eu passei são apenas exemplos. Vá ao site e faça os downloads dos arquivos, como indiquei na resposta. Junto você irá ver um exemplo de como funciona. E por demais, utilize o site do framework para ver o que precisa fazer, não consigo te ajudar porque não sei o que tem. Faça tudo do zero e entenda como o FullCalendar funciona, depois você conseguirá incorporar em sua página.

Inserir um calendário com HTML


How to automatically rewrite response records obtained using recursion in BIND?

Question: I'm using Bind 9.9.4 on a hypervisor (lets call the hypervisor A) for VMs. The hypervisor has a VPN connection to a different host (lets call it B), which also has a public IP. The bind on hypervisor A is used by the VMs and won't answer to requests from anyone else.
To force the most of the traffic to host B through the VPN, it would be easiest if Bind would rewrite the A and AAAA records it finds during recursion to the local, private IP given to the vpn tunnel to host B.
I've already read about Response Policy Zones (RPZ), but as I get them, I have to replicate all records I want to be rewritten. Ideally, Bind would automatically detect the public IP of B in the records and replace it automatically.
Is there a way to achieve that?
Comment: When you get a moment, please accept your supplied answer so that this doesn't show up in unanswered question searches. Thanks!
Comment: @AndrewB Sorry, I totally forgot about this! Did it, thanks for notifying me.
Answer: I found out that it is actually possible using Response-Policy Zones.
One can match on IPs using the rpz-ip suffix. The notation is:
# for IPv4
prefixlength.B4.B3.B2.B1.rpz-iz
# for IPv6
prefixlength.W8.W7.W6.W5.W4.W3.W2.W1.rpz-iz

Details can be found in BINDs Administrator Reference Manual.


Variable drawn from a normal distribution

Question: What exactly is the meaning of a "variable drawn from a normal distribution"? I know what a normal distribution is, but my main exposure to "variables" is from calculus, so I have a hard time understanding this terminology.
Answer: It means that this is a random variable (i.e.a measurable function defined on a probability space) whose distribution is the normal distribution.


How to create an observable class in TypeScript using RXJS

Question: I'm struggling to figure out how to make a model observable. I've read this and it's not what I want. I don't want individual properties to be observable, I want the entire class to be. Here's what I have so far:
export class ObservableModel extends Observable<any> {
    __internalSource = new BehaviorSubject(this);
    source = this.__internalSource.asObservable();
}

/**
 * Base entity class which all models should extend
 */
export class EntityModel extends ObservableModel {
   protected entityData: AnyEntity;
   protected entityState: {
      loading: boolean;
      loaded: boolean;
      reloading: boolean;
      error: boolean;
   } = {
      loading: false,
      loaded: false,
      reloading: false,
      error: false,
   };

   constructor(public type: string, public id?: string) {}

   from(value: AnyEntity) {
      const { type, id } = value;
      this.entityState = {
         loaded: true,
         loading: false,
         reloading: false,
         error: false,
      };

      this.entityData = value;
      this.__internalSource.next(this);
   }

   load() { ... }
   reload() { ... }
   private requestData() { ... }
}

export class CollectionModel extends EntityModel {
   @attr name: string;
}

export class ProductModel extends EntityModel {
   @attr name: string;
   @attr description: string;
   @hasOne('collection') collection: CollectionModel;
}

I have this working somewhat, but it breaks down. For instance, if I use the following in Angular
// component
export AppComponent {
   product = new ProductModel('product', '1');
}

// The following works...

   {{prod.loading}} works
   {{prod.reloading}} works
   {{prod.loaded}} works
   {{prod.error}} works
   {{prod.name}} works
   {{prod.id}} works
   {{prod.type}} works

// This doesn't work...

      {{collection.loaded}} // TS throws an error that "Object is of type unknown"

 This works?
      {{ prod.collection.name }} works

I don't understand why this is happening.
Comment: I don't think that this is a good idea. When working with observables, you want to have immutable data and use pure functions to transform your data along the way. With a class, it's quite the opposite approach
Comment: Don't you need to use `.value` in your template to access the value and its members?
Comment: I might look into giving an Rxjs answer. But to me it sounds like you actually want something that work more like Vue's then getter/setter and now observables
Answer: I'm not sure of the usability of it, but here's what I could come up with. The biggest issue was, as you can guess, the types. Since you use Observable<any> there was no way for typescript to do anything with it.
export class ObservableModel<T> extends Observable<T> {
    __internalSource = new BehaviorSubject(this);
    source = this.__internalSource.asObservable();
}

And thus now, we have to propagate that change to the entity:
/**
 * Base entity class which all models should extend
 */
export class EntityModel<T> extends ObservableModel<T & EntityModel<T>> {
   protected entityData: any;
   protected entityState: {
      loading: boolean;
      loaded: boolean;
      reloading: boolean;
      error: boolean;
   } = {
      loading: false,
      loaded: false,
      reloading: false,
      error: false,
   };

   constructor(public type: string, public id?: string) {
     super();
   }

   from(value: any) {
      const { type, id } = value;
      this.entityState = {
         loaded: true,
         loading: false,
         reloading: false,
         error: false,
      };

      this.entityData = value;
      this.__internalSource.next(this);
   }

   getState() {
     return this.entityState;
   }
}

Note that I've also added a getter function for the state. That's because the way you accessed data in the template was wrong (or you were thinking about using something other than this as the values).
Thus, now we fix how the template look like:
// The following works...

   {{prod.getState().loading}} works
   {{prod.getState().reloading}} works
   {{prod.getState().loaded}} works
   {{prod.getState().error}} works
   {{prod.name}} works
   {{prod.id}} works
   {{prod.type}} works

      {{collection.getState().loaded}}

        {{ collection.name }} works

Everything works just about the same, except that:

We need to call getState() to have access to the "internal state"
We need to nest the .loaded condition within the async pipe if we want to make it look like it's a proper stream of data
Comment: Thank you!  This makes more sense now! I also had various issues with the whole Observable part. This works perfectly now.


How prove this $arg((1+ia)(2+ia)(3+ia)\cdots(n+ia))=\arctan{\frac{a}{1}}+\arctan{\frac{a}{2}}+\cdots+\arctan{\frac{a}{n}}$

Question: let $i^2=-1,a>0$, show that
$$arg((1+ia)(2+ia)(3+ia)\cdots(n+ia))=\arctan{\dfrac{a}{1}}+\arctan{\dfrac{a}{2}}+\cdots+\arctan{\dfrac{a}{n}}$$
I can't How prove this equation,Thank you
because  $n=1$.we have
$$(1+ia)=\arctan{a}\Longleftrightarrow \tan{(1+ia)}=a?$$
then I can't.Thank you
Comment: You already saw that it's not even true for $n=1$..
Comment: i think the question should be to prove $$arg((1+ai)(2+ai)...(n+ai))=\sum_{k=1}^{n}\arctan(\frac{a}{k})$$ they might be discussing about the arguement.
Comment: @ProMatheus,oh,Yes, Thank you
Comment: The main point is : "the complex argument of a product of two numbers is equal to the sum of their arguments, "http://mathworld.wolfram.com/ComplexArgument.html.
Answer: let $$k+ia=r_ke^{i\theta_k}=r_k(\cos \theta_k+i\sin \theta_k)$$ where $\theta_k=\arctan(\frac{a}{k})$ is the arguement of the term. now what do you get in the arguement part when you multiply all the terms. you get a $r_1r_2\cdots r_ne^{i(\theta_1+\theta_2+\cdots+\theta_n)}$


Prove: $|a\sin x+b \cos x|\leq \sqrt{a^2+b^2}$

Question:
$$|a\sin x+b \cos x|\leq \sqrt{a^2+b^2}$$

I have tried: $$|a\sin x+b \cos x|\leq |a+b|\leq \sqrt{a^2+b^2}$$
Suffices to prove: $$|a+b|\leq \sqrt{a^2+b^2}$$
But I can't find how to continue from here.
Comment: $|a+b|\leq \sqrt{a^2+b^2}$ is not true, try $a=3, b=4$
Comment: @gammatester Find $x : \sin x = \cos x = 1$...
Comment: @Abstraction: That is irrelevant. You cannot prove the inequality, and therefore OP's reasoning cannot be OK.
Comment: @gammatester Oh, sorry, missed that point. Reasoning is indeed faulty.
Comment: @gbox, use https://en.wikipedia.org/wiki/Brahmagupta%E2%80%93Fibonacci_identity
Comment: In fact, $|a\sin x+b \cos x|\leq |a+b|$ is also false : you can take $a=1=-b$ and $x=0$, for example. But $|a\sin x+b \cos x|\leq |a|+|b|$ is true (but since $|a|+|b|\geq \sqrt{a^2+b^2}$, this isn't really helpful here).
Comment: See [this answer](https://math.stackexchange.com/a/856600/409), and/or [this entry at Trigonography.com](http://trigonography.com/2015/09/30/combining-sine-and-cosine/).
Answer: Use Cauchy-Schwarz inequality :
\begin{align}|a\sin x+b \cos x| = |(a,b)\cdot (\sin x,\cos x)|
&\leq \sqrt{a^2+b^2}\sqrt{\sin^2 x+\cos^2 x}=\sqrt{a^2+b^2}.\end{align}
Answer: $$|a \sin x + b \cos x|=\big|\sqrt{a^2+b^2}\left(\frac a{\sqrt{a^2+b^2}}\sin x+\frac b{\sqrt{a^2+b^2}}\cos x\right)\big|=$$
$$=\sqrt{a^2+b^2}|\left(\sin(x+\phi)\right)|\le\sqrt{a^2+b^2}$$
Comment: Ok. Let $\frac a{\sqrt{a^2+b^2}}= \sin \phi, \frac b{\sqrt{a^2+b^2}}=\cos \phi$. Really,
$$\sin^2 \phi+\cos^2 \phi=\frac{a^2}{a^2+b^2}+\frac{b^2}{a^2+b^2}=1$$ and $|\sin \phi|=\frac a{\sqrt{a^2+b^2}}\le1$
Then $$sin x \sin \phi+\cos x \cos \phi=\sin(x+\phi)$$
Comment: can you please elaborate on the 2 move  where did $sin(x+\phi)$ came
Answer: Find the extrema of
$$a\cos(x)+b\sin(x).$$
By canceling the derivative,
$$-a\sin(z)+b\cos(z)=0$$ or$$\tan(z)=\frac ba.$$
Then, with
$$\cos(z)=\pm\frac1{\sqrt{\tan^2(z)+1}}=\pm\frac a{\sqrt{a^2+b^2}},\\\sin(z)=\pm\frac{\tan(z)}{\sqrt{\tan^2(z)+1}}=\pm\frac b{\sqrt{a^2+b^2}},$$
you obtain
$$a\cos(z)+b\sin(z)=\pm\sqrt{a^2+b^2}.$$
Then for all $x$,
$$-\sqrt{a^2+b^2}\le a\cos(x)+b\sin(x)\le\sqrt{a^2+b^2}.$$
Answer: $$a\sin{x}+b\cos{x}=\sqrt{a^2+b^2}(\frac{a}{\sqrt{a^2+b^2}}\sin{x}+\frac{b}{\sqrt{a^2+b^2}}\cos{x}$$
now let $$\sin{\alpha}=\frac{b}{\sqrt{a^2+b^2}}$$ then  $$\cos{\alpha}=\frac{a}{\sqrt{a^2+b^2}}$$ thus $$a\cos{x}+b\sin{x}=\sqrt{a^2+b^2}\sin({\alpha+x})<\sqrt{a^2+b^2}$$
Answer: Take two vectors: $v_1 = (a,b)$ and $v_2 = (\sin x, \cos x)$. Their scalar product is $(v_1, v_2) = |v_1||v_2|cos(\phi) = a \sin x + b \cos x$ where $\phi$ is the angle between $v_1$ and $v_2$, but $|v_1| = \sqrt{a^2 + b^2}, |v_2| = 1$.
Comment: Don't see any reason for a down vote. Canceling it by a +1. Nice answer
Answer: If we square the inequality we get $$a^2\sin^2 x+b^2\cos^2 x+2ab\sin x\cos x\leq a^2+b^2\\2ab\sin x\cos x\leq a^2(1-\sin^2 x) +b^2(1-\cos^2 x) =a^2\cos^2x+b^2\sin ^2 x\\0\leq a^2\cos^2x-2ab\sin x \cos x+b^2\cos^2 x=(a\cos x-b\sin x) ^2$$
The last equation is always true, and we can square inequality because both sides are positive.


Additional inputs for Shiny module only get updated once

Question: I tried boiling this down to a minimal example, but I think I have to provide more or less the full code to show the problem.
Basically I want a shiny app to act as a user friendly GUI to start/stop (multiple) system processes (mostly BASH scripts, for scientific workflows) through the processx package. So I made a shiny module that can start/stop and show a process log (just output from stderr+stdout). The script/command run is decided when calling the module, not in the module itself. It's then important that additional options can be passed on to the different processes depending on the script run, like choosing input/output folders, database files, settings, etc.
The issue is that the value of any additional inputs does not get updated every time the actionButton is clicked, so clicking the start button again (triggering the eventReactive) just starts the process again without the new options/setting.
I have attached the full code here and published an example app on my shinyapps.io account, available here: https://kasperskytte.shinyapps.io/processxmodule/
library(shiny)

#shiny module to start asynchronous processes using processx package

#shiny must be version 18.104.22.16803 or later to use shiny modules, install from github
installGitHub <- function(...) {
  if(!require("remotes")) {
    install.packages("remotes")
  }
  remotes::install_github(...)
}

if(any(grepl("^shiny$", installed.packages()[,1]))) {
  if(packageVersion("shiny") < "188.8.131.5203") {
    installGitHub("rstudio/shiny")
  }
} else
  installGitHub("rstudio/shiny")

require("shiny")
require("processx")

processxUI <- function(id) {
  shiny::tagList(
    uiOutput(NS(id, "startStopBtn")),
    p(),
    uiOutput(NS(id, "processStatus")),
    h4("Process log"),
    verbatimTextOutput(NS(id, "processLog")),
    downloadButton(NS(id, "downloadLogfile"), label = "Export log file")
  )
}

processxServer <- function(id, ...) {
  moduleServer(id, function(input, output, session) {
    #reactive to store processx R6 class object
    process <- reactiveVal()

    #reactive to store logfile created on start
    logfile <- reactiveVal(tempfile())

    #start/stop button
    output$startStopBtn <- renderUI({
      if(isFALSE(processAlive())) {
        actionButton(
          inputId = NS(id, "startStopProcess"),
          label = "Start process"
        )
      } else if(isTRUE(processAlive())) {
        actionButton(
          inputId = NS(id, "startStopProcess"),
          label = "Kill process"
        )
      }
    })

    #start a new process and logfile when actionbutton is pressed
    observeEvent(input$startStopProcess, {
      #start process if not already running, otherwise kill
      startProcess <- function(...) {
        #generate new log file for each new process
        logfile(tempfile())
        #start process piping stderr+stdout to logfile
        process(
          processx::process$new(
            ...,
            stderr = "2>&1",
            stdout = logfile(),
            supervise = TRUE
          )
        )
      }
      if(is.null(process()$is_alive))
        startProcess(...)
      else if(!is.null(process()$is_alive))
        if(isTRUE(process()$is_alive()))
          process()$kill_tree()
      else if(isFALSE(process()$is_alive()))
        startProcess(...)
    })

    #read process status every 500 ms (alive or not)
    #(only for updating status message below, otherwise use
    # process()$is_alive() to avoid refresh interval delay)
    processAlive <- reactivePoll(
      intervalMillis = 500,
      session = session,
      checkFunc = function() {
        if(!is.null(process()$is_alive))
          process()$is_alive()
        else
          FALSE
      },
      valueFunc = function() {
        if(!is.null(process()$is_alive))
          process()$is_alive()
        else
          FALSE
      }
    )

    #print status message of process and exit status if finished
    output$processStatus <- renderUI({
      if(isTRUE(processAlive())) {
        p("Process is running...")
      } else if(isFALSE(processAlive()) && !is.null(process()$get_exit_status)) {
        if(process()$get_exit_status() == 0)
          p("Process has finished succesfully")
        else if(process()$get_exit_status() == -9)
          p("Process was killed")
        else if(!process()$get_exit_status() %in% c(0, -9))
          p(paste0("Process has errored (exit status: ", process()$get_exit_status(), ")"))
      }
    })

    #read logfile every 500 ms
    readLogfile <- reactivePoll(
      intervalMillis = 500,
      session = session,
      checkFunc = function() {
        if(file.exists(logfile()))
          file.info(logfile())[["mtime"]][1]
        else
          return('No process has run yet')
      },
      valueFunc = function() {
        if(file.exists(logfile()))
          readLines(logfile())
        else
          return('No process has run yet')
      }
    )

    #print process logfile
    output$processLog <- renderText({
      readLogfile()
    },
    sep = "\n")

    #export process logfile
    output$downloadLogfile <- downloadHandler(
      filename = function() {
        #append module id and date to logfile filename
        paste0("logfile_", id, "_", format(Sys.time(), format = "%y%m%d_%H%M%S"), ".txt")
      },
      content = function(file) {
        file.copy(from = logfile(), to = file)
      },
      contentType = "text/plain"
    )
  })
}

ui <- navbarPage(
  title = "test",
  tabPanel(
    title = "Test",
    column(
      width = 4,
      wellPanel(
        sliderInput(
          NS("process1", "delay"),
          "Sleep delay",
          min = 1,
          max = 5,
          step = 1,
          value = 2)
      )
    ),
    column(
      width = 8,
      fluidRow(
        processxUI("process1")
      )
    )
  )
)

server <- function(input, output, session) {
  processxServer(
    "process1",
    command = "echo",
    args = as.character(reactive({input[[NS("process1", "delay")]]})())
  )
}

shinyApp(ui = ui, server = server)

Answer: The error is that you don't pass a reactive to your module. In the line
processxServer(
    "process1",
    command = "echo",
    args = as.character(reactive({input[[NS("process1", "delay")]]})())
  )

you evaluate your reactive before passing it to the module, therefore the module only gets the default at startup. I've changed it so that the unevaluated reactive is passed to the module and only evaluated when you make the startProcess function. However, this makes you a bit less flexible with the ... because now startProcess assumes that there is the argument args passed.
library(shiny)
library("processx")

#shiny module to start asynchronous processes using processx package

processxUI <- function(id) {
  shiny::tagList(
    uiOutput(NS(id, "startStopBtn")),
    p(),
    uiOutput(NS(id, "processStatus")),
    h4("Process log"),
    verbatimTextOutput(NS(id, "processLog")),
    downloadButton(NS(id, "downloadLogfile"), label = "Export log file")
  )
}

processxServer <- function(id, ...) {
  moduleServer(id, function(input, output, session) {
    #reactive to store processx R6 class object
    process <- reactiveVal()

    #reactive to store logfile created on start
    logfile <- reactiveVal(tempfile())

    #start/stop button
    output$startStopBtn <- renderUI({
      if(isFALSE(processAlive())) {
        actionButton(
          inputId = NS(id, "startStopProcess"),
          label = "Start process"
        )
      } else if(isTRUE(processAlive())) {
        actionButton(
          inputId = NS(id, "startStopProcess"),
          label = "Kill process"
        )
      }
    })

    #start a new process and logfile when actionbutton is pressed
    observeEvent(input$startStopProcess, {
      #start process if not already running, otherwise kill
      startProcess <- function(...) {
        #generate new log file for each new process
        logfile(tempfile())
        #start process piping stderr+stdout to logfile

        # make argument list
        dots <- list(...)
        dots$args <- as.character(dots$args())
        arg_list <- c(dots, stderr = "2>&1", stdout = logfile(), supervise = TRUE)

        process(
          do.call(processx::process$new, arg_list)
        )
      }
      if(is.null(process()$is_alive))
        startProcess(...)
      else if(!is.null(process()$is_alive))
        if(isTRUE(process()$is_alive()))
          process()$kill_tree()
      else if(isFALSE(process()$is_alive()))
        startProcess(...)
    })

    #read process status every 500 ms (alive or not)
    #(only for updating status message below, otherwise use
    # process()$is_alive() to avoid refresh interval delay)
    processAlive <- reactivePoll(
      intervalMillis = 500,
      session = session,
      checkFunc = function() {
        if(!is.null(process()$is_alive))
          process()$is_alive()
        else
          FALSE
      },
      valueFunc = function() {
        if(!is.null(process()$is_alive))
          process()$is_alive()
        else
          FALSE
      }
    )

    #print status message of process and exit status if finished
    output$processStatus <- renderUI({
      if(isTRUE(processAlive())) {
        p("Process is running...")
      } else if(isFALSE(processAlive()) && !is.null(process()$get_exit_status)) {
        if(process()$get_exit_status() == 0)
          p("Process has finished succesfully")
        else if(process()$get_exit_status() == -9)
          p("Process was killed")
        else if(!process()$get_exit_status() %in% c(0, -9))
          p(paste0("Process has errored (exit status: ", process()$get_exit_status(), ")"))
      }
    })

    #read logfile every 500 ms
    readLogfile <- reactivePoll(
      intervalMillis = 500,
      session = session,
      checkFunc = function() {
        if(file.exists(logfile()))
          file.info(logfile())[["mtime"]][1]
        else
          return('No process has run yet')
      },
      valueFunc = function() {
        if(file.exists(logfile()))
          readLines(logfile())
        else
          return('No process has run yet')
      }
    )

    #print process logfile
    output$processLog <- renderText({
      readLogfile()
    },
    sep = "\n")

    #export process logfile
    output$downloadLogfile <- downloadHandler(
      filename = function() {
        #append module id and date to logfile filename
        paste0("logfile_", id, "_", format(Sys.time(), format = "%y%m%d_%H%M%S"), ".txt")
      },
      content = function(file) {
        file.copy(from = logfile(), to = file)
      },
      contentType = "text/plain"
    )
  })
}

ui <- navbarPage(
  title = "test",
  tabPanel(
    title = "Test",
    column(
      width = 4,
      wellPanel(
        sliderInput(
          NS("process1", "delay"),
          "Sleep delay",
          min = 1,
          max = 5,
          step = 1,
          value = 2)
      )
    ),
    column(
      width = 8,
      fluidRow(
        processxUI("process1")
      )
    )
  )
)

server <- function(input, output, session) {
  processxServer(
    "process1",
    command = "echo",
    args = reactive({input[[NS("process1", "delay")]]})
  )
}

shinyApp(ui = ui, server = server)

Also, your definition of the delay slider is a bit outside of the shiny module concept. NS is thought to be called in the module ui, so that the definition of which elements belong to which namespace is clearly separated (but it obviously also works with your approach).
Comment: Thank you very much! I see now, that solved the issue. I know it's not exactly by the book doing it this way when using shiny modules, but I don't see any other options. I currently have 8 different processes to run from within the same app, so having to have 8x replicate code just because a few inputs are different really bothers me.


Join dictionaries in Python

Question: I'm able to achieve this but think there must be a better way of doing it. The idea is to have common solution for both the cases.
Problem:
a & b are two dictionaries . values of these dictionaries could be a simple string (use case 1) or lists of same length (use case 2). Please note that length of these lists could be different between a & b (ex:- Key '2' in use case 2) but length within the same dictionary is same.
Expected:
We need to create a final dictionary which will have keys from both the dictionaries a & b and consolidate those values (be it a string or list) as lists of lengths equivalent to longest from either of the dictionaries. For ex:- In use case 2, Key 2 has ["abc","def"] in dictionary a but just ["abc"] in dictionary b.Here we are expecting final result as 2: ["abc","def","abc",None].
Examples:
use case 1:
a = {1:"xyz",2:999,3:1234,4:"boy"}
b = {1:"xyz",2:99,3:19,6:"toy"}

Result expected : {1: ['xyz', 'xyz'], 2: [999, 99], 3: [1234, 19], 4: ['boy', None],
                   6: ['None', 'toy']

use case 2:
a = {1:["xyz","123"],2:["abc","def"],3:["zzz",""],4:["boy","abc"]}
b = {1:["xyz","1234"],2:["abc"],3:["zz",""], 6: ["toy"]}

result expected: {1: [('xyz', 'xyz'), ('123', '1234')], 2: [('abc', 'abc'), ('def', None)],
                  3: [('zzz', 'zz'), ('', '')], 4: [('boy', None), ('abc', None)],
                  6: [(None, 'toy')]})

Comment: It would be better if you described how the dictionaries need to be joined, deducting that from you minimal examples might be possible but because of the repeated list elements in both dicts, never 100% clear. Please update your post with a **description** of the problem that you try to solve. ( I first thought your output was sorted, until I started wondering where the `None` came from (used to even out unequal length lists?).
Comment: Have you seen this: http://stackoverflow.com/questions/1495510/combining-dictionaries-of-lists-in-python
Comment: Your examples don't make your intent clear, especially how `'toy'` disappears in the output. You need to give us an actual, precise specification of what you want to do.
Comment: Edited question with more details. thanks for your response.
Answer: Algorithm:
from itertools import izip_longest

def merge(a, b):
    res = {}
    keys = set(a.keys()) | set(b.keys())
    if isinstance(a.values()[0], list):
        res = {k: list(izip_longest(a.get(k, [None]), b.get(k, [None]))) for k in keys}
    else:
        res = {k: [a.get(k, None), b.get(k, None)] for k in keys}
    return res

Use case 1
a = {1:"xyz",2:999,3:1234,4:"boy"}
b = {1:"xyz",2:99, 3:19,  6:"toy"}

exp = {1: ['xyz', 'xyz'],
       2: [999, 99],
       3: [1234, 19],
       4: ['boy', None],
       6: [None, 'toy']}

print merge(a, b) == exp

Output:
True

Use case 2
a = {1:["xyz","123"], 2:["abc","def"],3:["zzz",""],4:["boy","abc"]}
b = {1:["xyz","1234"],2:["abc"],     3:["zz",""],  6: ["toy"]}
exp = {1: [('xyz', 'xyz'), ('123', '1234')],
       2: [('abc', 'abc'), ('def', None)],
       3: [('zzz', 'zz'), ('', '')],
       4: [('boy', None), ('abc', None)],
       6: [(None, 'toy')]}

print merge(a, b) == exp

Output:
True

Note Python 2

Join dictionaries in Python


Trying to edit wp-config file on Google cloud platform but get this message

Question: Trying to edit wp-config file on Google cloud platform but get this message.
<code>PHP Warning:  file_put_contents(/var/www/html/wp-config.php): failed to open stream: Permission denied in phar:///usr/local/bin/wp/vendor/wp-cli/config
-command/src/Config_Command.php on line 192
</code>
Comment: I tried to change permissions but no luck
Comment: Have you tried to use `sudo` in front of your commands? Please provide more details.
Answer: Your not logged in as a user that has the necessary permissions to edit the file.
Change the permissions on the file to allow your current user access or log in as a user that has the necessary permissions.
We are talking about Linux permissions here, google cloud platform is irreverent to your question.


What kind of app is this?

Question: I installed yesterday this app http://www.appbrain.com/app/mini-info/com.dynotes.miniinfo from android market on my phone.
But I've never seen such apps before. It doesn't look like a widget, it looks like custom dialog.
So, does anybody know, what technique has the author of this app used?
Answer: If the left screen isn't a widget, it's most likely a regular Activity but with a theme that looks something like this:

And this theme is applied to the Activity in the manifest file like this:
<activity
    android:name="com.example.MyActivity"
    android:theme="@style/Theme.FloatingMenu" />

Answer: Without having tried the app I would say that the one to the left is a dialog, and the ones to the right are regular widgets.
Answer: Description
A simple & hassle free way for device info. Widgets, toggle bar, and lots more!
https://market.android.com/details?id=com.dynotes.miniinfo&feature=search_result
Comment: but widgets are on the second screenshot. The first one is no widget, i'm pretty sure. But maybe i'm wrong
Comment: I think it is widget. The widget is pressed. But maybe i'm wrong ))

What kind of app is this?


What is the name for a function that behaves symmetrically when its arguments are scaled?

Question: In other words, is there a name for this property of a function $f$:
$$f(\alpha x_1,x_2,\ldots,x_n) = f(x_1,\alpha x_2,\ldots,x_n) = \ldots = f(x_1,x_2,\ldots,\alpha x_n)$$
Edit:
I appreciate the answers received; however, they focus on identifying the functions that have this property rather than giving the right term (if it exists). This question is about terminology.
Even though the set of functions with this property is rather narrow, I was wondering whether there's a term or a combination of terms that would describe it. There are terms for similarly stated properties (e.g. symmetry and homogeneity/scale invariance); so I was hoping this property could be described as succinctly.
Comment: @GerryMyerson For a concrete example, $\det$ as a function with the columns of a square matrix as its arguments and the determinant of the matrix as the value.
Comment: If the arguments are from a field, the condition is equivalent to the condition that the function only depends on the product of its arguments.
Comment: Is there any such function, other than constant times power of product of $x_i$?
Comment: @GerryMyerson Well, interpreting this very generously [hah, funny how I could've said "generally" and it would mean almost the same thing], $f$ could be a function from $M^n$, where $M$ is some magma, to a (mere) set.
Comment: @GerryMyerson We can actually be even more general: $f\colon M^n \to S$, where $M$ is a magma with a set $A$ acting on it, with the action being $(\alpha, x) \mapsto \alpha x \in M$, for each $\alpha \in A$ and $x \in M$. This is also suggested by the term "scaling" in the question [so $A$ acts as some set of "scalars" for $M$-elements, just as in the case of vector spaces or modules].
Comment: Thank you for the answers; however, I am looking for the appropriate term for this property rather than the functions that satisfy it (see edit in question)
Answer: The aim of this answer is to give a characterization of functions $f$ satisfying the hypothesis that multiplying any one of the coordinated by a fixed constant $c$ gives the same value as multiplying another of the coordinates by $c.$ Our claim is that any such function is equal to some one variable function of the product of the variables of $f.$ [It is clear on the other hand that functions of this type satisfy the hypothesis.]
Given the variables $x_1,x_2,\ldots x_n.$  for each $k$ from $1$ to $n$ let $p_k$ denote the partial product $x_1x_2\cdots x_k.$ Now first begin with the value $f(p_{n-1},1,\cdots 1)$ and apply the relation using $c=x_n$ at the first and $n$th variables to get
$$f(p_n,1,\ldots 1)=f(p_{n-1},1, \ldots,1,x_n.\tag{1}$$
Next begin with the value of $f(p_{n-2},1,\ldots 1, x_n)$ and apply the relation using $c=x_{n-1}$ at the first and $(n-1)$st variables to arrive at
$$f(p_{n-1},1,\ldots, 1, x_n) = f(p_{n-2},1,\ldots,1,x_{n-1},x_n)\tag{2}$$
Note now that combining $(1),(2)$ we have shown that $g(p_n)=f(p_n,1,\ldots 1)$ is equal to the result of shifting $x_n$ into the final variable slot, and $x_{n-1}$ into the slot to the left of the final one. It seems clear (or could induct) that after doing $n-1$ steps of this kind, we arrive at the result that the function f we began with is actually simply a function of the product $p_n$ of the varibles. That is,
$$g(x_1x_2\cdots x_n)=f(x_1,x_2,\cdots,x_n.$$
Comment: Note that I put this up before I noticed user joriki's comment which asserts this for arguments in a field. [In the above I think only some mild things like a unit element and maybe commutativity was used.]
Comment: Thank you for the answer; however, I am looking for the appropriate term for this property rather than the functions that satisfy it (see edit in question)


Discord bot Command That changes Value of a different command

Question: I'm looking for a way to change a text string or a value in one command by typing the new value in a different command. For example I have Discord js v12 and I'm using module commands with each command being in its own .js file.
module.exports = {
    name: 'calc',
    cooldown: 1000,
    run: async(client, message, args) => {
        if (!message.member.hasPermission("ADMINISTRATOR")) return await message.delete();
        await message.delete();

        var multiply = args[0] * (100 - percalc) / 100;
        var calculation = multiply.toFixed(2);

        if(!args[0]) return await message.channel.send('Specify a Value');

        await message.channel.send(changableValue);
        await message.channel.send(calculation < 5 ? 5 : calculation);
    }

and I have the consts in the config file like
const percalc = 50;
const changableValue = 'Text example';

Right now the command _calc {number} puts out a calculation in percentage based on the percalc const and a text that comes with it in the changableValue part.
I'd like to make a command let's say _calcset {Value} that will save the provided value and will send it in place of the changableValue const.
Answer: First of all, note that the only reason the keyword const exists is because it stands for constant and constant variables can never be changed once initialized. So make sure you change the variable declaration keyword to just var or let.
Method 1 - If you don't need data to persist
Now, if you only want the variable to be changed per session, and you're fine with it going back to what you defined it as when you shut down the bot, you can just update the variable using functions exported from the js file. But to get the dynamic variable you'll also need to use a getter function that you export as well. Example:
config.js
var changeableValue = "foo";

function getValue() {
    return changeableValue;
}

function updateValue(newValue) {
    changeableValue = newValue;
}

module.exports = {
    getValue,
    updateValue
}

command.js
const { getValue, updateValue } = require("config.js");

console.log(getValue()); // logs "foo"
updateValue("bar");
console.log(getValue()); // logs "bar"

Unfortunately, as I mentioned, the changeableValue var will be reset back to "foo" every time you shut off the bot. If that's okay with you, then the above works fine.
Method 2 - If you need data to persist through sessions
If you want to persist the changeableValue variable through sessions, then it gets a little more complicated. Your two most likely options are either to write the value to a JSON file using the fs module (so it will be saved to your disk), or save the value in some other database, like MongoDB. I would recommend using another database provider because there are more problems you can run into when writing to your own disk, for example, if you make two write requests at the same time (like if two users use the command at the same time), you can corrupt the file when the requests try to write at the same time. However setting up an external database is outside of the scope of this question, so here's how you would set up writing to a JSON file:
config.json
{
    "changeableValue": "foo"
}

command.js
const fs = require("fs");
var { changeableValue } = require("config.json");
console.log(changeableValue) // logs "foo"

var updatedValueJSON = JSON.stringify({ changeableValue: "bar" }); // necessary because the JSON object must be converted to a string

fs.writeFile("config.json", updatedValueJSON, "utf8", () => {
    // this is the callback function called when the file write completes
    let { changeableValue } = require("config.json");

    console.log(changeableValue); // logs "bar", and now if you restart the bot and import changeableValue, it will still be bar
});

Comment: How would I implement it into the `_calcset {Value}` command? Thru an argument I'm guessing where I would replace the "bar" with the arg?
Comment: Yes, replace the "bar" argument with the value you want to pass to the function to be saved.


iPad Javascript Debugging

Question: We have a huge client-side application that doesn't work at all on an iPad and we have no idea why.
Unfortunately I don't have a book way of showing or explaining a particular piece of Javascript that doesn't work because from what we call tell, there are none.
Can any heavy Javascript users give me some clues how we can troubleshoot this?
PS - We are a Windows shop, but I would be willing to go buy a MacBook Pro to troubleshoot if need be, but I'd obviously prefer to save the 2 grand if I can.
Comment: Is it a web app? Would you be willing to share the URL? Define _"doesn't work at all"_. Do you know if it only happens on iPads, or also on other devices? Do you do heavy computation in JS, client-side?
Comment: On chrome, using the dev console, you can emulate devices using the phone icon on the upper leftmost part of it.
Answer: I don't use Windows, but I assume you could use virtualization software to run OSX on a PC and then use the Safari remote web inspector:
https://developer.apple.com/safari/tools/
It looks like there are also two tools available if that doesn't work:
https://people.apache.org/~pmuellr/weinre/docs/latest/Home.html
http://www.telerik.com/platform#test

iPad Javascript Debugging


local mean value property for subharmonic functions .

Question: $u$ satisfies  "mean value property locally " on $\Omega$ if for every $x\in \Omega \exists \delta=\delta (x)>0 $   such that
$u(x) \le \frac {1}{|\mu(B(x,r)|}\int_{\partial B(x,r)} u(y) dS_y$
for all $r\le \delta(x)$
Does this imply that if $u\in C^2(\Omega)$ and satisfies mean value property locally in $\Omega$ then $u$ is subharmonic ??
Any hints will be nice.
Comment: Yes, I am sure this is covered in standard texts on potential theory, such as Helms ("Potential Theory"). In most of potential theory, we don't require $C^2$, just upper or lower semi-continuity.
Comment: @Old John : What is the basic argument to extend local property to the global property ?
Comment: Hint: use the 2nd order Taylor expansion of u at x. The first derivatives cancel out in integration, the second derivatives contribute the Laplacian, and nothing else matters.
Comment: From memory, I think it is a connectedness argument, but I think you might have to adjust the statement of the problem above, as I think it would fail if $\Omega$ were not connected.
Comment: @LeonidKovalev : I will try and will try to get back with an answer .
Comment: Interestingly, Ransford (Potential Theory in the Complex Plane) and Hayman and Kennedy (Subharmonic functions) use the local submean property to define subharmonicity.
Comment: @LeonidKovalev : Sir , i need some more hints . I am getting something like $\epsilon \le \int_{\partial B(x,r)} Du(x) (y-x) +\int_{\partial B(x,r)}D^2 u(x) (y-x)^2 $. I doubt if i am on the right track.
Comment: @Theorem You should be aware that $Du$ is a vector, and so is $y-x$, while $D^2u$ is a matrix. Right now you are treating them as if they were numbers. It may help to spell out the vectors and matrices in coordinates $Du=(u_{x_1},\dots,u_{x_n})$, etc.
Answer: We first claim that if a $C^0(\bar{\Omega})$ function $u$ satisfies the following local mean value inequality
$$u(y)\leq\frac{1}{n\omega_nR^{n-1}}\int_{\partial B_R(y)}u  ds \text{ for all } R\leq \delta$$
then maximal principle applies, i.e. $u$ attains its maximum at $\partial \Omega$.
Assume our claim now. Let $\tilde{u}$ be the harmonic function defined by the boundary value $u|_{\partial B}$ on the boundary of an arbitrary ball $B\subset\subset \Omega$. Then $\tilde{u}$  satisfies mean value equality in $B$ since it is harmonic in $B$. Then $u-\tilde{u}$ satisfies the above mean value inequality. Then by our claim (maximal principle), we have $\sup_{x\in B}(u-\tilde{u})=\sup_{x\in\partial B}(u-\tilde{u})$. But $u-\tilde{u}=0$ on $\partial B$. Hence we have $u-\tilde{u}\leq 0$. $u\leq \tilde{u}$ in $B$.
Now we show that $u$ is subharmonic, given an harmonic function $h$  in $B\subset \subset \Omega$, such that $u\leq h$ on $\partial B$. We need to show that $u\leq h$ in B. Since we know $u\leq\tilde{u}$ in $B$. It suffices to show that $\tilde{u}\leq h$ in $B$. To see this one uses the Possion kernel $$\tilde{u}(x)=\int_{\partial B}K(x,y)u(y)ds_y$$
$$h(x)=\int_{\partial B}K(x,y)h(y)ds_y$$
 Since $u(y)\leq h(y)$ on $\partial B$ and $K(x,y)\geq 0$. We have $\tilde{u}(x)\leq h(x)$.
Now we show our claim that the local mean value inequality
$u(y)\leq\frac{1}{n\omega_nR^{n-1}}\int_{\partial B_R(y)}u  ds $
implies maximal principle.
We use the standard topological argument. Define a set $S:=\{q\in\bar{\Omega}| u(q)=\sup_{x\in\bar{\Omega}}u(x)\}$. If $u$ attains maximum at a point $p\in\Omega$ then $S$ is nonempty since $p\in S$. Note that $S$ is closed since every sequence in $S$ converges to a point in $S$ since $u$ is continuous. Next if  $p\in S\cap\Omega$, then  $u(p)\leq\frac{1}{n\omega_nR^{n-1}}\int_{\partial B_R(p)}u  ds $ and $u(p)\geq u(x)$ implies $u(x)=u(p)$ for all $x\in B_R(p)$ since $u$ is continuous. Hence $B_R(p)\in S$
Hence $S$ is open. Now $S$ is open and closed and nonempty, hence we have $S=\bar{\Omega}$. This proves our claim and finished our proof.
Comment: Thanks for your editing, Byron.
Comment: Shouldn't we be proving that $- \Delta u \leq 0$? Why do you show that $u \leq h$ instead?
Answer: No, a function satisfying a mean-value inequality is not necessarily $C^2$ (think of the norm function $\mathbb R^d\supseteq\Omega\ni\vec x\mapsto|\vec x|\in\mathbb R$) but if it satisfies a mean-value equality it is harmonic and therefore $C^\infty$ (in fact, analytic).
Yes, a function's being (sub/super)mean-valued is (sub/super)harmonic, but you need to interpret the Laplacian in a generalized sense. For example, in my example above the Laplacian is a dirac-delta which is a positive distribution (testing against positive test functions yields a positive output).


host with default gateway as itself

Question: I am facing a peculiar problem. Earlier we had 4 network segments in our production setup, say segment A,B,C and D. A,B and C are able to communicate with each other,the corporate lan and the internet. Segment D is completely isolated segment and purely used for backup and management. so a host Z only on segment D was not able to access any of the other segment.
We recently introduced vmvare vsphere 5.1 setup in our production environment. We have created a distributed switch in vcenter. The distributed switch has uplinks from all the 4 network segments. We have created separate port group for each segment as well.
Now the problem is the host D is now able to communicate with other segments, but only those in the vmware setup, ie hosts attached to the distributed switch. Physical machines in other segments are still not accessible by machine Z.
Now this is my analysis of the problem.

Checking the host Z, if found the the default gateway was set as host Z itself.
A vsphere distributed switch behaves like an L2 switch and port groups are just a group of ports and does not mark any isolation between them.
Since the default gateway is maintained, there is path in the host Z routing table for all other segments. ie the packets reach the D segment switch[point 1].The switch is then sending these packets through the uplinks to the vsphere distributed switch, Keeping point 2 in mind, the packets reaches the destination host.

Point 3 is where I am confused[specifically, the part which is bolded], may be due to my less knowledge in the networking side. Since for machine Z, the gateway is itself, any packet sent for other segments should return to itself....!!.??..or I know that there is something called the spanning tree protocol, which prevents looping in the network. Is this coming into play....?? How is the packet reaching my distributed switch....??
Please correct me if any of the points are wrong and many thanks in advance.
Comment: Spanning Tree prevents traffic storms when you connect multiple switches together: A to B, B to C, and then C back to A, by detecting the presence of a physical loop and automatically blocking one of those three paths to prevent the switches from forwarding the same traffic over and over in a circle... so that is unlikely to be related.  The default gateway isn't relevant if host Z has an IP address on the same subnet as other hosts, since the gateway is only used to reach hosts that are *not* on the same IP subnet.  Describing the IP subnetting scheme may be useful, here.
Comment: hai michael,  Thanks for the reply. A i mentioned in another comment, we have separate physical switches for the 4 segments. Routers are maintained for segments A,B and C and they can communicate with each other,corporate lan and internet. Switch for segment D is physically isolated. It is not connected to any router.  What i noticed is the moment i set default gateway of host Z as itself or any other machine's IP in segment D, its able to communicate to machines in other segment,but only those attached to the vmware VDS. Physical machine is other segments are still not accessible.
Comment: Physical machine is other segments are still not accessible. please note that host Z is attached only to segment D switch which has no routers connected to it.
Answer: At last got the answer to my question. Its  was due to how Linux implelemts TCP/IP stack. By default it uses weak host model.[http://en.wikipedia.org/wiki/Host_model] . The Remote hosts  network adapter which was connected to the private network was responding to request on the ip of the other adapter due to this.
The host Z was always accessing the private network D only . As mentioned by sean,since the default gateway of Z was set to itself, it would try to sent packets directly to any other host, which supported the behaviour.
Answer: It sounds to me like your network is not actually segmented how you describe.  Is it possible that the distributed switch is using the same VLAN number for all port-groups or possibly not using VLANs at all?  If packets are not being VLAN tagged via the VDS, that would explain why there is undesired connectivity inside of vSphere, and that same connectivity is not observed on the physical uplinks.
It might be helpful to provide more details about IP/masking across your environment, as well as router interfaces to explain the segmentation in more detail.
In any case, I hope this much might be useful.  Good luck.
Comment: hai sean, thanks for the reply and you are correct. We are not using vlans. We have seperate switches for each segment. I m not clear how the packets are reaching the VDS at first place when the default gateway is the host Z itself.Any light on this..?
Comment: it is possible that the IP and netmask on host Z are set in a way that the host does not think it needs a gateway to reach the hosts on other segments.  the fact that you are not using VLANs means that the hosts within vSphere would be able to reach each other without a router, depending on how their IP/mask is configured.
Comment: the moment i remove the gateway setting on machine Z, its not able to communicate with other segments. This shows that, the gateway has something to do with the behavior. Yes, the hosts within vsphere are able to reach one another depending on their IP/MASK settings.
Comment: with a default route set to it's own interface, the server would attempt to send packets directly to any other hosts.  this is much like host Z having a mask that summarizes all of your networks.  again, it would be helpful for you to describe your subnet scheme.  since your virtual network is not segmented, there would be more going on at layer-2 than you might think.  to prevent cross-network communication, you would really want to assign VLAN numbers to the port-groups on your VDS, forcing hosts to go through their respective routers to reach other segments.
Comment: ok, thanks.  on host z, remove the default route and use a /16 mask.  the connectivity will still work because all networks are using a common (default) VLAN.  please tell me if this works.
Comment: i guess you didn't say what network D is, so I should not have assumed.  if it is another 10.72.X.X network, then my last comment should work.
Comment: sorry sean, i didnt want to disclose the details but accidental posted it. I can add that A,B and C are /24 networks and D is a /21 network. The host Z has only one interface card with D segment IP. Its routing table contains an entry for the D segment and not for any segments. I also noticed that if i change the gateway and set it as any other D segment ip in segment D in host Z, its still able to communicate to other segment machines in vmware setup.
Comment: do the /24 subnets A/B/C fall in the same range as the host z /21?  if that is the case, host z would attempt to directly access any address (no routing) on those subnets.
Comment: i think the possibily is something like yu suggested in your earlier post **"with a default route set to it's own interface, the server would attempt to send packets directly to any other hosts. this is much like host Z having a mask that summarizes all of your networks."**  Can you tell me why this might be happening....?? The same behaviour is observed when i set gateway as any other D segment IP. Is your suggestion applicable in this case also....??
Comment: no the /24 subnets A/B/C doesnot fall in the range of /21 segment
Comment: sorry, i cannot answer because i don't know how your other D segment IPs are being set.  fwiw, posting addresses and masks in private ranges is pretty low risk...  I have no way of accessing those networks unless I am already inside your environment.
Comment: sorry sean, my seniors are not allowing me to share the info. All other D segment IP are set in the same way as host Z
Comment: hai sean, i thnk as u said in your comment **with a default route set to it's own interface, the server would attempt to send packets directly to any other hosts. this is much like host Z having a mask that summarizes all of your networks** is what is happening. I checked the network packets using wireshark and saw the host Z sending an arp request for ip of the remote machine directly without first issuing an arp for the gateway(cleared arp cache first), and since the physical and DS was connected , the machine recivd the packet and responded. Its like the switches are being cascaded.plz sgst

host with default gateway as itself


clarification needed on exec usage in python

Question: I have this:
>>> d = {}
>>> d["hi"] = 12345

>>> d1 = {}

>>> d1["hiiii"] = 1234590

I know why I get an error below. This is because exec could not find variables hi and hiiii.
>>> exec "print hi, hiiii"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'hi' is not defined

>>> exec "print hiiii"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'hiiii' is not defined

Now it works because exec was able to find hi and hiiii variables in dictionary d and d1
>>> exec "print hi, hiiii" in d , d1
12345 1234590

So far so good.
Question:
Now when I print d I see that it has been modified and prints lot of key,value pairs..why?
But on printing d1 I do not see lot of key,value pairs, why so?
Answer: This is explained in the docs:

As a side effect, an implementation may insert additional keys into the dictionaries given besides those corresponding to variable names set by the executed code. For example, the current implementation may add a reference to the dictionary of the built-in module __builtin__ under the key __builtins__ (!).


for i in range(0, int(num[pos])): TypeError: 'int' object is not subscriptable

Question: def validar(pergunta, min, max):
    x = int(input(pergunta))
    while((x < min) or (x > max)):
        print('Código Inválido')
        print('Digite um número inteiro entre 10000 e 30000')
        x = int(input(pergunta))
    return x

def calcular(num):
    print('Dígito          |', end='')
    pos = 0
    while pos < 5:
        for i in range(0, int(num[pos])):
            print(f'{i} |', end='')
            pos += 1
    print()
    print('Peso            |', end='')
    for peso in range(2, 7):
        print(f'{peso:^5} |', end='')
    print()
    print('Multiplicação   |', end='')
    soma = 0
    peso1 = 2
    resto = 0
    for d in range(0, 5):
        for digito in num:
            resultado = int(digito[d]) * peso1
            soma += resultado
            peso1 += 1
            resto = soma % 7
            print(f'{resultado:^5} |', end='')
    print(f'   Soma todos = {soma}')
    print('-' * 75)
    print(f'                                                     Resto de {soma} por 7 = {resto}')
    print('-' * 75)
    print(f'{int(num[0])} - {resto}')
    print('------')
    return f'{num}-{resto}'

digito = validar('Digite o código do produto: ', 10000, 30000)

calcular(digito)

Comment: Por favor, explique exatamente qual é a sua dúvida e como podemos lhe ajudar. Não jogue simplesmente o código em uma pergunta.
Comment: Para saber melhor como fazer uma pergunta, clique [aqui](https://pt.meta.stackoverflow.com/a/8046/101).
Comment: Votei para fechar como precisando de mais detalhes, mas me equivoquei. O Voto de fechamento correto é devido a qualidade. Na função `validar()` o retorno é sempre um inteiro `x = int(input(pergunta))` o que implica que na linha `for i in range(0, int(num[pos])):` sempre será gerado um erro pois `num` é o retorno de `validar()` e sendo um inteiro não pode ser fatiado `num[pos]`. O problema pode ser facilmente detectado [fazendo a depuração do código](https://pt.meta.stackoverflow.com/q/7785/137387).
Comment: Não da para saber certamente o quer fazer, mas analisando o seu código acho que você está tentando fazer isso https://ideone.com/Nnt81K
Answer: No código for i in range(0, int(num[pos])):, mais especificamente aqui: int(num[pos]), você está tentando acessar a posição 0 de um número inteiro, no caso esse número é a sua variável num.
Esse erro (TypeError: 'int' object is not subscriptable), segunda a documentação do python, ocorre quando você tenta acessar uma função como se fosse um objeto iterável. No caso, você está tentando tratar esse número inteiro como se fosse um Array, porém isso não funciona.


Is having the same PTR hostname valid for multiple ip addresses?

Question: Currently I have the following setup with two hostnames and two ips:
cheeze1.mydomain.com    IN  A   22.214.171.124
126.96.36.199.in-addr.arpa    IN  PTR cheeze1.mydomain.com

cheeze2.mydomain.com    IN  A   18.104.22.168
184.108.40.206.in-addr.arpa    IN  PTR cheeze2.mydomain.com

I want to change to having a round-robin dns for a single hostname using the two ips. Are the following PTR records valid? Can a host have multiple IPs and with each having valid reverse dns resolution?
cheezeonly.mydomain.com IN  A   188.8.131.52
cheezeonly.mydomain.com IN  A   18.104.22.168
184.108.40.206.in-addr.arpa    IN  PTR cheezeonly.mydomain.com
184.108.40.206.in-addr.arpa    IN  PTR cheezeonly.mydomain.com

EDIT: Please note that this question isn't asking the same as suggested in comments.
I'm going to answer this one myself, you guys are no help marking it as duplicate and not reading the question properly. Hopefully this answer will help others.
ANSWER:::
Yes, it is valid, and yes it will pass a FcRDNS check.
From the "Pro DNS and BIND" book:
http://www.zytrax.com/books/dns/ch9/rr.html
An alternate approach is to define multiple A records with the same mail server name:
; zone file fragment
        IN  MX  10  mail.example.com.
....
mail    IN  A       192.168.0.4
        IN  A       192.168.0.5
        IN  A       192.168.0.6

In this case the load-balancing effect is under the control of BIND and the rrset-order record. In order to avoid problems if the receiving mail system does reverse look-up as a spam check then the PTR records for 192.168.0.4, 192.168.0.5, 192.168.0.6 above must all define (resolve to) mail.example.com.
And from RFC1912: Common DNS Operational and Configuration Errors
"For every IP address, there should be a matching PTR record in the in-addr.arpa domain. If a host is multi-homed, (more than one IP address) make sure that all IP addresses have a corresponding PTR record (not just the first one). Failure to have matching PTR and A records can cause loss of Internet services similar to not being registered in the DNS at all. " –
Therefor this configuration is valid and passes FcRDNS checks.
Comment: re: dups:: no, those aren't what I'm asking. The first is about multiple PTR for a single IP and the second is about having having two different IPs resolve to a single host, which the A record only resolves to one IP, failing fcrdns check.
Comment: i got way more freaking hassle from the community then help to solve this question.
Comment: could you please post your answer as an answer to your own question, rather than in the question itself?
Comment: you guys don't give up. I can't answer my own question, no option to add an answer since douches marked it as duplicate. @dbr at the top of the screen it says "This question already has an answer here:" .... it's disabled the add answer feature for me.
Answer: Yes, it's valid. But...
Some programs do a "double-reverse lookup" or as Wikipedia calls it, Forward-confirmed reverse DNS. Quoting from the wikipedia entry, "RFC 1912 and RFC 1033 (Informational) recommend it as a best practice, but it is not a requirement of standard defining RFCs governing operation of the DNS." (emphasis, mine).  The programs that do this will complain or refuse service to/from that IP/hostname.
Comment: this would pass a FcRDNS check though...