Is it possible to display Entityform Types using Page Manager and Panels in D7?

Question: Currently, I have a D7 site and my main Content region is displayed using Page Manager and Panels variants. I've created an Entityform Type that allows users to request an appointment, and I'd like this specific entityform type to have a different layout than what the default page.tpl.php provides.
I'd love to provide a default panels layout for all Entityform types, but I can't seem to find a way to do this (even using the Entityform Panels module.) I've come close by using the "Page manager existing pages", but submission pages display in the default page.tpl.php.
Is there a way to do this?
Answer: What we have done so far, is to reference an Entity-Form in an node type with entityreference.
This works so far.
The Form will be displayed in the panelized theme and the preview will show up too in the correct context.
But!

The Preview will not show the labels of empty fields
The submission Page will not show in the correct layout and is still loosing context (even with pm-existing-pages)
List fields are broken, if core Patch https://www.drupal.org/node/1677598 is applied they don't break the form submit, but are empty in the preview and not saved.
Date fields with time are somehow broken too. Time is not safed, Date only when using the PopUp Calender

We decided to use the redirect option instead of the submission page to workaround the layout problem with the submission.
The Preview is still broken and we are trying to get it fixed.
Conclusion: Entityforms and Panels do not play well together. If we would have know this before we would have built a custom module or used Webform 4.x instead (we are still using webform 3.x in this site but there you don't have the option to use views to manipulate submitted data without loading another bunch of buggy modules!)
Hopfully Drupal 8 and YAML-Forms do a better Job in the future.


on() e bind() não estão funcionando

Question: Estou usando off() em um elemento para desabilitar a sua funcionalidade e preciso habilitá-lo novamente com on(). Mas não está funcionando quando on() é executado...
Aqui está o código, estou tentando prevenir que um formulário seja enviado 2 vezes quando é clicado num botão:
$("#meuBotao").click(function (e) {
    $(this).off("click");
    $.ajax({
    url: "/page",
    type: "POST",
    complete: function() {
                    $(this).on("click");
    },
                ...

O que eu estou fazendo de errado? Eu tentei com on() e off(), e com bind() e unbind() também (que estão deprecated para as versões antigas agora, mas deveria funciona ainda assim).
Answer: Pelo que eu entendi você quer desabilitar o botão enquanto o AJAX está rodando para o usuário não conseguir disparar várias requisições, correto? Neste caso poderia ser feito assim:
 $("#meuBotao").on('click',function(){
    var el = $(this);
    el.prop('disabled',true); //desabilita o botão
    $.ajax({
    url: "/page",
    type: "POST",
    complete: function(){
        el.prop('disabled',false); //habilita botão novamente
    },
    //...

Note que eu criei uma nova variavel el para manusear o elemento $(this), de forma que ele funcione corretamente mesmo dentro de outros escopos (como no caso da funcão disparada no complete do AJAX).
Eu também troquei .click() por .on('click') pelo fato de este segundo ser mais recomendado por vários motivos.
Comment: Neste caso não faz nenhuma diferença usar `click` ou `on`.
Comment: O próprio teste que você linkou mostra que isso não é verdade. Só existe diferença de performance entre usar delegação ou não.
Comment: @bfavaretto Na verdade, dando uma de chato, tem sim, é comprovado que e método `.on()` é [mais](http://www.brentsowers.com/2012/03/jquery-on-performance.html) [performático](http://jsperf.com/jquery-on-versus-click/2), portanto, mesmo sem aproveitar completamente as funcionalidades desse método, ainda é vantajoso usá-lo.
Comment: Acho que usar `.on` ou `.click` neste caso é irrelevante e não creio ser mais recomendado aqui. O `.on` como linkou é usado para delegar eventos, que não se aplica aqui.
Comment: @Sergio o `.on` não se limita somente ao uso com delegação de eventos, na verdade o uso dele no lugar de *antigos* delegadores é até incentivado [no próprio blog](http://blog.jquery.com/2011/11/03/jquery-1-7-released/) do jQuery.
Answer: O principal problema aqui é que o this dentro da função ajax não é o mesmo que o this fora da função. O escopo é diferente... Isso tem solução fácil, que é criar uma variável intermédia que aponta para o mesmo objeto:
$("#meuBotao").click(function (e) {
    $(this).off("click");
    var self = this; // assim guardamos o apontador no "self"
    $.ajax({
        url: "/page",
        type: "POST",
        complete: function() {
            $(self).on("click"); // aqui usa o "self". Já agora, aqui falta a função a correr quando o click fôr gerado
        },
            ...

À parte desse detalhe existem outras maneiras mais usadas para impedir cliques, em vez de remover e adicionar eventos. Uma delas é criar uma flag/bandeira como propriedade no elemento ou uma variável que guarda a informação de se o elemento pode ser clicado ou não.
Um exemplo disto seria:
$("#meuBotao").click(function (e) {
    if (!$(this).data('clicavel')) return false;
    $(this).data('clicavel', false);
    var self = this; // assim guardamos o apontador no "self"
    $.ajax({
    url: "/page",
    type: "POST",
    complete: function() {
          $(self).data('clicavel', true);
    },
                ...

Pode inclusive fazer o mesmo adicionando CSS pointer-events: none; numa classe, ou diretamente no elemento. Pode ver mais ideias nesta resposta: https://pt.stackoverflow.com/a/2353/129
Nota: no seu código $(this).on("click"); falta o segundo parâmetro da função que indica que código correr quando o click for recebido...
Comment: Muito obrigado!

on() e bind() não estão funcionando


Exchange 2010 Mailbox Server Reinstall

Question: I need to reinstall the OS on a mailbox server.
If I:

backup databases
uninstall exchange
redo the OS
reinstall exchange
restore databases

... will the config for that server remain (user mailboxes etc)?
If not, what process should I follow?
Edit: This is not the only exchange sever. Will the configuration remain so long as there is at least one server remaining?
Answer: To directly answer your question, yes the Exchange config for the server will remain as long as the newly re-installed server has the exact same fully-qualified name as it originally had.  All of the config settings for an Exchange 2007 and later server are stored in AD.  So when you run setup Setup.exe with the /m:RecoverServer switch

Setup.exe /m:RecoverServer

then the Exchange installer will look into AD and get the previous configurations for the server and set this new instance up in the same way.  You just have to make sure that the names are identical.
As for backing up databases and all, remember that you can move a mailbox database to another mailbox server and keep it active/online while this server is unavailable.  So do that, in a big way.  If you plan your database moves right (or, even better, have a DAG), and if you're using a good load balancer for your CAS roles, you can actually loose an entire Exchange server with no impact to the end users.
If this is your first time rolling through an Exchange server like this, then I recommend hitting the Oracle of Google for some step-by examples or videos.  I just saw these in a quick search, they have good info but depending on your comfort level you may want more/less:

http://ripusudan.wordpress.com/2012/10/09/how-to-customize-ms-office-2010-installation-using-oct/
http://www.exchange2010.com/2011/06/setupcom-mrecoverserver-when-server-is.html
or straight from the horse's mouth http://technet.microsoft.com/en-us/library/dd876880(v=exchg.150).aspx
Answer: I suggest:

move all the Exchange roles/mailboxes/redirect traffic from that server to another server (the other one You mentioned you already have or better -> setup a temporary one)
make a clean Uninstall of exchange from that server You want to reinstall after moving all mailboxes/roles.
reinstall server / exchange
move back the roles/mailboxes/redirect traffic to new installation and make a clean uninstall of the temporary instance if You used it.

That way You will keep everything online for Your users and minimize downtime.

Exchange 2010 Mailbox Server Reinstall


Android: Acessing front facing camera for Android 2.3

Question: There really seems to be no information on how to acess the front facing camera on android phones (gingerbread).
Could someone please point me to a page or post that explains how it's done?
Thanks!
Comment: And oh yeah someone with higher rep should really add a front facing tag since I probably wont be the only one asking about this in the months to come ;)
Answer: Here is an example on how to access different cameras and switch between them: CameraPreview
The link is not accessible right now, Google has moved the Sample Project.
Please import a Sample Project and find it at:
ApiDemos/com.example.android.apis.graphics/CameraPreview.java
Answer: Mat be this might help you How to use Front Facing Camera on Samsung Galaxy S
As for 2.3 Camera you can try this method passing the camera ID
Comment: Thanks for your quick reply but that is a Galaxy S specific sollution before Gingerbread was released.


Understanding a subsequence converges in the proof of completeness of $L^p$ in Stein-Shakarchi's Functional Analysis

Question: I am trying to understand the following proof of completeness of $L^p$ in Stein-Shakarchi's Functional Analysis. (See the proof on page 5 of the link or at the end of this post.)
In the proof, it is said that:

Since
  (by construction of the telescopic series) the $(K − 1)^{\mathrm{th}}$ partial sum of
  this series is precisely $f_{n_K}$ , we find that $f_{n_K}\to f$ a.e.

Question 1: why is this true?
What I tried is $f(x)=f_{n_1}(x)+f_{n_{K+1}}-f_{n_1}(x)+(f_{n_{K+2}}+f_{n_{K+3}}+...)=f_{n_{K+1}}+(f_{n_{K+2}}+f_{n_{K+3}}+...)$
If $K\to\infty$ is it correct to conclude $f_{n_K}\to f$ ?
Question 2: why $2^p|f(x)|^p+2^p|S_K(f)(x)|^p\le2^{p+1}|g(x)|^p,$ for all $K$ ?
Comment: Which book is the excerpt from? Stein-Shakarchi?
Comment: @Jack from this page 5 http://assets.press.princeton.edu/chapters/s9627.pdf
Answer: This is Theorem 1.3 in Section 1.2 (page 5) of Stein-Shakarchi's Functional Analysis.
Note that

the $(K-1)^{\mathrm{th}}$ partial sum in the proof refers to $S_K(f)(x)$, which by the definition formula equals to $f_{n_K}$;
by the proof, $S_K(f)\to f$ almost everywhere.

Thus the authors conclude that $f_{n_K}=S_{K-1}(f)\to f$ almost everywhere.
For the second question, simply note that by the triangle inequality,
$$
|f(x)|\leq |g(x)|,\quad |S_K(f)|\leq |g(x)|.
$$
Comment: The proof in Stein-Shakarchi: "... hence the series defining $f$ converges almost everywhere, and $f\in L^p$".
Comment: - by the proof, $S_K(f)\to f$ a.e. what proof are you citing ?
Comment: though it is $_{_}=_{−1}()$ without the last term $K$, even still it holds $_{_}→ $ ?
Comment: @galleta For any convergent sequence of complex numbers $(z_k)$, $\lim_{k\to\infty}z_{k}=\lim_{k\to\infty}z_{k-1}$.
Comment: Now makes sense, Thank you for your help Jack


Queue size appears to be the ENV size in SimPy

Question: I am just starting to work on an event simulation, and I am having some issues with monitoring the queue.
It appears that everytime I check the queue, it is actually showing the Env.now.  Any advice?
import simpy

num_of_machines = 2

env = simpy.Environment()
bcs = simpy.Resource(env, capacity=num_of_machines)

def monitor(resource):
     """This is our monitoring callback."""

     print('Queue size: %s' % len(resource.queue))

def process_client(env, name):

    with bcs.request() as req:
        yield req
        print('%s starting to charge at %s' % (name, env.now))
        yield env.timeout(90)
        print('%s ending charge at %s' % (name, env.now))
        monitor(bcs)

def setup(env):
    i = 0

    while True:
        i += 1
        yield env.timeout(1)

        env.process(process_client(env, ('Car %s' % i)))

env.process(setup(env))

env.run(until=300)

Results:
Car 1 starting to charge at 1
Car 2 starting to charge at 2
Car 1 ending charge at 91
Queue size: 88
Car 3 starting to charge at 91
Car 2 ending charge at 92
Queue size: 88
Car 4 starting to charge at 92
Car 3 ending charge at 181
Queue size: 176
Car 5 starting to charge at 181
Car 4 ending charge at 182
Queue size: 176
Car 6 starting to charge at 182
Car 5 ending charge at 271
Queue size: 264
Car 7 starting to charge at 271
Car 6 ending charge at 272
Queue size: 264
Car 8 starting to charge at 272

Comment: So what exactly is your problem?
Comment: I am trying to figure out how many cars are in the queue waiting to charge
Answer: You spawn a process_client() every timestep, so when the first of these processes is done after 90 time steps, you already have created 90 new processes that are queueing up.  So your numbers are looking quite right.


Why does this custom CKEditor plugin produce the toolbarview-item-unavailable error?

Question: I have 2 modules in active development with the purpose of learning how to develop custom plugins for the Ckeditor5 wysiwyg.
On both modules, I am stuck on the following problem. The error pasted below is from the second module :
ckeditor5-dll.js?v=35.4.0:5 toolbarview-item-unavailable {item: 'testPlugin'}
Read more: https://ckeditor.com/docs/ckeditor5/latest/support/error-codes.html#error-toolbarview-item-unavailable

Clearing indicated my plugin cannot be included in the toolbar.
With the module enabled, my testPlugin module is visible and added to my active toolbar in the text-formats configuration area as show below:

However, when on a node-edit form the plugin icon is not rendered in the toolbar due to the javascript error included above :

The full code for the second module is located here for your reference but I pasted some essential code below for anyone who wants to help or refer to this question in the future:
testPlugin.ckeditor5.yml
testplugin_embeddedContent:
  provider: testplugin
  ckeditor5:
    plugins:
      - embeddedContent.EmbeddedContent
    config:
#      embeddedContent:
      testPlugin:
        openDialog:
          func:
            name: Drupal.ckeditor5.openDialog
            invoke: false
        dialogSettings:
          height: 75%
          dialogClass: embedded-content-widget-modal
          title: Create embedded content
  drupal:
    label: Test Plugin
    elements:
      - <embedded-content>
      - <embedded-content data-plugin-config data-plugin-id>
    admin_library: testplugin/admin.embedded_content
    class: Drupal\testplugin\Plugin\CKEditor5Plugin\EmbeddedContent
    library: testplugin/embedded_content
    toolbar_items:
#      embeddedContent:
      testPlugin:
        label: My Test Plugin
    conditions:
      filter: testplugin

index.js:
import EmbeddedContent from "./embeddedcontent";

/**
 * @private
 */
export default {
  EmbeddedContent: EmbeddedContent
};

embeddedcontent.js:
import { Plugin } from 'ckeditor5/src/core';
import EmbeddedContentEditing from './embeddedcontentediting';
import EmbeddedContentUI from './embeddedcontentui';

/**
 * Main entry point to the embedded content.
 */
export default class EmbeddedContent extends Plugin {

  /**
   * @inheritdoc
   */
  static get requires() {
    return [
      EmbeddedContentEditing,
      EmbeddedContentUI
    ];
  }

  /**
   * @inheritdoc
   */
  static get pluginName() {
    // return 'embeddedContent';
    return 'testPlugin';
  }
}

embeddedcontentediting.js:
import {Plugin} from 'ckeditor5/src/core';
import {toWidget, Widget} from 'ckeditor5/src/widget';
import EmbeddedContentCommand from './embeddedcontentcommand';

/**
 * Embedded content editing functionality.
 */
export default class EmbeddedContentEditing extends Plugin {

  /**
   * @inheritdoc
   */
  static get requires() {
    return [Widget];
  }

  /**
   * @inheritdoc
   */
  init() {
    this.attrs = {
      embeddedContentPluginConfig: 'data-plugin-config',
      embeddedContentPluginId: 'data-plugin-id',
    };
    const options = this.editor.config.get('embeddedContent');
    if (!options) {
      return;
    }
    const {previewURL, themeError} = options;
    this.previewUrl = previewURL;
    this.themeError =
      themeError ||
      `

${Drupal.t(
        'An error occurred while trying to preview the embedded content. Please save your work and reload this page.',
      )}

    `;

    this._defineSchema();
    this._defineConverters();

    this.editor.commands.add(
      'embeddedContent',
      new EmbeddedContentCommand(this.editor),
    );
  }

  /**
   * Fetches the preview.
   */
  async _fetchPreview(modelElement) {
    const query = {
      plugin_id: modelElement.getAttribute('embeddedContentPluginId'),
      plugin_config: modelElement.getAttribute('embeddedContentPluginConfig'),
    };
    const response = await fetch(
      `${this.previewUrl}?${new URLSearchParams(query)}`
    );
    if (response.ok) {
      return await response.text();
    }

    return this.themeError;
  }

  /**
   * Registers embeddedContent as a block element in the DOM converter.
   */
  _defineSchema() {
    const schema = this.editor.model.schema;
    schema.register('embeddedContent', {
      allowWhere: '$block',
      isObject: true,
      isContent: true,
      isBlock: true,
      allowAttributes: Object.keys(this.attrs),
    });
    this.editor.editing.view.domConverter.blockElements.push('embedded-content');
  }

  /**
   * Defines handling of drupal media element in the content lifecycle.
   *
   * @private
   */
  _defineConverters() {
    const conversion = this.editor.conversion;

    conversion
      .for('upcast')
      .elementToElement({
        view: {
          name: 'embedded-content',
        },
        model: 'embeddedContent',
      });

    conversion
      .for('dataDowncast')
      .elementToElement({
        model: 'embeddedContent',
        view: {
          name: 'embedded-content',
        },
      });
    conversion
      .for('editingDowncast')
      .elementToElement({
        model: 'embeddedContent',
        view: (modelElement, {writer}) => {
          const container = writer.createContainerElement('figure');
          return toWidget(container, writer, {
            label: Drupal.t('Embedded content'),
          });

        },
      })
      .add((dispatcher) => {
        const converter = (event, data, conversionApi) => {
          const viewWriter = conversionApi.writer;
          const modelElement = data.item;
          const container = conversionApi.mapper.toViewElement(data.item);
          const embeddedContent = viewWriter.createRawElement('div', {
            'data-embedded-content-preview': 'loading',
            'class': 'embedded-content-preview'
          });
          viewWriter.insert(viewWriter.createPositionAt(container, 0), embeddedContent);
          this._fetchPreview(modelElement).then((preview) => {
            if (!embeddedContent) {
              return;
            }
            this.editor.editing.view.change((writer) => {
              const embeddedContentPreview = writer.createRawElement(
                'div',
                {'class': 'embedded-content-preview', 'data-embedded-content-preview': 'ready'},
                (domElement) => {
                  domElement.innerHTML = preview;
                },
              );
              writer.insert(writer.createPositionBefore(embeddedContent), embeddedContentPreview);
              writer.remove(embeddedContent);
            });
          });
        };
        dispatcher.on('attribute:embeddedContentPluginId:embeddedContent', converter);
        return dispatcher;
      });

    Object.keys(this.attrs).forEach((modelKey) => {
      const attributeMapping = {
        model: {
          key: modelKey,
          name: 'embeddedContent',
        },
        view: {
          name: 'embedded-content',
          key: this.attrs[modelKey],
        },
      };
      conversion.for('dataDowncast').attributeToAttribute(attributeMapping);
      conversion.for('upcast').attributeToAttribute(attributeMapping);
    });
  }

  /**
   * @inheritdoc
   */
  static get pluginName() {
    return 'embeddedContentEditing';
  }
}

embeddedcontentui.js:
import { Plugin } from 'ckeditor5/src/core';
import { ButtonView } from 'ckeditor5/src/ui';
import EmbeddedContentIcon from '../theme/icons/embeddedcontent.svg';
import {DomEventObserver} from "ckeditor5/src/engine";

/**
 * Ckeditor5 doesn't support double click out of the box.
 * Register it here so we can use it.
 *
 * @Todo Replace double click with a balloon style popup menu to
 *   edit the embedded content item.
 */
class DoubleClickObserver extends DomEventObserver {
  constructor( view ) {
    super( view );
    this.domEventType = 'dblclick';
  }

  onDomEvent( domEvent ) {
    this.fire( domEvent.type, domEvent );
  }
}

/**
 * Provides the embedded content button and editing.
 */
export default class EmbeddedContentUI extends Plugin {

  init() {
    const editor = this.editor;
    const options = this.editor.config.get('embeddedContent');
    if (!options) {
      return;
    }

    const { dialogURL, openDialog, dialogSettings = {} } = options;
    if (!dialogURL || typeof openDialog !== 'function') {
      return;
    }
    editor.ui.componentFactory.add('embeddedContent', (locale) => {
      const command = editor.commands.get('embeddedContent');
      const buttonView = new ButtonView(locale);

      buttonView.set({
        label: Drupal.t('Embedded content'),
        icon: EmbeddedContentIcon,
        tooltip: true,
      });

      // Bind the state of the button to the command.
      buttonView.bind('isOn', 'isEnabled').to(command, 'value', 'isEnabled');

      this.listenTo(buttonView, 'execute', () => {
        openDialog(
          dialogURL,
          ({ attributes }) => {
            editor.execute('embeddedContent', attributes);
          },
          dialogSettings,
        );
      });

      return buttonView;
    });

    const view = editor.editing.view;
    const viewDocument = view.document;

    view.addObserver( DoubleClickObserver );

    editor.listenTo( viewDocument, 'dblclick', ( evt, data ) => {
      const modelElement = editor.editing.mapper.toModelElement( data.target);
      if(modelElement && typeof modelElement.name !== 'undefined' && modelElement.name === 'embeddedContent'){
        const query = {
          plugin_id: modelElement.getAttribute('embeddedContentPluginId'),
          plugin_config: modelElement.getAttribute('embeddedContentPluginConfig'),
        };
        openDialog(
          `${dialogURL}?${new URLSearchParams(query)}`,
          ({ attributes }) => {
            editor.execute('embeddedContent', attributes);
          },
          dialogSettings,
        );
      }
    } );
  }
}

embeddedcontentcommand.js:
import { Command } from 'ckeditor5/src/core';

/**
 * Creates embedded content
 */
function createEmbeddedContent(writer, attributes) {
  return writer.createElement('embeddedContent', attributes);
}

/**
 * Command for inserting <embedded-content> tag into ckeditor.
 */
export default class EmbeddedContentCommand extends Command {
  execute(attributes) {
    const embeddedContentEditing = this.editor.plugins.get('embeddedContentEditing');

    // Create object that contains supported data-attributes in view data by
    // flipping `DrupalMediaEditing.attrs` object (i.e. keys from object become
    // values and values from object become keys).
    const dataAttributeMapping = Object.entries(embeddedContentEditing.attrs).reduce(
      (result, [key, value]) => {
        result[value] = key;
        return result;
      },
      {},
    );

    // \Drupal\media\Form\EditorMediaDialog returns data in keyed by
    // data-attributes used in view data. This converts data-attribute keys to
    // keys used in model.
    const modelAttributes = Object.keys(attributes).reduce(
      (result, attribute) => {
        if (dataAttributeMapping[attribute]) {
          result[dataAttributeMapping[attribute]] = attributes[attribute];
        }
        return result;
      },
      {},
    );

    this.editor.model.change((writer) => {
      this.editor.model.insertContent(
        createEmbeddedContent(writer, modelAttributes),
      );
    });
  }

  refresh() {
    const model = this.editor.model;
    const selection = model.document.selection;
    const allowedIn = model.schema.findAllowedParent(
      selection.getFirstPosition(),
      'embeddedContent',
    );
    this.isEnabled = allowedIn !== null;
  }
}

I would appreciate some help understanind what I'm missing or doing wrong.
Thanks in advance.
Comment: Please include minimal code to reproduce the problem _in the question body_, rather than linking to a full set of code. That question will just get closed otherwise, as this question will fail to be useful in the future when you remove the broken code from the external site. This is the sort of question that ends up being very useful for future developers so let's get an exemplary canonical version of it created now for the future generations :)
Comment: Is the information at https://ckeditor.com/docs/ckeditor5/latest/support/error-codes.html#error-toolbarview-item-unavailable unhelpful?
Comment: Hi @cilefen.
I did look at the documentation but it does not really offer a solution but only mentions that the plugin fails to load for some reason - which I already know
Comment: Thanks @Clive. I included some of the essential code. Apologies, it goes beyond minimal
Answer: I would recommend keeping your class name and plugin name consistent. In embeddedcontent.js the class is EmbeddedContent but the plugin is testPlugin. It looks like you have commented-out lines in your ckeditor5.ymlthat would declare the plugin as embeddedContent, try committing to that and removing testPlugin.


RegEx, preg_replace_callback Question PHP

Question: This is what I've got for for my RegEx, I was wondering if this is the best way.
I want to be able to find something similar regardless of the spacing between Identifiers and not be case sensitive.  And if possible, not worry about order..
Example:
[Foreclosure ="Remax" URL="http://www.remax.com" Title = "4 Bedroom 2 Bath Condo"]
[Foreclosure ="Remax"URL="http://www.remax.com"Title="4 Bedroom 2 Bath Condo"]
[Foreclosure  =   "Remax"    URL="http://www.remax.com"     Title = "4 Bedroom 2 Bath Condo"    ]

Here's my existing Code:
function ForeclosureCode_filter( $buffer )
{
    //There might be a better way to do the regex...  But this seems to work...
    $buffer = preg_replace_callback( '@\[Forclosure *=*"(.*?)" *url *=*"(.*?)" *title="(.*?)" *\]@si',
        "ForeclosureCode_replace", $buffer );
    return $buffer;
}

Comment: That sounds condescending... Answer: 0 or more of previous expression.
In my defense, I've not used RegEx very much at all..
Comment: Why the several =* then?
Comment: Because I don't really know what I'm doing with RegEx... It's still a little confusing to me.  I'm at least "TRYING" to figure it out, VS ask someone else to do all the work for me.  I could have said here's this what's the regex for this.
Answer: I'd use \s* to match indefinite amounts of whitespace; this allows you to include all forms of whitespace, not just regular spaces (and thus you can match tabs, etc).
'@\[Foreclosure\s*=\s*"(.*?)"\s*url\s*=\s*"(.*?)"\s*title="(.*?)"\s*\]@si'


How to add custom css files in a theme from drupal.org?

Question: I am using the Zen theme on my site, but would like to add custom CSS files that the theme should use. How can I achieve this?
Comment: You should create a [sub theme](http://drupal.org/node/225125) based on ZEN
Answer: While you can add your own styles to the Zen theme, it would require that you hack the theme.
What you should do instead when using Zen, is to use it as a base theme, and create what's call a subtheme. That is a theme that will use the styles, templates etc from the Zen theme, but where you can custom overrides, alterations and additions without changing Zen itself.
There is a detailed handbook page where you can read about how this is done and what to be aware of.
Within the Zen theme there is also located a start kit for your subtheme that will help you to do most of what needs to be done, and documentation on what to do in the README file in the theme.
Answer: Add the CSS styles to the theme.info file with the following line.
<code>stylesheets[all][] = css/layout.css
</code>


Finding a particular type of sequence of functions

Question: For every bounded  function $f:[a,b] \to \mathbb R$ on a closed bounded interval $[a,b]$ , which is dis-continuous at at most countably many points of its domain ; can we find a sequence of real-valued functions $\{f_n\}$ with  domain $[a,b]$ such that each $f_n$ is dis-continuous at only finitely many points of its domain and $\{f_n\}$ converges uniformly to $f$ on $[a,b]$ ? If such a sequence of functions can not be found for every $f$ , can we impose some extra condition on $f$ such that such a sequence can be found ?
( For such functions $f$ , since each $f_n$ is easily shown to be Riemann-integrable , we can conclude , due to uniform convergence , that $f$ is Riemann integrable )
Comment: If $f$ is not bounded, It is clearly impossible to find such a sequence $f_n$. First I suppose you must assume $f$ bounded.
Comment: @foo90 : Yes , I do need $f$ to be bounded
Answer: No. Put $[a,b]=[0,1]$, $A=\{0\}\cup\{1/n:n\in\Bbb N\}$, $f|A=1$ and $f|[0,1]\setminus A=0$. Then the function $f$ is discontinuous at each point of the set $A$ and is continuous at each point of the set $[0,1]\setminus A$. Moreover, if $g:[0,1]\to\Bbb R$ is a function such that $|f(x)-g(x)|<1/3$ for each $x\in [0,1]$ then the function $g$ is discontinuous at each point of the set $A$ too.
Comment: This doesn't change the validity of this counter-example, but your function $f$ is discontinuous at $0$.
Comment: @Dominik Thanks. Corrected.
Comment: Nice simple counter-example.
Answer: I think Bounded Variation (also called "rectifiable") is the condition you want on $f$.  It suffices to consider $f$ monotone and bounded, since any BV function is a difference of two monotone ones, and the set of functions approximable as required in the problem statement is closed under addition.
For $f$ monotone and bounded, the set of discontinuities is countable and sum of the jumps at discontinuities finite. If the jumps are $J_1, J_2, \dots $ then $\sum |J_i|$ is absolutely convergent. Cutting off the sum at $n$ terms with less than $\epsilon$ of jumping left in the "tail" of the series, fit a function to $f$ that equals it around the first $n$ jumps, is within $\epsilon$ everywhere, and bridges the jumps with index higher than $n$ by linear interpolation over a very short interval near the discontinuity.
The details are more complex than this because of the possibility that the set of points of discontinuity has limit points.  Nevertheless I think the complications can be overcome and the essential point is bounded variation.  If I have time I will write out a fuller argument.
Comment: Bounded variation in a subdomain containing all the points of discontinuity, or maybe even bounded total jump discontinuity, would be more precise conditions. The function can oscillate all it wants on intervals where it is continuous, and this does not impede uniform continuous approximation.


How can I display content of the same type in different ways

Question: I have some content of the same type already on the site, but there are distinctions within the content, maybe categorized with taxonomy, that sub-type the items. What is a good approach to displaying these sub-types in different ways?
Comment: Your request is vague. You are going to have to be explicit on what you mean by "different ways".
Comment: Interesting question, there would have to be some way to preprocess the taxonomy field before the page is rendered. Almost like a pre-query.
Answer: One approach would be to generate your theme's template recommendations based on the URL alias of the page you're viewing. For example consider the following example paths:
car/ferrari/red
car/ferrari/black
car/bmw/blue
car/bmw/red
The paths above are generated using the following URL path pattern:
[node:content-type]/[node:field-car-brand-category]/[node:field-car-color-category]
Now that you've defined the URL paths, you can add this PHP snippet to your template.php either in hook_preprocess_page or hook_preprocess_node, depending on the template type you'd like to add to the suggestions:
<code>function mytheme_preprocess_page(&$variables, $hook) {

    //get path alias without querying DB manually
    $alias = explode('/',drupal_get_path_alias(request_uri()));

    //add template suggestions based on path
    $path = drupal_get_path_alias($_GET['q']);

    if ($path != $_GET['q']) {
      $template_filename = 'page';

      //Break it down for each piece of the alias path
      foreach (explode('/', $path) as $path_part) {
        $template_filename = $template_filename . '__' . str_replace('-', '_', $path_part);
        $variables['theme_hook_suggestions'][] = $template_filename;
      }
    }
}
</code>
Now if you examine the var dump for $variables['theme_hook_suggestions'], you'll notice a template hierachy based on the current URL path tokens.
This might not be a fool proof way to achieve what you're after, but it is certainly works and is quick and easy.
Comment: That's a great idea, very quick and easy, like you said. Thanks!


Show that $\int_0^\infty \frac{1}{x^\alpha(1+\log^2x)^\alpha}dx$ diverges for any $\alpha>0$

Question: How can I prove that $$\int_0^\infty \frac{1}{x^\alpha(1+\log^2x)^\alpha}dx$$ diverges for any $\alpha>0$?
Comment: i would take a look at a right neigbourhood of $x=0$ and a neighbourhood of $x=\infty$
Answer: Actually the integral converges if $\alpha=1$, but only then.
To prove this, decompose the integral dyadically to see
$$\int_0^\infty \frac1{x^\alpha (1+\log^2 x)^\alpha} dx = \sum_{k\in\mathbb{Z}} \int_{2^k}^{2^{k+1}} \frac1{x^\alpha (1+\log^2 x)^\alpha} dx $$
Note that  $\int_{2^k}^{2^{k+1}} \frac1{x^\alpha (1+\log^2 x)^\alpha} dx $ is bounded from above and below (up to constants independent of $k$) by
$$\frac{2^k }{2^{k\alpha} (1+k^2)^\alpha}$$
Thus, the integral converges if and only if the sum
$$\sum_{k\in\mathbb{Z}} \frac{2^{k(1-\alpha)}}{(1+k^2)^{\alpha}}$$
converges.
Clearly, this is the case if and only if $\alpha=1$, since if $\alpha < 1$ the portion where $k$ tends to $+\infty$ diverges and if $\alpha > 1$ the portion where $k$ tends to $-\infty$ diverges.
Remark. This procedure is referred to as Cauchy condensation test.
Comment: Thanks for your answer. Could you add a precise statement of the Cauchy condensation test that you are applying and a remark on where you're applying it? Also, it is possible to prove our result using only the comparison test? If yes, how?
Comment: Please read what I wrote. I gave you a complete proof of the test I'm applying (and it uses only the comparison test). Just wanted to let you know that this is called "Cauchy condensation test".
Comment: I moved the reference to the Cauchy condensation test that confused you to the end. It is really unrelated to the logic of the argument.
Comment: Thanks, it clears that up. Could you add some details on that bound "up to a constant"?
Comment: If $2^k\le x\le 2^{k+1}$, then $c 2^{k\alpha} (1+k^2)^\alpha\le x^\alpha (1+\log^2 x)^\alpha \le C 2^{k\alpha} (1+k^2)^\alpha$, where $c,C$ are some constants (you can try to see what they are, but it's not important) not depending on $k$.
Comment: And how do you get $$\frac{2^k }{2^{k\alpha} (1+k^2)^\alpha}?$$
Comment: The denominator should be clear, it comes from estimating $x^\alpha (1+\log^2 x)^\alpha$ as in my last comment. The numerator comes from the length of the interval we are integrating over: $x\in [2^k, 2^{k+1}]$.


Is it possible to secure a VPS from its seller/provider?

Question: I have bought a VPS hosted in the USA through an Iranian company (I live there, it's quite hard to buy one directly.), and I am wondering if it is possible to secure the system against potential spying by the Iranian authorities. Partial, probabilistic solutions are also welcome.
Answer: No, physical access trumps whatever security you can apply.  I would also expect that the company In the US would comply with Iranian laws, which would most likely demand access.
Answer: Techically no, it's not possible to prevent service provider to access all data of a VPS. They have physical access to the server. Even if you encrypt all data on the drive, the service provider has access to the key while it's in the memory. You wouldn't even notice such activity as they can take s snapshot and investigate it instead of the running copy.
Legally, yes. It's probably already illegal to spy on you. But if your opponent is an intelligence agancy of a country, that doesn't weight much.
Only buy a VPS or (dedicated server) from a provider you can trust or host the server yourself.
Comment: Most of the answer like this, don't explain much how would they do that.
Comment: I am ok with that, but I'd like it if it needs some serious effort on their part. A little barrier of costs.


JOIN com duas colunas na mesma tabela

Question: Bom dia.
Como consigo fazer um JOIN, de duas coluna na mesma tabela?
Na tabela cotação, tem a coluna com o cpf_cnpj da ogirem e destino.
SELECT
    cotacao.*,
    clienteOrigem.ID_Cliente    as origemIdcliente,
    clienteOrigem.cpf_cnpj      as origemCpfcnpj,
    clienteOrigem.isento        as origemIsento,
    clienteOrigem.suframa       as origemSuframa,
    clienteOrigem.rsocial       as origemRsocial,
    clienteOrigem.nfantasia     as origemNfantasia,
    clienteOrigem.ie            as origemIe,
    clienteOrigem.im            as origemIm,
    clienteOrigem.cep           as origemCep,
    clienteOrigem.rua           as origemRua,
    clienteOrigem.num           as origemNum,
    clienteOrigem.comple        as origemComple,
    clienteOrigem.bairro        as origemBairro,
    clienteOrigem.cidade        as origemCidade,
    clienteOrigem.codMunicipio  as origemCodMunicipio,
    clienteOrigem.estado        as origemEstado,
    clienteOrigem.pais          as origemPais,
    clienteOrigem.email         as origemEmail,

    clienteDestino.ID_Cliente   as destinoIdcliente,
    clienteDestino.cpf_cnpj     as destinoCpfcnpj,
    clienteDestino.isento       as destinoIsento,
    clienteDestino.suframa      as destinoSuframa,
    clienteDestino.rsocial      as destinoRsocial,
    clienteDestino.nfantasia    as destinoNfantasia,
    clienteDestino.ie           as destinoIe,
    clienteDestino.im           as destinoIm,
    clienteDestino.cep          as destinoCep,
    clienteDestino.rua          as destinoRua,
    clienteDestino.num          as destinoNum,
    clienteDestino.comple       as destinoComple,
    clienteDestino.bairro       as destinoBairro,
    clienteDestino.cidade       as destinoCidade,
    clienteDestino.codMunicipio as destinoCodMunicipio,
    clienteDestino.estado       as destinoEstado,
    clienteDestino.pais         as destinoPais,
    clienteDestino.email        as destinoEmail

FROM cotacao
    LEFT JOIN clientes clienteOrigem on clienteOrigem.cpf_cnpj = cotacao.origem
    LEFT JOIN clientes clienteDdestino on clienteDdestino.cpf_cnpj = cotacao.destinatario

WHERE
    ID_Cotacao = '3'

Alem dos dados da tabela cotação, preciso pegar os dados da origem e do destino.
Isso é possível?
Comment: Podes colocar uma amostra do conteudo das tabelas?
Answer: Você chegou bem perto, acredito que seu erro está na falta de um alias
SELECT * from cotacao
LEFT JOIN clientes cliente_origem on cliente_origem.cpf_cnpj = cotacao.origem
LEFT JOIN clientes cliente_destino on cliente_destino.cpf_cnpj = cotacao.destinatario
WHERE ID_Cotacao = '3'

Se você quiser pegar só as  razões sociais de cada cliente seria assim:
SELECT cliente_origem.rsocial as rsocial_origem,
       cliente_destino.rsocial as rsocial_destino,
from cotacao
LEFT JOIN clientes cliente_origem on cliente_origem.cpf_cnpj = cotacao.origem
LEFT JOIN clientes cliente_destino on cliente_destino.cpf_cnpj = cotacao.destinatario
WHERE ID_Cotacao = '3'

Preste atenção na diferença entre cliente_origem e cliente_destino, também usei um alias nas colunas ficando rsocial_origem e rsocial_destino. Então no seu PHP você pega dessa forma:
echo $row['rsocial_origem']; /* razão do cliente de origem */
echo $row['rsocial_destino']; /* razão do cliente de destino */

Se quiser pegar só os dados do cliente origem é só usar cliente_origem.*
Comment: Ele mostra todos os dados da tabela `cotacao`, `clienteOrigem `, mas não mostra nenhum valor da tabela `clienteDestino`.
Comment: @Tiago Você verificou a integridade dos seus dados? Realmtente o valor do `cotacao.destino` existe na tabela clientes?
Comment: Sim, existem http://i.imgur.com/IcoZVqd.png
Comment: @Tiago Como está salvo na coluna destino da tabela cotação? Está sem pontuação?
Comment: Falha minha...rsrs, o campo é `destinatario` e não destino. (http://i.imgur.com/j2VDCSd.png). Agora esta mostrando os valores, mas tenho uma dúvida... Como distinguir o valor de origem e destinatario, sendo que os campos são os mesmos?
Comment: Não sao os mesmos, como o @ctgPi explicou, quando tu usa o `alias` você  cria uma "nova tabela". Se você utilizar `cliente_destino` ele só vai retornar dados do seu relacionamento `cliente_destino.cpf_cnpj = cotacao.destinatario`
Comment: Bacana! Como faria para mostrar no PHP o echo do `clienteOrigem.rsocial` e `clienteDestino.rsocial`?
Comment: @Tiago Atualizei minha resposta com um exemplo
Comment: Você esta colocando 2 selects?
Comment: O `primeiro` select da minha resposta é um exemplo, o `segundo` é mostrando como você faria pra pegar as razões sociais ambos feitos com 2 `LEFT JOIN`
Comment: Editei meu codigo inicial.
Comment: Eu teria que fazer `alias` para todos os campos?
Comment: @Tiago Exatamente
Comment: Atualizei meu post. Esta dando um erro, `Unknown column 'clienteDestino.ID_Cliente' in 'field list'`
Comment: @Tiago Você escreveu errado no `LEFT JOIN clientes clienteDdestino` está com dois D, o certo é `LEFT JOIN clientes clienteDestino`
Comment: Como eu faço para incluir um outra tabela `config`?
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/24888/discussion-between-maicon-carraro-and-tiago).
Comment: Descobrir :), Obrigado.
Answer: SELECT * from cotacao
LEFT JOIN clientes AS cliente_origem ON cliente_origem.cpf_cnpj = cotacao.origem
LEFT JOIN clientes AS cliente_destino ON cliente_destino.cpf_cnpj = cotacao.destino
WHERE ID_Cotacao = '3'

O <tabela> AS <novo_nome> renomeia as tabelas, e cria uma nova tabela virtual, permitindo que você faça vários JOINs (inclusive INNER JOINs, se for o caso) com a mesma tabela, mas em contextos diferentes.
A pegadinha é que renomear a tabela não renomeia as colunas da tabela; se você está puxando o resultado como um array associativo, você pode encontrar algum erro ou sentir a falta de algumas colunas. Você conserta isso fazendo
SELECT
    cliente_origem.nome AS cliente_origem_nome,
    cliente_origem.endereco AS cliente_origem_endereco,
    -- outras colunas de cliente_origem…
    cliente_destino.nome AS cliente_destino_nome,
    cliente_destino.endereco AS cliente_destino_endereco,
    -- outras colunas de cliente_destino…
    -- outras colunas de outras tabelas…
FROM …

Comment: @Tiago, só complementando você também pode buscar todos os campos de uma tabela `cliente_origem.*` e depois renomear apenas os campos da segunda tabela `cliente_destino.nome AS cliente_destino_nome`. Então o campo `$row['nome']` no seu _array_ será referente a tabela "origem" e os referente a destino estarão renomeadas `$row['cliente_destino_nome']`.
Comment: Explicou bem melhor que eu :)
Comment: Ele mostra todos os dados da tabela `cotacao`, `clienteOrigem `, mas não mostra nenhum valor da tabela `clienteDestino`.
Comment: Sim, e eu, pessoalmente, sou partidário de `cliente_origem.nome AS \`cliente_origem.nome\``, etc. mas eu entendo que a maioria das pessoas não gostam muito de ficar escapando os _identifiers_ na consulta em si.

JOIN com duas colunas na mesma tabela


How to make numbers grow and decrease in a smarter way?

Question: I created a function with JavaScript, which is a countdown of the numbers on the screen that increases and decreases its size, however, the code is too large and I want to know how to do it in a more intelligent way without using many lines. Thank you
My code can be found here

var mudar5 = document.getElementById("cinco");
var mudar4 = document.getElementById("quatro");
var mudar3 = document.getElementById("tres");
var mudar2 = document.getElementById("dois");
var mudar1 = document.getElementById("um");
var mudarGo = document.getElementById("go");
mudar3.style.fontSize = "20px";

var fonteAtual = 1;
var minSize = 1;
var maxSize = 80;
var intervalTime = 10;
var intervalTimeDecrease = 2;

increaseSize();

//liga o cinco
function increaseSize() {

  var interval = setInterval(function() {
    fonteAtual++;

    mudar3.style.fontSize = fonteAtual + "px";

    if (fonteAtual === maxSize) {
      clearInterval(interval);
      decreaseSize();
    }

  }, intervalTime);

}

function decreaseSize() {

  var interval = setInterval(function() {
    fonteAtual--;
    mudar3.style.fontSize = fonteAtual + "px";

    if (fonteAtual === minSize) {
      clearInterval(interval);
      liga2();
    }

  }, intervalTimeDecrease);

}
//liga o quatro
function liga2() {
  document.querySelector("#tres").style.display = "none";
  document.querySelector("#dois").style.display = "block";
  increasetwo();
}

function increasetwo() {

  var interval = setInterval(function() {
    fonteAtual++;

    mudar2.style.fontSize = fonteAtual + "px";

    if (fonteAtual === maxSize) {
      clearInterval(interval);
      decreasetwo();
    }

  }, intervalTime);

}

function decreasetwo() {

  var interval = setInterval(function() {
    fonteAtual--;
    mudar2.style.fontSize = fonteAtual + "px";

    if (fonteAtual === minSize) {
      clearInterval(interval);
      liga1();
    }

  }, intervalTimeDecrease);

}

//liga o 3
function liga1() {
  document.querySelector("#dois").style.display = "none";
  document.querySelector("#um").style.display = "block";
  increaseone();
}

function increaseone() {

  var interval = setInterval(function() {
    fonteAtual++;

    mudar1.style.fontSize = fonteAtual + "px";

    if (fonteAtual === maxSize) {
      clearInterval(interval);
      decreaseone();
    }

  }, intervalTime);
}

function decreaseone() {
  var interval = setInterval(function() {
    fonteAtual--;
    mudar1.style.fontSize = fonteAtual + "px";

    if (fonteAtual === minSize) {
      clearInterval(interval);
      ligaGo();
    }

  }, intervalTimeDecrease);
}

//Liga o Go
function ligaGo() {
  document.querySelector("#um").style.display = "none";
  document.querySelector("#go").style.display = "block";
  increaseGo();
}

function increaseGo() {

  var interval = setInterval(function() {
    fonteAtual++;

    mudarGo.style.fontSize = fonteAtual + "px";

    if (fonteAtual === maxSize) {
      clearInterval(interval);
      mudarGo.style.fontSize = 80 + "px";
    }

  }, intervalTime);
}

//liga o Um
function liga1() {
  document.querySelector("#dois").style.display = "none";
  document.querySelector("#um").style.display = "block";
  increaseone();
}

function increaseone() {

  var interval = setInterval(function() {
    fonteAtual++;

    mudar1.style.fontSize = fonteAtual + "px";

    if (fonteAtual === maxSize) {
      clearInterval(interval);
      decreaseone();
    }

  }, intervalTime);
}

function decreaseone() {
  var interval = setInterval(function() {
    fonteAtual--;
    mudar1.style.fontSize = fonteAtual + "px";

    if (fonteAtual === minSize) {
      clearInterval(interval);
      ligaGo();
    }

  }, intervalTimeDecrease);
}

//Liga o Go
function ligaGo() {
  document.querySelector("#um").style.display = "none";
  document.querySelector("#go").style.display = "block";
  increaseGo();
}

function increaseGo() {

  var interval = setInterval(function() {
    fonteAtual++;

    mudarGo.style.fontSize = fonteAtual + "px";

    if (fonteAtual === maxSize) {
      clearInterval(interval);
      mudarGo.style.fontSize = 80 + "px";
    }

  }, intervalTime);
}
#dois,
#um,
#go {
  display: none;
  font-size: 0px;
}

3

2

1

GO!

Comment: I think it's possible to make the animation using CSS 3 and without JavaScript.
Comment: [Everything you wanted to know about CSS animations but were too afraid to search for](https://developer.mozilla.org/en-US/docs/Web/CSS/animation)
Comment: Your link is broken
Comment: Could you give me a demonstration of this? @Alexander
Comment: lol Jaromanda, your link caption made me laugh
Answer: I think you can decrease the code by factoring your code because as far as i can see most of it does the same thing.
your code can be something like this which will more or less do the same things:

var counter = 3;
var fonteAtual = 1;
var minSize = 1;
var maxSize = 80;
var intervalTime = 10;
var intervalTimeDecrease = 2;

var mudar = document.getElementById("number");
mudar.innerHTML = counter;

increaseSize();

function increaseSize() {

  mudar.innerHTML = counter==0?'GO!':counter;

  var interval = setInterval(function() {
    fonteAtual++;

    mudar.style.fontSize = fonteAtual + "px";

    if (fonteAtual === maxSize) {
      clearInterval(interval);
      if(counter === 0){
        return;
      }
      decreaseSize();
    }

  }, intervalTime);

}

function decreaseSize() {

  mudar.innerHTML = counter==0?'GO!':counter;

  var interval = setInterval(function() {
    fonteAtual--;
    mudar.style.fontSize = fonteAtual + "px";

    if (fonteAtual === minSize) {
      clearInterval(interval);
      counter--;
      increaseSize()
    }

  }, intervalTimeDecrease);

}

no need for any CSS to do the same thing
and if you want it to be only one function:

var counter = 3;
var fonteAtual = 1;
var minSize = 1;
var maxSize = 80;
var intervalTime = 10;
var intervalTimeDecrease = 2;

var mudar = document.getElementById("number");

ChangeSize(true);

//-----------------------------------

function ChangeSize(sign){

  mudar.innerHTML = counter==0?'GO!':counter;

  var interval = setInterval(function() {
    fonteAtual = sign ? (fonteAtual + 1) : (fonteAtual - 1)

    mudar.style.fontSize = fonteAtual + "px";

    if (fonteAtual === maxSize) {
      clearInterval(interval);
      if(counter === 0){
        return;
      }
      ChangeSize(false)
    }

    if (fonteAtual === minSize) {
      clearInterval(interval);
      counter--;
      ChangeSize(true)
    }

  }, sign ? intervalTime : intervalTimeDecrease);

}

Answer: You could implement the animation using CSS Animations instead of JavaScript. I provde an example below to help you get started. Just change the animation properties to get expected effect.

.container {
  text-align: center;
  margin: 0 auto;
}

#tres, #dois, #um, #go {
  font-size: 0;
  animation: .5s ease-in-out 2 forwards alternate zoom;
}
#dois {
  animation-delay: 1s;
}
#um {
  animation-delay: 2s;
}
#go {
  animation-delay: 3s;
  animation-iteration-count: 1;
}

@keyframes zoom {
    0% { font-size: 0; }
    100% { font-size: 80px; }
 }

3

2

1

GO!

The ease-in-out is used for animation-timing-function property in the example. But if you need to speed function will be same as in your post, then use another predefined speed curve or define your own speed curve using cubic-bezier() function.
Answer: mixing CSS with a bit of JS to give flexibility:

var states = [3, 2, 1, "GO!"];
var countdownElement = document.getElementById('countdown');

states.forEach(function(state, index){
  countdown.style.animationIterationCount = states.length * 2 - 1;

  setTimeout(function(){
    countdownElement.innerHTML = state;
  }, index * 1000);
});
.countdown-out, .countdown-in {
  animation: .5s linear forwards alternate zoom;
}

@keyframes zoom {
  0% { font-size: 0; }
  100% { font-size: 64px; }
}

3


How do detect change in network type use in Phonegap / Cordova

Question: In Phonegap / Cordova 3.0, How do I detect a change in a network from 3G to Wi-Fi or vice versa. When changing, the offline event is not called because it quickly switches between the two.
Answer: I've created a Gist showing how to check the connection every x seconds from javascript. I don't know if it's the right approach for your usecase, but I needed this for an app recently: https://gist.github.com/EddyVerbruggen/10499328#file-connectionchecker-js


question related to divisibility

Question: how to prove the following:
if $a$ and $b$ are both odd integers, prove:
$$a^4 +b^4 \equiv 2 \pmod{16}$$
If anybody know any other method or solution other than putting  $a$ or $b = 2k+1$ or using the fact that square of an odd integer is of the form $8k+1$ then share that solution here.
Comment: One immediate reduction would seem that your statement is equivalent to $a^4\equiv1\pmod{16}$ for all odd $a$. Why did you add $b$?
Answer: If $c$ is odd=$2k+1$(say),
(i)$c^2=(2k+1)^2=8\frac{k(k+1)}{2}+1=8y+1$ for some integer $y$.
$c^4=(c^2)^2=(8y+1)^2=64y^2+16y+1=1+16(y+4y^2)=1+16z$ for some integer $z$.
(ii) $c^4=(2k+1)^4=(2k)^4+ ^4C_1(2k)^3+ ^4C_2(2k)^2+ ^4C_3(2k)+ 1$
$=16k^4+32k^3+24k^2+8k+1≡8k^2+8k+1\pmod {16}=16\frac{k(k+1)}{2}+1≡1\pmod {16}$
(iii)we have already found $8\mid(c^2-1)$
Now $2\mid(c^2+1)$ as $c$ is odd, so, $8\cdot 2\mid(c^2-1)(c^2+1)=>16\mid(c^4-1)$
(iv) Using this, $\lambda(16)=\frac{\phi(16)}{2}$ as $16$ is a power$(≥3)$ of $2$, so $\lambda(16)=4=>c^4≡ 1\pmod {16}$ if $(c,16)=1$  i.e., if  $c$ is odd.
So, in all the 4 ways we have proved, $c^4$ leaves remainder $1$ when divided by $16$ if $c$ is odd.
So, $a^4$, $b^4$ each will leave $1$ as remainder when divided by $16$
Comment: Minor TeX tip: Use `\mid` to get a vertical bar acting as a relation (more space around the bar). You get $8\mid(c^2-1)$ instead of $8|(c^2-1)$.
Comment: Thanks @HaraldHanche-Olsen, I've rectified & I'll use this in future.
Answer: We use induction. Since taking fourth powers does not depend on the sign, assume $a,b$ are non-negative. The statement is obviously true for $a=b=1$. Now, if it is true for $(a,b)$ then we want to show that it is true for $(a+2,b)$.
$$(a+2)^4 + b^4 - 2 = (a^4+b^4-2)+ 8a^3+24a^2+32a+16\\
= (a^4+b^4-2) + 16(2a+1) + 8a^2(a+3)$$
which is divisible by 16 since $a+3$ is even. Similarly if the statement is true for $(a,b)$, it is true for $(a,b+2)$. Hence it is true for all pair of odd integers.
Answer: One has $a^4-b^4=(a-b)(a+b)(a^2+b^2)$. If $a,b$ are odd, all factors in this product are even, and one of the the first two factors is even divisible by $4$. This shows that in this case $a^4\cong b^4\pmod{16}$, so all odd fourth powers are in the same congruence class modulo $16$, and it doesn't take long to figure out which class that is. In any case twice that class is the class of $2$.

question related to divisibility


Create Data Binding not showing updated field from AppResources

Question: I have two resx
AppResources.resx
AppResources.zh-Hant.resx

It just happened. I can not access strings I updated using the Search Properties panel.
Text="{Binding LocalizedResources.introText, Mode=OneWay, Source={StaticResource LocalizedStrings}}"

But I can access it though the code.
AppResources.introText;

What I suspect is I have decided to migrate AppResources.resx with AppResources.zh-Hans.resx
Then I proceed to delete this file
-AppResources.zh-Hans.resx

Then I goto the Project Properties and disable the English support.
But I found that it keeps coming back as default(which is annoying).
After a while, I discovered I can access newly added string through the xaml way.
What do I do?
Answer: Problem solved.
I need to build the project...
I am silly.


Getting the usual definition of product topology from an alternative one

Question: I'm studying the topological product using Schubert's book.
He starts by defining the product topology as follows:

DEFINITION. Let $\{X_{\lambda}\}_{\lambda\in\Lambda}$
    be a (non-empty) family of topological spaces. The coarsest topology on the set $X=\underset{\lambda\in\Lambda}{\prod}X_{\lambda}$
   , for which all projections $p_{\lambda}:X\rightarrow X_{\lambda}$
    are continuous, is called the product topology on X. If $X$ is considered as having this topology, then $X$ is called the topological product of the spaces $X_\lambda$.

He then states the following theorem:

THEOREM: Sets of the form $\prod Q_{\lambda}$, where $Q_{\lambda}$  is open in $X_{\lambda}$ and $Q_{\lambda}=X_{\lambda}$  with a finite number of exceptions, form a basis for the product topology.

Which the usual definition of the product topology.
I tried to prove this theorem from the given definition. I'm still very shaky in this topic (topology), and I found this proof particularly tricky, so I would like you to check it.
My attempt: I know that the coarsest topology on $X$ containing all the sets of a certain family $A$ of subsets of $X$ is the topology generated by $A$ ($A$ thus being a subbasis for this topology).
Hence, if we let $A$ be the set of all subsets of $X$ containing all the sets of the form $p_{\lambda}^{-1}(Q_{\lambda})$ (with $Q_\lambda$ an open set of $X_\lambda$), $A$ is a subbasis of the product topology (because all projections $p_{\lambda}:X\rightarrow X_{\lambda}$ are continuous precisely when the sets of the form $p_{\lambda}^{-1}(Q_{\lambda})$ (with $Q_\lambda$ an open set of $X_\lambda$) are open in $X$).
I also know that, if $Q_{\mu}$
  is a set of $X=\underset{\lambda\in\Lambda}\prod X_{\lambda}$, then $p_{\mu}^{-1}(Q_{\mu})=X_{1}\times X_{2}\times...\times Q_{\mu}\times...$
Now, the set of all finite intersections of the elements of $A$ is a basis of $X$. The finite intersections of the $p_{\mu}^{-1}(Q_{\mu})=X_{1}\times X_{2}\times...\times Q_{\mu}\times...$ are precisely of the form described in the theorem.
Comment: Yes this looks exactly right to me. By the way I really like the question. Also you might find this interesting: https://en.wikipedia.org/wiki/Product_topology#Properties If you ever learn category theory, the reason to use the product topology (instead of the seemingly more straightforward box topology) is that it is a categorical product which is equivalent to the universal property definition Schubert gives above (to check that a function _into_ a product is continuous, we just verify that each coordinate function is continuous).
Comment: Yep, that's how it's done imho.
Answer: What your attempt shows is that  A is a sub-base for a topology  $T$ on $X$ that's a subset of the product topology given by the "DEFINITION". What is missing is the converse.  Your 2nd-last sentence needs to proven. That is, show that every $p_{\lambda}$ is continuous with the topology $T$ on $X.$ To show this, let $S$ an be open  subset of $X_{\lambda}.$ Then $p_{\lambda}^{-1}S\in A\in T,$ so $p_{\lambda}^{-1}$ is $T$-continuous. So by the DEFINITION, $\;T$ must have the product topology as a subset.
This is often called the Tychonoff product topology,or the topology of point-wise convergence, to distinguish it from the box product topology, which is stronger, and, for some types of $X_{\lambda},$ there is also the uniform product  topology (also called the topology of uniform convergence.) The Tychonoff product has been found to be an extremely useful tool.


How to simplify this series?

Question: I have the series
$$
P_i = 1 = \bigg[1 + \frac{q}{p} + \bigg(\frac{q}{p}\bigg)^2 + \bigg(\frac{q}{p}\bigg)^3 + \cdots + \bigg(\frac{q}{p}\bigg)^{i-1}  \bigg]P_1
$$
We have the boundary condition
$$
P_N=1
$$
Apparently, if we assume $p\neq q$, we obtain
$$
P_N = \frac{1-\bigg(\frac{q}{p}\bigg)^N}{1-\bigg(\frac{q}{p}\bigg)}P_1
$$
Could someone explain how the power series was simplified to this?
Comment: Are you familiar with geometric progressions?
Comment: @Gary, somewhat, although I've really only dealt with simplifying basic stuff like $\sum_{i=1}^N (\frac{1}{2})^i$.
Comment: Having $q/p$ in place of $1/2$ does not change much. Consider https://en.wikipedia.org/wiki/Geometric_progression#Derivation
Comment: @Gary. Thanks I'll look at the resource.
Answer: A geometric sum. It is easy to prove (e.g. by induction) that if $a\ne 1$:
$\begin{align*}
  \sum_{0 \le k \le n} a^k
     &= \frac{a^{n + 1} - 1}{a - 1}
\end{align*}$
If $a = 1$, obviously:
$\begin{align*}
  \sum_{0 \le k \le n} a^k
     &= n + 1
\end{align*}$

How to simplify this series?


In NHL, can an attacking player possess the puck without touching it during delayed offside?

Question: Consider the segment from 1:22 to 1:28 of the video at https://twitter.com/sportsnet/status/1469495840079327233
These events occurred in this order:

An attacking player A0 is in the attacking zone.
An attacking player A1 possesses the puck in the neutral zone.
A1 causes the puck to completely cross the blue line into the attacking zone, without touching it after it has crossed the blue line.
A0 leaves the attacking zone, causing the attacking team to "tag up" and become onside.
A1 touches the puck.

If A1 had touched the puck before A0 left the attacking zone, it is clearly offside.
Which of the following rulings is correct?

There is a delayed offside because A1 did not touch the puck in the attacking zone, but the delayed offside is nullified after the team tags up.
There is an offside immediately when A1 caused the puck to cross the blue line while his team is offside, just because A1 possessed the puck.

The linesman ruled the first one. The referees ruled the second. The NHL Senior Executive Vice President Colin Campbell later said the first ruling is correct. Who is right?
Also, how is "possession and control" defined? Is simply being the last player to touch the puck enough to be in possession of it? But this would be inconsistent with the fact that shooting the puck across the blue line such that it is far away from the player would create a delayed offside.
Answer: Unsurprisingly, Colin Campbell is right, as you'd expect.
From the 2022 NHL Rulebook, rule 83 (Off-sides), delayed off-sides:

83.3 Delayed Off-side – A situation where an attacking player (or players) has preceded the puck across the attacking blue line, but the defending team is in a position to bring the puck back out of its defending zone without any delay or contact with an attacking player, or, the attacking players are in the process of clearing the attacking zone.
If an off-side call is delayed, the Linesman shall drop his arm to nullify the off-side violation and allow play to continue if:

(i) All players of the offending team clear the zone at the same instant (skate contact with the blue line) permitting the attacking players to re-enter the attacking zone, or
(ii) The defending team passes or carries the puck into the neutral zone.

If, during the course of the delayed off-side, any member of the attacking team touches the puck, attempts to gain possession of a loose puck, forces the defending puck carrier further back into his own zone, or who is about to make physical contact with the defending puck carrier, the Linesman shall stop play for the off-side violation.

The specific action the player would take that would cause the off-sides whistle to be correct is to touch the puck.
At 1:25, you can see the player at the top of the screen last touches the puck on the blue line (so, not yet off-sides).  At 1:26, you can see for a brief moment all three attacking players are on-side (their skates are at least touching or over the blue line's leading edge, or the edge closest to the goal).  It's very brief - less than half of a second, and by centimeters - and I could see another person seeing this differently - but that's why Campbell uses the words "could not definitively determine".  In my eyes they're on-side, and at minimum clearly not definitively off-sides (which would be required for overturning the goal).
Note that your distinction is not quite right.  The delayed off-sides doesn't only happen when the attacking player is not possessing the puck.  It can also happen when the attacking players do possess the puck, but are clearing the zone, and don't actually touch the puck - even if it's under their control (just as long as they don't touch it, which is of course challenging).


Numbers, letters and words on top of guitar music score notes

Question: I'm trying to play 'Gran Vals' by Tarrega, and the music score has several letters accompanied by a number on top of the notes, for example:
C.2a_ _ _ _ _ _ _ _ _ __ _
In some cases there are words like
ten:
Here is the score:

What does this mean?
Can any one provide a link where I can review this type of notation?
Answer: These expressions are common in classical guitar music.
ten: means tenuto, which is a playing style used for effect. Each note should be held for its full length. Do not confuse this with legato, tenuto is holding notes for their full length but not necessarily playing them smoothly or softly.
The C.2a Is a barre. This is unique to stringed instruments and it is when you lay one finger (usually the first finger) across all or some of the strings on one fret. A full barre is across all six strings, while a half barre is across the top three or so strings (sometimes four). The number shows you which fret this is done on. the ------¬ written after this shows you how long to hold the barre for in the music, and you should lift your finger at the end of the line.
I have not seen a barre written in this form before, usually it is written as a capital 'C' followed by roman numerals for the fret and the same line indication. A half fraction before the 'C' (or a dash vertically through it) indicates a half barre:
Comment: Thank you!
It makes it easier to understand how to play this piece.
Is there a link you recommend where all of this notation is explained? The results that came up after I googled were somewhat confusing.
Thanks again!
Comment: this was from my own knowledge with reassurance from google, but i'll look for a site for you.
Comment: Try [this](https://en.wikipedia.org/wiki/List_of_musical_symbols) page for notation, and [this](https://en.wikipedia.org/wiki/Glossary_of_musical_terminology) page for expressions (use CTRL + F to search for the right term)
Comment: "A half fraction before the 'C' indicates a half barre" An alternative notation is a dashed C , eg https://musescore.org/sites/musescore.org/files/Example_3.jpg


Let $G$ be a finite group and let $p$ a prime number that divides $|G|$. Let $h$ denote the number of subgroups of $G$ of order $p$.

Question: Let $G$ be a finite group and let $p$ a prime number that divides $|G|$. Let $h$ denote the number of subgroups of $G$ of order $p$.
Prove that:
i)  There are $h(p-1)$ elements of order $p$ in $G$
ii) $h\equiv 1 \pmod p$

I'm not yet introduced to normal subgroups. This is an exercise from the chapter of group actions. But I don't see how I can use my knowlegde about group actions to solve this exercise.
Answer: The first part is straightforward. An element $a$ of order $p$ generates a subgroups $\langle a \rangle$ of order $p$, which consists of the identity $e$, and of $p-1$ elements of order $p$. Two (distinct) such subgroups $A$ intersect in the identity. Therefore the set of elements of order $p$ is the disjoint union of all these $A \setminus \{ e \}$.
For the second part, let $A$ be one the subgroups of order $p$, and consider the action of $A$ by conjugacy on the set $\mathcal{S}$ of subgroups of order $p$.
The orbits of the action have length $1$ or $p$. Clearly the orbit of $A$ has length $1$. If the orbit of $B \ne A$ has length $1$ (that is, $B$ is fixed by $A$ in this action), then $\langle A, B \rangle$ is an elementary abelian group of order $p^2$ which has $p+1$ subgroups of order $p$, one of which is $A$, so this yields $p$ subgroups of order $p$ (all fixed by $A$ in this action) other than $A$.
Then there are the orbits of length $p$. Summing all up, we see that the number $h$ of subgroups in $\mathcal{S}$ is congruent to $1$ modulo $p$.
Comment: Very intuitive compared to what I would have done.
Comment: Why do two subgroups of order $p$ intersect only the identity ?
Comment: By http://en.wikipedia.org/wiki/Lagrange's_theorem_(group_theory) (I have added *distinct* in the text, just in case.)


Programmatically showing a View from an Eclipse Plug-in

Question: I have a plug-in to an Eclipse RCP application that has a view.  After an event occurs in the RCP application, the plug-in is instantiated, its methods are called to populate the plug-in's model, but I cannot find how to make the view appear without going to the "Show View..." menu.
I would think that there would be something in the workbench singleton that could handle this, but I have not found out how anywhere.
Answer: You are probably looking for this:
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView("viewId");

Comment: It is important to note that the arg0 can be a view part's VIEW_ID field.
Comment: Where do I put that? I put it in all my classes, but still doesn't work. (I accidentally closed the view within the RCP application)
Answer: If called from handler of a command
HandlerUtil.getActiveWorkbenchWindow(event).getActivePage().showView(viewId);

would be better, as I know.
Answer: I found the need to bring the view to the front after it had been opened and pushed to the background.  The activate method does the trick.
PlatformUI.getWorkbench()
    .getActiveWorkbenchWindow()
    .getActivePage()
    .activate(workbenchPartToActivate);

NOTE: The workbenchPartToActivate is an instance of IWorkbenchPart.
Answer: In e4, the EPartService is responsible for opening Parts. This can also be used to open e3 ViewParts. Instantiate the following class through your IEclipseContext, call the openPart-Method, and you should see the Eclipse internal browser view.
public class Opener {
    @Inject
    EPartService partService;

    public void openPart() {
        MPart part = partService.createPart("org.eclipse.ui.browser.view");
        part.setLabel("Browser");

        partService.showPart(part, PartState.ACTIVATE);
    }
}

Here you can find an example of how this works together with your Application.e4xmi.


Infinitely many primes derived from coprimality of Fermat numbers.

Question: Everyone knows that there is an infinitude of primes. I know the Euclide, the Euler and the Erdos proofs. But are they the only known proofs ?
I will try, here, to present a fourth one :
Let the Fermat numbers $F_n=2^{2^n}+1$. They are not all primes, $F_5$ for example is not, Euler has proved it ! There are two possibilities, of course : if there is an infinitude of prime Fermat numbers, the primes are infinite. If there is an infinitude of compound Fermat numbers, the Goldbach theorem states that $\gcd(F_n,F_m)=1$ if $n\neq m$. So $F_n=p_1^{n_1}\cdots p_i^{n_i}$ and $F_m=q_1^{m_1}\cdots q_j^{m_j}$ and $p_k\neq{q_j},\forall{j,k}$. Thus $p_1=F_n^{1/n_1}p_2^{-n_2/n_1}\cdots p_i^{-n_i/n_1}$ are infinite and there is always an infinitude of primes! Do you know another proof mentioned in the literature, please? Thank you.
Comment: @Hurkyl Googling "an infinity of" I found lots of usesof this construction.  Then, restricting the search by adding "math", I still found lots of uses and, on the few Google pages that I actually looked into, no claims that it's a *misuse* except for your comment here.
Comment: @Hurkyl The first dictionary I checked gives, as one meaning of "infinity", "an infinite or very great number or amount". So I think "an infinity of primes" is quite correct.
Comment: My hunch is that any rigorous book about prime numbers probably has at least one other proof besides the classic one. Somewhere I read a proof that I thought was inelegant because it requires proving the fundamental theorem of arithmetic first, and I don't know, the infiniteness of primes seems to me like a more elementary thing than unique factorization.
Comment: We don't need to break into cases. For each Fermat number $F_m$, let $p_m$ be its smallest prime factor. The $p_m$ are all distinct.
Comment: I've always liked this one: http://www.cut-the-knot.org/proofs/InjectivePrimes.shtml
Comment: There are hundreds of proofs of the infinitude of primes. I'm certain someone has compiled a large list somewhere. [Here](http://math.gcsu.edu/~ryan/13capstone/papers/harrison.pdf) is a smaller list that I found on the first page of a google search.
Comment: "Infinitely many" or "an infinite set of", not "an infinity of".
Comment: You can simplify your proof a bit: since all $F_n$ are coprime and every number has a unique prime decomposition, there are necessarily an infinity of primes, whether or not the $F_n$ are themselves primes (just pick one prime factor of $F_n$, for each $n$).
Comment: @Andreas: I don't doubt that that *misuse* is sufficiently common to make it into a dictionary -- but it is still a *misuse* that is one source of confusion people have about the topic, and worth correcting. (in particular, no mathematical usage of 'infinity' shares this meaning)
Comment: Related https://math.stackexchange.com/questions/50006/different-ways-to-prove-there-are-infinitely-many-primes
Answer: This page at MIT purports to be an attempt to collect as many proofs as possible.  But I suspect it has been left unfinished because it's not very long and there are lots of proofs of this theorem.
This page presents several proofs and could probably be expanded.
Answer: The key idea of Euclid's classical proof is that we can construct an infinite sequence of primes from any infinite sequence of coprimes, e.g. give an increasing sequence of naturals $\,f_n > 1\,$ that are pair-coprime, i.e. $\,(f_i,f_j) = 1\,$ for $\,i\ne j,\,$ then choosing $\,p_i\,$ to be a  prime factor of $\,f_i\,$ yields an infinite sequence of primes, since the $\,p_i\,$ are distinct: $\,p_i\ne p_j,\,$ being factors of coprimes $\,f_i,\, f_j\,$.
Thus, since the Fermat numbers enjoy such coprimality, they yield an infinite sequence of primes. Ribenboim says the proof using the sequence of Fermat numbers is due to Goldbach (1730), and the idea of using coprimes was used in an exercise by Hurwitz (1891).
You can find these references, and many other proofs that there are infinitely many primes in the first chapter of Ribenboim's The new Book of Prime Number Records.
Answer: There are six nice proofs presented in the first chapter of Proofs from THE BOOK, including one similar to yours using Fermat numbers.


I can't send string with messaging center in xamarin forms

Question: I can send object when I use a class like this.
MessagingCenter.Send<CariRoot>(selectedCari, "mselectedCari");
MessagingCenter.Subscribe<CariRoot>(this, "mselectedCari" ,async (sender) =>
{
    SearchCari = $"{sender.CARIUNVAN}";
    _SelectedCariRoot = sender;

    Console.WriteLine(SearchCari);
});

But when I want to send a string not an object I use MessagingCenter like this and this code doesn't work. I can't figure how to send a string.
MessagingCenter.Send<string>(searchText, "searchText");
MessagingCenter.Subscribe<string>(this, "searchText", async (sender) =>
{
    SearchStateText = $"{sender}";
});

Do you have any solution ?
Comment: Make sure to follow the [documentation](https://learn.microsoft.com/xamarin/xamarin-forms/app-fundamentals/messaging-center). AFAIK, `string` cannot be the `TSender` type. It should be one of your classes/pages.
Comment: As @julian says, read the docs.  `Send` where `T1` is the type of the **sender**, and `T2` is the type of the **payload**
Answer: The Send method specifies two generic arguments. The first is the type that's sending the message, and the second is the type of the payload data being sent. To receive the message, a subscriber must also specify the same generic arguments. This enables multiple messages that share a message identity but send different payload data types to be received by different subscribers.
In addition, this example specifies a third method argument that represents the payload data to be sent to the subscriber. In this case the payload data is a string.
You can refer to the sample code below:
MessagingCenter.Send<Page, string>(this, "searchText", "John");

MessagingCenter.Subscribe<Page, string>(this, "searchText", async (sender, arg) =>
{
    await DisplayAlert("Message received", "arg=" + arg, "OK");
});


Linear Regression Prediction Interval for precise y values

Question: When calculating the prediction intervals for a regression function, can the y values be precise values "without errors"?
As far as I know, in regression function calculation only the x values are assumed to have no error and not the y values (see requirements below). But in computational chemistry the calculated values are precise per definition, as same input gives same output, so they don't have standard deviation or sth like that.
The mathematical requirements are, according to my literature (german DIN):

independent and normally distributed values
homogeneity between lowest and highest value's variance
a linear functional relationship where the x values count as errorless and the y values are assumed to have errors

They state: If those requirements are not satisfied, then the calculation scheme cannot be used and another scheme has to be chosen. And that last requirement is, what the question is about: What if both, x and y values, have "no error" ... is the system still usable or do I need something more appropriate?
For clarification, this is the system that should be treated:
$\hskip3.5cm$
Comment: If the relationship between $x$ and $y$ is linear, i.e. $y=\alpha x + \beta$, and there are 'no errors' then you just have to take out two different points $(x_1, y_1)$ and $(x_2, y_2)$ and solve the system of equations $y_1=\alpha x_1 + \beta$ and $y_2=\alpha x_2 + \beta$ for $\alpha$ and $\beta$.
Comment: If there's no error, then why would you need regression at all? You can simply compute E(Y|x) by observing a single Y for any x you want. (Even better, if the model is correct, you only need to observe as many Y-values as you have unspecified parameters in the model to compute the population values exactly.)
Comment: A toy example & a clear statement of your goals might help to clarify what you're trying to do here. As @fcoppens points out, if you know the functional form of the relationship between $x$ & $y$ (which needn't necessarily be linear), estimation of the parameters is straightforward & prediction intervals are of zero width. It sounds rather as if *interpolation* between the calculated values might be what you're after - statistical models for this sort of problem have narrow prediction intervals for $y$ when $x$ is close to some calculated value & wide ones when $x$ is far away from any.
Comment: I edited some more information into the question ... hope that helps in understanding it.
Comment: So presumably, given a measured value $x$, there *would* be some variability in the calculated values $y$, which might be modelled as random "error"? That's a least a rather empirical way of approaching it. Another is, supposing you have a particular mechanism for the data-generating process in mind, to consider the errors as being in $x$: see [Is regression of x on y clearly better than y on x in this case?](http://stats.stackexchange.com/questions/69646/is-regression-of-x-on-y-clearly-better-than-y-on-x-in-this-case/69667) (I'm imagining there are some physical parameters that on ...
Comment: the one hand are fed into a computer model to generate $y$ & on the other used to define the set up of an experiment to measure $x$.)
Comment: I don't mean that my y values are the same as the x values but only that as often as I "measure"=calculate the y values, they will be always the same. Normally there would be some experimental uncertainty that has to be assumed and that, I think, is one of the mathematical assumptions.
Comment: We've been reading your q. as about regressing $y$ on $x$ when the output $y$ is a deterministic, errorless function of the input $x$. That doesn't seem to square with the graph though - you're not saying that you calculate the "calculated value", say 1.19, *from* the "experimental value", say 2.12, are you?
Comment: Exactly, I do not calculate the y values *from* the experimental values. Those are dipole moments that were either measured ($x$) or calculated by quantum chemistry ($y$). Each point is one molecule with a certain dipole moment.
Comment: I guess the *x on y* version should work. Then I can get a guess with an error range for the real measured property from my calculated property value. Thank you for help!
Answer: First of all, deterministic (i.e. the same computation always yields the same result) does not imply error-free (not even free of random error!).

That being said, both ways of modeling, $y = f (x)$ as well as $x = f (y)$ are used in chemometrics. The former is known as ordinary or classical regression or calibration, the latter is referred to as inverse calibration.
Both ways of calibration have different characteristics.

As the comments already pointed out, one important difference is in the  assumption where most of the variance is: on $x$ or on $y$.
In addition, if the purpose of the model is prediction, you should predict forwards, i.e. in the direction that is modeled. That is, if you want to predict experimental results, model $experiment = f (theory)$.
On the other hand, if you assume the error is on your theoretical model and you are interested in the relationship between theoretical model and experimental results (remember: experimental science makes the fundamental point that if experiment and theory do not agree, it is theory that needs to change) and you e.g. need to measure the slope between experiment and theory, then model $theory = f (experiment)$
(In chemical analysis as in measuring concentrations, there are more important characteristics, wrt. to how multivariate measurements are used, and whether all constituents of the system are known - but these are probably not relevant for your problem).

I work with vibrational spectra which are sometimes computed for molecules in vacuum and then a correction factor is applied to account for the difference between vacuum (theory) and solution (reality/experiment). While I may be biased because I'm experimental spectroscopist, I'd say that at least in this situation it is very clear where the major source of error is...

About the DIN: are you referring to DIN 32465 or 38402?
They give formulas that are valid only under the stated assumptions (which are also in chemical analysis very often not met, particularly the variance homogeneity (also your graph looks like increasing variance with increasing values). The consequence is that you cannot use the "shortcut" formulas but have to do the proper calculation. In particular, you'd underestimate the uncertainty for high values and overestimate uncertainty for low values. From a statistics point of view, a weighted regression would be appropriate.
However, partiularly if you need to measure figures of merit such as limit of detection LOD or limit of quantitation LOQ, there are straightforward (though tedious) methods to do this almost without assumptions.


Are there fewer rhymes in contemporary popular music? If so, why?

Question: Vsauce mentions a study by Joan Serra showed contemporary pop music is less complex in its musical motives than it was, which he explains by a wider diversity in form and genres.
While complexity of melody is a complex question, since it depends on the listener which patterns he finds important, a rhyme and even a good rhyme is relatively easy to define as repetition of words whereas:

The stressed vowel sound in both words must be identical, as well as
  any subsequent sounds. For example, "sky" and "high"; "skylight" and
  "highlight".
The onset of the stressed syllable in the words must
  differ. For example, "bean" and "green" is a perfect rhyme, while
  "leave" and "believe" is not.

To me, it seems like rhymes, in this classical definition, have decreased in frequency in popular music over the last 60 years or so. Are there any studies/clues that would back this claim? If so, how do they explain it?
EDITS: Clarity & definition of a rhyme added
Comment: The notion of "good rhyme" is _not_ straightforward or easy to define. The term _perfect rhyme_ says nothing about the "goodness" of a rhyme; it merely describes a certain type of rhyme, in opposition to an _imperfect rhyme_, also called an _oblique rhyme_,  _slant rhyme_, or _off-rhyme_. Some of the greatest rhyming couplets in the history of poetry were slant rhymed couplets. This question still seems off-topic to me; you are asking for studies that support your idea, but requests for external resources are off-topic.
Comment: A good question, but by what standard would it be possible to answer objectively?
Comment: @user45266  I hope you re-evaluate the hold after I added an objective definition of rhymes.
Comment: @DavidBowling Sorry, "good rhyme" is actually part of the terminology in my language. More perfect would probably sound even worse. I don't know which word to choose but I'm not saying good rhymes imply good art.
Answer:
Vsauce mentions a study by Joan Serra showed contemporary pop music is less complex in its musical motives than it was, which he explains by a wider diversity in form and genres.

The problem with studies like this comes down to definitions. How do you define 'pop' music in a way that makes meaningful comparisons across time possible? How do you define 'complexity' in a way that is consistent across different musical genres, which focus on completely different types of musical elements?
The study in question seems to be this one. As far as I can tell, the researcher in question is just using songs that are in the million-song dataset - but I can't see in the study where he gives any reasoning as to why this is a scientifically-consistent collection of music to compare across time. (this article has some of the same objections about the study.)
The researcher has also been limited to the particular data fields already available in the million-song dataset; They don't seem to have independently validated the usefulness of those fields, although perhaps that validation is available elsewhere.

To me, it also seems like classical rock used more rhymes, or more intricate rhymes than the contemporary pop music. Is this true? If so, why?

To find out if it's true, you'd have to come up with a formal metric for 'rhyme intricacy', and do the analysis. I'd be incredibly surprised if a lot of current hip-hop oriented pop music didn't score very highly on some possible metrics for rhyme intricacy. But ultimately the metric would be subjective - as would the definitions for "classical rock" and "contemporary pop".
Edit, following the definition of rhyme being added to the question:
I am not aware of any comparative studies of rhyme frequency. My guess would be that you would see a wider range in rhyme frequency in contemporary chart music compared to the chart music of 60 years ago. On one hand, there is a prevalence of dance-influenced music that often treats lyrical content as somewhat textural or incidental, rather than focal. On the other hand, the last 40 years have seen the onset of hip-hop music which is likely to be much higher in rhyme density (probably in any type of rhyme) than any sung music. In fact two of the studies I can find on measurement of rhyming metrics focus on hip-hop:
Using Automated Rhyme Detection to
Characterize Rhyming Style in Rap Music
Automatic Detection of Internal and Imperfect Rhymes in Rap Lyrics
Of course defining what a rhyme is still doesn't give an entirely unambiguous metric for measuring rhyme frequency or richness. Do we do it as a metric per second (which would be affected by tempo), or per word? Do we count repetitions of rhyming couplets? How exactly do we define what "the stressed vowel sound" is, when this can vary according to accent/locality? Are we interested in rhymes within lines, or only at line endings?
Taking a step back, focusing on the definition of 'good rhyme' might be at odds with what many artists are actually trying to achieve. The Wikipedia entry on imperfect rhyme explains why there are a number of creative reasons why it is desirable to use imperfect rhymes (or half rhyme / slant rhyme):

This can be used to avoid rhyming clichés (e.g. rhyming "knowledge"
  with "college") or obvious rhymes, and gives the writer greater
  freedom and flexibility in forming lines of verse. Additionally, some
  words have no perfect rhyme in English, necessitating the use of slant
  rhyme. The use of half rhyme may also enable the construction of
  longer multisyllabic rhymes than otherwise possible.

Given that the creative use of imperfect rhyme can be seen as a good thing, it may be that the use of 'good' rhyme might subjectively be seem as naïve and clichéd.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/93380/discussion-between-topo-morto-and-probably).
Answer: With music production easily accessible to everyone (you really only need a computer and a mic) a lot of the music is made by people that I wouldn't personally define as "musicians". It sounds a bit snobby but what I mean is that more and more often pop music is produced by people that don't put their whole life towards studying music. This make them more "superficial" as composers, less interested in finding complex harmony (there are tones of pop songs that really use no more than 2 or 3 chords) and less interested in finding complex lyrics (rhymes, alliterations and other researched figures are almost absent in most of trap music for example).
I would say, without any intention to offend, that today "music ignorants" (as they ignore, they lack knowledge) are a major part of the producers and the listeners and this make pop music generally simpler.
Classic rock, jazz and similar genres were usually made by musicians that really mastered at least one instrument so they studied a lot of music in their lives (in contrast with rappers, trappers, djs and so on that often only learned how to use a software).
Comment: I think you're absolutely right that different audiences enjoy different things. Where I would disagree is with the idea that the people who successfully *create* music for a particular audience do so because they're ignorant. I think what you'll find is that the latest summer hit is generally made by teams of professionals who have a lot of very sophisticated knowledge about making that type of music - even if it is intentionally "lowest common denominator" stuff in some ways, that doesn't mean it's easy to be successful with it.
Comment: I'd say it's the other way around. Popular music is written by teams and created by studios with perfect knowledge of the demand.
Comment: *with perfect knowledge of the demand* that's exactly the problem: what we have is the sale of music and songs have become a ware. What sells best and popularity has never been a point of quality. But this has been also before the time of Bob Dylan and John Lennon. I'm still discovering new secrets and wonders in their lyrics. But I don't think that the rhymes are the most important criteria. It is the sense and content, whether they have to tell something or not, the message. And the rhymes sould really be hindering for this goal.
Comment: There absolutly are people with a lot of music knowledge, but are they interested in composing the new summer raggaeton hit? Not often..
Comment: Kendrick Lamar won a Music Pulitzer Prize without any music training (just an example in a sea of famous street teached rappers). I'm not saying pop artists are on a lower level, they just make their music in a different way. And that way make their music simpler.
Comment: Are you saying that there aren't actually people around today with the knowledge to produce good music? Because if there are, surely they could each easily make a few tunes and knock the 'ignorants' out of the charts?
Comment: but if they were able to produce music *better* than the new summer raggaeton hit, why wouldn't they?
Comment: They do but it is not appreciated by the masses as simpler pop music is. As i progress through my music study, the higher level of knowledge i go, the less people that listen to pop music i find in my classes. Same is true in the other direction. And I'm not saying they produce music better, that's just a matter of taste.
Comment: Yes, but he didn't make that album on his own - look at the list of producers at https://en.wikipedia.org/wiki/Damn_(Kendrick_Lamar_album). And lack of formal training doesn't mean lack of knowledge.
Comment: I understand what you mean and partially agree. The teams behind the actual singer could be trained, maybe even formal music trained (even if I still have to know a formal trained musician that would participate in some of those genres production). In that case the music is simple not because of ignorance but by choice.
Comment: @topomorto - Watch as they produce music better than the reggaeton hit and then promptly not market it worth a darn. (It's like my listening to music on YouTube and Musescore - despite how hit-and-miss they are overall, I've found several original composition gems on both websites that I'd say are better than the reggaeton hit.)
Comment: @Dekkadeci Do you mean better and similar in style, or better but very different in style? Or both?
Comment: @topomorto - Better but different in style.
Comment: @Dekkadeci well yep, I'm with you! I've found a bunch of (what I think are) great artists recently from following late-night radio or twitter links - once I check out their bandcamp or soundcloud sometimes they only have a few thousand listens - clearly they're not making much money yet. If they're working in a different style though, you can't really say their work is "better" than the latest reggaetón hit (even subjectively), because you're comparing apples and oranges.