Serve Static files from Google Cloud Storage Bucket (for Django App hosted on GCE)

Question: I'm trying to serve the static Files for my django App from Cloud Storage Bucket but don't know the exact process. Can someone please suggest a proper way to do so ?
Steps I did:

Uploaded all the static files on Google Cloud Storage Bucket(www.example.com) using gsutil command.
Edited /etc/apache2/sites-available/default-ssl.conf File.

File Content:
<VirtualHost *:443>
        ServerName example.com
        ServerAdmin email@example.com

 #       Alias /static /opt/projects/example-google/example_static
        Alias /static https://storage.googleapis.com/www.example.com/static
        <Directory /opt/projects/example-google/example_static>
           Require all granted
        </Directory>

        <Directory /opt/projects/example-google/example/example>
            <Files wsgi.py>
                Require all granted
            </Files>
        </Directory>

        WSGIDaemonProcess example python-path=/opt/projects/example-google/example:/opt/projects/example-google/venv/lib/python2.7/site-packages
        WSGIProcessGroup example
WSGIApplicationGroup %{GLOBAL}
        WSGIScriptAlias / /opt/projects/example-google/example/example/wsgi.py

        SSLEngine on
        SSLCertificateFile  /etc/apache2/ssl/example.com.crt
        SSLCertificateKeyFile /etc/apache2/ssl/example.com.key
        SSLCertificateChainFile /etc/apache2/ssl/intermediate.crt
</VirtualHost>

settings.py File:
# Static files (CSS, JavaScript, Images)
STATIC_URL = '/static/'
# STATIC_URL = 'https://storage.googleapis.com/www.example.com/static/'
STATIC_ROOT = os.path.join(BASE_DIR, '../example_static')

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, '../example_media')
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'), MEDIA_ROOT,)

Any suggestion on what all additional changes are required for this task ?
Thanks,
Comment: Any Suggestions Please ?
Answer: Main references:

https://django-storages.readthedocs.io/en/latest/backends/gcloud.html
https://medium.com/@umeshsaruk/upload-to-google-cloud-storage-using-django-storages-72ddec2f0d05

Prerequisite steps

Go to GCP: Cloud Storage (GCS) and click on CREATE BUCKET (fill-up as needed)
Once created, you can make it public if you want it to act like a CDN of your website (storage of your static files such as css, images, videos, etc.)

Go to your newly created bucket
Go to Permissions and then Click Add members
Add a new member "allUsers" with role "Cloud Storage - Storage Object Viewer"
Reference: https://cloud.google.com/storage/docs/quickstart-console

Method 1 (easier and faster, but requires constant manual copying of files to the GCS)

Configure your Django's static file settings in your settings.py

# Tell Django about the different locations to where the static files used by the project can be found
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'templates'),
    os.path.join(BASE_DIR, "yourapp1", "templates"),
    os.path.join(BASE_DIR, "yourapp2", "static"),
    os.path.join(BASE_DIR, "watever"),
    "/home/me/Music/TaylorSwift/",
    "/home/me/Videos/notNsfw/",
]

# If the command "collectstatic" is invoked, tell Django where to place all the collected static
# files from all the directories included in STATICFILES_DIRS. Be aware that configuring it with a
# path outside your /home/me means that you need to have permissions to write to that folder later
# on when you invoke "collectstatic", so you might need to login as root first or run it as sudo.
STATIC_ROOT = "/var/www/mywebsite/"

# Tell Django the base url to access the static files. Think of this as the "prefix" of the URL
# to where your static files are. Note that if you browse through your bucket and happen to see a
# URL such as "https://storage.cloud.google.com/<your_bucket_name>/someFileYouHaveUploaded", such
# URL requires that whoever accesses it should be currently logged-in with their Google accounts. If
# you want your static files to be publicly accessible by anyone whether they are logged-in or not,
# use the link "https://storage.googleapis.com/<your_bucket_name>/someFileYouHaveUploaded" instead.
STATIC_URL = "https://storage.googleapis.com/<your_bucket_name>/"

# References:
# https://docs.djangoproject.com/en/3.0/howto/static-files/
# https://docs.djangoproject.com/en/3.0/howto/static-files/deployment/
# https://docs.djangoproject.com/en/3.0/ref/settings/

If you have HTML files or CSS files that access other static files, make sure that they reference those other static files with this updated STATIC_URL setting.

In your home.html
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'home/css/home.css' %}">

Then in your home.css file
background-image: url("../assets/img/myHandsomeImage.jpg");

The home.css link now would translate to:

https://storage.googleapis.com/[your_bucket_name]/home/css/home.css

While the myHandsomeImage.jpg would be:

https://storage.googleapis.com/[your_bucket_name]/home/assets/img/myHandsomeImage.jpg

Of course if you wish, you could just put the absolute path (complete URL), but such configuration would always require you to update the used URLs manually, like if you switched to development mode and wanted to just access the static files locally instead of from GCS.

Run below. This would copy all files from each directory in STATICFILES_DIRS to STATIC_ROOT directory.

python3 manage.py collectstatic

# or if your STATIC_ROOT folder requires permissions to write to it then:
# sudo python3 manage.py collectstatic

Go to the STATIC_ROOT folder and upload its contents to GCS. Either upload them manually through the GCS GUI Console or through the Google provided tool "gsutil" along with rsync
Now, your GCS bucket already contains your static files, with your Django project configured to directly access those files through the configured STATIC_URL.

Method 2 (longer, but do not require manual copying after)

[OPTIONAL STEP] Prepare your python virtual environment

python3 -m venv path/to/the/target/location/for/the/virtual/environment
source path/to/the/target/location/for/the/virtual/environment/bin/activate

Install the necessary packages to be able to access and store directly to your GCS

pip3 install django-storages # https://pypi.org/project/django-storages/
pip3 install google-cloud-storage # https://pypi.org/project/google-cloud-storage/

[MANDATORY STEP if you are on a computer outside the Google Infrastructure] Go to GCP: IAM, Service Accounts, and click on CREATE SERVICE ACCOUNT

Name: SomeName
ID / email: somename
Role: Project - Owner
CREATE KEY, select JSON
Store the downloaded JSON file. This generated json key would be used later for authentication purposes once we start accessing and storing to the GCS
Reference: https://cloud.google.com/docs/authentication/getting-started

Configure your Django's static file settings in your settings.py

STATICFILES_DIRS = ['same_values_as_in_method_1_above']
DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage'
GS_BUCKET_NAME = 'your_bucket_name'
STATICFILES_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage'
STATIC_URL = 'https://storage.googleapis.com/<your_bucket_name>/'
from google.oauth2 import service_account
GS_CREDENTIALS = service_account.Credentials.from_service_account_file(
    'path/to/the/downloaded/json/key/credentials.json' # see step 3
)

# There are 2 ways to authenticate, you could either do 1 of the following
# 1. Define the variable GS_CREDENTIALS in the settings.py (as done above), or just
# 2. write the command "export GOOGLE_APPLICATION_CREDENTIALS='path/to/credentials.json'" in the shell where you would run the "collectstatic" command

Run below. This would copy all files from each directory in STATICFILES_DIRS directly to your GCS bucket. This might take a while.

python3 manage.py collectstatic

Now, your GCS bucket already contains your static files, with your Django project configured to directly access those files through the configured STATIC_URL.
Comment: THANK YOU, why is there literally no Google tutorial on this???  Do they expect people to just figure it out by trial and error??? Jeeeez
Comment: You just saved my life
Answer: Basically you need to:

create cloud storage bucket and set it to public readable.
collect static file local
copy file to cloud storage
set STATIC_URL

Check the step 1-4
https://cloud.google.com/python/django/container-engine#deploy_the_app_to_container_engine
Comment: @lucemia, is there a way to set static files in GCS in this fashion without making the files publicly available? These appear to be similar instructions to the ones provided by Google, so I'm assuming static files should/need to be publicly available in the bucket, but this had me thinking about secure document downloads from a bucket. Would you suggest simply using the cloud storage python package and some type of API for file gathering in those instances, or is it possible to make a googleapis url, accessible to my app but still not publicly available?
Comment: could you be more specific with number 4? What would one be setting STATIC_URL to, and why?
Comment: Yes, there is a signed urls https://cloud.google.com/storage/docs/access-control/signed-urls


Jquery: Como mostrar cada valor de um radio button em div's separadas quando clicado?

Question: Estou desenvolvendo um comparador de produtos onde, como exemplo, devo selecionar apenas dois produtos dentro de um universo com 4 produtos.
No caso o usuário selecionaria dois produtos dentro desse universo com 4 produtos e logo abaixo desse universo de produtos apareceriam informações dos dois produtos selecionados posicionadas uma do lado da outra (coluna 1 e coluna 2).
Para isso, estou codificando com Jquery, ajax e php para que quando for identificado a seleção de dois produtos, o ajax busque as informações desses mesmos no banco de dados (até aqui tudo bem).
A minha dúvida é: Como faço para que seja possível eu selecionar apenas dois produtos utilizando radio button limitando sempre apenas a duas seleções? E além disso, como faço para que a informação do produto selecionado apareça na coluna 1 e o segundo produto selecionado apareça na coluna 2?
Abaixo segue o que tenho desenvolvido até o momento:
Estrutura html que mostra 4 produtos com seus respectivos radio buttons:

Produtos

<input class="form-check-input radio" type="radio" name="produto1" id="1" value="Tênis preto">

<input class="form-check-input radio" type="radio" name="produto2" id="2" value="Tênis branco">

<input class="form-check-input radio" type="radio" name="produto3" id="3" value="Tênis verde">

<input class="form-check-input radio" type="radio" name="produto4" id="4" value="Tênis azul">

Abaixo, o código jquery que pega os valores dos itens selecionados e demonstram essas informações em suas respectivas colunas, onde não é permitido selecionar mais que dois produtos:
$('.radio').change(function(){

    var calcado = $(this).val();
    var count = $("input[type='radio']:checked").length;

    if(count > 2){

    alert("voce não pode comparar mais que dois produtos");

        $(this).prop('checked', false);

    return false;

    }

  // como faço para que se possa sempre selecionar apenas dois produtos mostrando informações dos produtos selecionados separadamente?

    $('#coluna1').text(calcado);
    $('#coluna2').text(calcado);

    //

});

No caso, como eu poderia melhorar o meu código para chegar no resultado descrito? Como exemplo prático fiz um esboço no JSFidle: https://jsfiddle.net/bhreywzu/
Comment: Veja na documentação [``](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/radio) que está tentando utilizando o componente para a finalidade errada, radior buttons são projetados para selecionar apenas um valor de um conjunto.
Comment: Fiz uma postagem no stackoverflow global sobre este mesmo problema e os gringos foram super gentis. Dê uma olhada por lá e perceba como me deram uma solução sem negativar minha dúvida. De qualquer forma, obrigado pelo feedback: https://stackoverflow.com/questions/73519894/jquery-limit-user-to-select-only-two-radio-options-at-once-and-display-values-i
Comment: Você vem falar de gentileza e me acusa de votar negativo na sua pergunta só porque fiz um comentário? Não senhor, olhe aqui https://imgur.com/a/MaStE0t você tem três voto negativos e um positivo, se eu tivesse negativado ficaria assim  https://imgur.com/3FgcBMi quatro votos negativos e um positivo.
Comment: Relaxa. Ficar assim é pior. Se ver meu comentário eu agradeci teu feedback. Aprenda ser gentil ;)
Comment: Você me acusa do que eu não fiz e me manda relaxar. Não sou seu familiar e nem seu amigo, se não tem provas de má conduta minha não me acuse. E não vou dar um negativo apenas porque me  deixou com ódio pessoal seu.
Comment: Que Deus ilumine teu caminho com muita luz. Fique com ELE \_/
Answer: Encontrei uma solução para essa questão. No caso utilizei um checkbox ao invés de um radio button. Abaixo segue o código Javascript que pega os valores do checkbox e os disponibiliza em uma div conforme o usuário vai clicando nas opções:
Na parte do html as duas divs que mostram os valores dos checkbox selecionado, foi acrescido uma class "output" conforme abaixo:

E abaixo, o código que pega os valores do checkbox e inseri os mesmos nas divs id coluna1 e coluna 2:

let $output = $('.output');

let updateSelections = () => {

  $output.text('');

  $calcados.filter(':checked').each((i, el) => {

    $output.eq(i).text(el.value);

  });
}

let $calcados = $('.radio').change(function() {

  if ($calcados.filter(':checked').length > 2) {

    $(this).prop('checked', false);

  } else {

    updateSelections();

  }

});

Fonte da resolução do problema: https://stackoverflow.com/questions/73519894/jquery-limit-user-to-select-only-two-radio-options-at-once-and-display-values-i


Create Apple TV Apps in portrait orientation mode

Question: For my business purpose we have to place Apple TV in portrait mode. How can I create an app that have portrait orientation?.
Answer: The concept from an SDK perspective does not exist. None of the rotation-related methods from iOS made it over to tvOS, and for a good reason. With that said, there is still a small segment where it could be useful to have your tvOS application being rendered with more vertical than horizontal space.
You can read this post for some help.
Comment: Thank you so much for your help. I followed the post but I  don't have an idea about how to manage keyboard of UITextfield. Even my UITextField is in Vertical orientation my keyboard is not rotating. If I rotate the window then it is not fit in the screen. Do you have any suggestion on this?
Comment: Hi! I do not know what is the reason for this. I tried to answer the question that you asked :)
Comment: As per requirement they place the Apple TV in portrait mode. So that I have to make portrait applications. Did you find out a way to manage keyboard?. All controls I can manage using window rotation method, but couldn't manage Keyboard.
Comment: @iphoneBees can see [this](https://stackoverflow.com/questions/14157582/ios-force-keyboard-to-be-presented-in-landscape-orientation) or [this](https://stackoverflow.com/questions/29495554/keyboard-issue-in-landscape-orientation-xcode-swift)
Comment: Thank you so much for the suggestion, but UIInterfaceOrientation method is not available for tvOS. Have to find out some other tricks.
Comment: Sure. If you come across any solution to manage keyboard please let me know.


How to add module to admin/config page?

Question: I'm working on a module in Drupal 7. I've added a hook_menu implementation:
$items['admin/config/content/mymodule'] = [
  'title'            => 'MyModule',
  'description'      => 'Configure MyModule settings.',
  'page callback'    => 'mymodule_get_form',
  'page arguments'   => ['mymodule_admin_settings'],
  'file'             => 'mymodule.admin.inc',
  'access arguments' => ['administer mymodule'],
  'menu_name'        => 'mymodule',
];

...and a configure line to mymodule.info:
configure = admin/config/content/mymodule

A Configure link for MyModule now appears the admin/modules page, but how can I also have the module listed on the admin/config page? Or is the admin/config page reserved for only core modules?
Answer: If you do it like this, with the system.module callback for the parent item, you get the nice listing page when you visit 'admin/config/mymodule'
/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {

  $items = [];

  $items['admin/config/mymodule'] = [
    'title'            => 'My configuration section',
    'description'      => 'This is the parent item',
    'position'         => 'left',
    'weight'           => -100,
    'page callback'    => 'system_admin_menu_block_page',
    'access arguments' => ['administer site configuration'],
    'file'             => 'system.admin.inc',
    'file path'        => drupal_get_path('module', 'system'),
  ];

  // Need at least one child item before your section will appear.
  $items['admin/config/mymodule/item'] = [
    'title'            => 'First item',
    'description'      => 'This is the first child item in the section',
    'page callback'    => 'mymodule_item_callback',
    'access arguments' => ['administer site configuration'],
  ];

  return $items;
}

Comment: @jevon: clearing the (menu) cache is adequate to see the changes.
Comment: Don't forget that you'll need to disable and enable the module for the menu changes to take effect.
Comment: menu cache can be cleared using drush at command line using `drush cc menu` - ref: https://drupal.stackexchange.com/a/58621/1082
Answer: Looking at the code of system_admin_config_page(), which is page callback for admin/config, I notice it contains the following lines:
if ($admin = db_query("SELECT menu_name, mlid FROM {menu_links} WHERE link_path = 'admin/config' AND module = 'system'")->fetchAssoc()) {
  $result = db_query("
    SELECT m.*, ml.*
    FROM {menu_links} ml
    INNER JOIN {menu_router} m ON ml.router_path = m.path
    WHERE ml.link_path != 'admin/help' AND menu_name = :menu_name AND ml.plid = :mlid AND hidden = 0", $admin, array('fetch' => PDO::FETCH_ASSOC));
  foreach ($result as $item) {
    _menu_link_translate($item);
    if (!$item['access']) {
      continue;
    }
    // ...
  }
  // ...
}

The first query select the menu_name field for the menu associated with the path admin/config, which by default is management; the second query select all the menus that have the same value for menu_name, and whose parent is admin/config.
As your menu uses a different value for menu_name, it is not selected from the second query, and it is not show in the admin/config page.
Answer: Remove the 'menu_name' part, that is not necessary.
Answer: I had trouble with this too on the config page.  The only way I was able to do add the link to the config page was to declare two menu items like so, with the parent link at 'admin/config/module' and a child link at 'admin/config/module/manage'.
  $items['admin/config/whh-maps'] = array(
    'title' => 'World Hiphop configuration',
    'description' => 'Allows administrators to configure maps for WHH.',
    'position' => 'left',
    'weight' => -30,
    'page callback' => 'drupal_get_form',
    'page arguments' => array('whh_maps_form'),
    'access arguments' => array('administer whh maps'),
    'file' => 'whh_maps.admin.inc',
  );
  $items['admin/config/whh-maps/manage'] = array(
    'title' => 'Manage countries',
    'description' => 'Allows admins to edit country information',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('whh_maps_form'),
    'access arguments' => array('administer whh maps'),
    'file' => 'whh_maps.admin.inc',
    'weight' => -10,
  );

Answer: $items['admin/config/user-interface/mymodule'] = array(
    'title' => 'My Module',
    'description' => 'description',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('my_admin_function'),
    'access arguments' => array('administer site configuration'),
);

$items['admin/config/user-interface/mymodule/manage'] = array(
    'title' => 'My Module',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'description' => 'description',
    'weight' => -10,
);
return $items;

this worked for me.
I was actually struggling for about half an hour until I realized I wasn't returning $items....I always seem to do that.
Answer: /**
 * Implements hook_menu().
 */
function notification_menu() {

  $items = [];

  $items['admin/customize'] = [
    'title'            => 'Send Comment notifications',
    'discription'      => 'Admin will send notification to user about updates',
    'type'             => MENU_NORMAL_ITEM,
    'page callback'    => 'drupal_get_form',
    'page arguments'   => ['notification_form'],
    'access arguments' => ['access adminstration page'],
    'access callback'  => TRUE,
  ];

  return $items;
}

/**
 * Custom form.
 */
function notification_form($form, &$form_state) {

  $form['send_mail_to'] = [
    '#title'         => 'Send Mail To',
    '#discription'   => 'To whom you want to send form',
    '#size'          => 40,
    '#type'          => 'textfield',
    '#required'      => TRUE,
    '#default_value' => variable_get('send_mail_to'),
  ];

  //here the admin can wite subject for the mail.
  $form['mail_subject'] = [
    '#title'         => 'Subject',
    '#discription'   => 'the purpous of this mail',
    '#type'          => 'textfield',
    '#size'          => 40,
    '#maxlenght'     => 120,
    '#required'      => TRUE,
    '#default_value' => variable_get('mail_subject'),
  ];

  $form['mail_body'] = [
    '#title'         => 'Body',
    '#discription'   => 'the body of your mail.',
    '#type'          => 'textarea',
    '#row'           => 10,
    '#columns'       => 40,
    '#required'      => TRUE,
    '#default_value' => variable_get('mail_body'),
  ];

  $form['mail_bcc'] = [
    '#title' => 'BCC this mail to all',
    '#type'  => 'checkbox',

  ];

  return system_settings_form($form);
}

Comment: This doesn't answer the question, since it doesn't say why the OP is not seeing their module listed in the admin page; plus, code-only answers are not much helpful. (Check the code: You have some typos.)

How to add module to admin/config page?


The file names are not transliterated on upload

Question: I am using Drupal 7 and have transliteration module enabled.
I have a file field and I want to have the names of the uploaded files to be transliterated on upload.
The url alias for the nodes are well transliterated. But the file names are not.
I checked the settings for file system. The current settings are:

Transliterate file names during upload.(checked)
Lowercase transliterated file names. (checked)

If I "Transliterate existing file names" (admin/config/media/file-system/transliteration) then the names of the files I have already uploaded are transliterated. But still, when I upload new files, the file names are not transliterated.
Any ideas why the names are not translated on upload?
Comment: @Jimajamma yes, they are there and I have set them as stated in the question. Still the filenames are not transliterated.
Comment: The transliteration settings *should* be right off `admin/config/media/file-system/settings`
Comment: @Jimajamma, I cannot understand what you mean. What should be off?
Comment: if you go to `www.yoursite.com/admin/config/media/file-system/settings` the transliteration options should be right there
Comment: You did not mention `Transliterate file names during upload` which is the key setting on the menu I mentioned.  If you installed transliteration AFTER you uploaded files, the files prior still may have oddball chars in them but all new file uploads should be transliterated.  If this is the case, there is a TRANSLITERATION button (by default up in the top right corner) that will allow you to bulk transliterate those preexisting files.  If this is not the case, then it suggests a installation issue on your site that is beyond the scope here.
Comment: @Jimajamma Actually I did mention to **Transliterate file names during upload**. I now updated the question. And I tried "Transliterate existing file names". It works fine. But still, when I upload new files, the file names are not transliterated
Comment: is this a file field ? did you check the settings on the field ?
Comment: @mojzis, it is a file field. I checked the settings of the field but found none related with transliteration. Which setting exactly are you referring to?
Answer: File names are not URL aliases. Pathauto has never had any sort of integration with files at all.
Comment: Right, thank you. I edited the question and hope it describes the problem better now.
Answer: Although this is an old question, you could add debug in
transliteration_init
To check the value of $_FILES and transliteration there.
for example, to test the var value, add
watchdog('debug', var_export($_FILES, 1));


How to write an equation that's nested?

Question: Let's say I have an equation that's nested:
$$
\displaystyle x = f\left(f\left(f\left(f\left(f\left(i, a_4\right), a_3\right), a_2\right), a_1\right), a_0\right)
$$
If I wanted to write this equation where it's nested from $a_k$ to $a_0$ without writing out all the terms, how would I denote it?
Answer: I can think of two possibilities.  One is
$$
x = f(f(\cdots f(f(i, a_k), a_{k-1}), \ldots, a_1), a_0)
$$
and the other is
$$
x = b_0
$$
where
$$
b_j = f(b_{j+1}, a_j) \qquad 0 \leq j < k
$$
$$
b_k = f(i, a_k)
$$
Answer: You could write e.g. write  $x = f(\ldots f(f(i,a_k),a_{k-1})\ldots ,a_0)$
or alternatively define $g_n (y) := f(y,a_n)$ and write the equation as $$x = \left(\bigcirc_{n=0}^k g_n\right)(i)$$
Comment: The cirle is here used as the composition operator on a function space: For $h := f \circ g$ we get $h(x) = f(g(x)) \forall x$. The big symbols are just used for repeating the given symbol, like $\bigcup \bigcap \oplus$ e.t.c
Comment: Thanks. I'm not familiar with this big circle. What is this called?
Comment: I wouldn't use the big circle notation, it's very ambiguous unless your operator is both commutative and associative.
Comment: @McFry Right, that is a crucial point! As long as you have "count", you could still properly define a direction, without needing commutativity.
Answer: Depending on the audience (if they're coming from a slightly more computer-scientific background), treating as the function foldl could perhaps be the clearest. See also How to write a functional fold in mathematics?

How to write an equation that's nested?


get button in movieclip to go to another frame inside the same movie clip

Question: I have several website pages set up on different frames inside the content (which is a movieclip) of the home page - which is on frame 1 of the main timeline. The content movieclip name is contentMc.
My About page is at frame 10. There is a button on this page (called btnAbout_contactpg) that I want to make jump to my Contact page (frame 50) - all of which is nested under the main contentMc movieclip.
This is the pathway on my contentMc (where all of my pages are located), just in case that doesn't make sense: https://lh4.googleusercontent.com/-YHqWuWYUkME/TuuwcRzUkaI/AAAAAAAAAXM/47EwKEr0uTk/s193/pathway.png
I cannot figure out how to do this. I have looked at several different instructions online, but none of them seem to work.
If anyone can help it would be much appreciated!
EDIT:
I am also trying to get a button on my gallery page to load an external image, but it is not recognizing where the button is either:
btnGallery_1.addEventListener (MouseEvent.CLICK, showPic1);
function showPic1 (e:MouseEvent) {
    var target:Object=e.target;
    var parent=target.parent;
    my_loader.load(new URLRequest("image-0.jpg"));
}

Answer: btnAbout_contactpg.addEventListener(MouseEvent.CLICK,gotoContact);
function gotoContact(e:MouseEvent){
    var target:Object=e.target;
    var parent=target.parent;
    // if your "pages" are themselves movieclips, you will probably need to uncomment out the line below
    //parent=parent.parent;
    parent.gotoAndStop(50);
}

At first glance, this should work.
UPDATE:
Lemme guess... your button (btnAbout_contactpg) is only on frame 50...
...so the code you have on your main timeline (presumably on frame 1) is trying to add a listener to an object that won't exist for another 49 frames...
Therefore, barring a complete revamp of your movie's structure (to better utilize the Display model - addChild(), removeChild(), addChildAt(), etc.), I'm going to suggest doing something that is considered BAD PRACTICE.  Add the code (to add the listener) to the button to the frame where the button appears.  You may need to alter the path when specifying the callback though.  Something like:
btnAbout_contactpg.addEventListener(MouseEvent.CLICK,this.parent.gotoContact);

Comment: You've asked the same question before, slightly different, and got the same answer - perhaps it's time you started looking at some tutorials on how to use the timeline and on basic ActionScript now...
Comment: I tried it with and without the parent=parent.parent; line and this is the error I got both times:  1120 Access of undefined property btnAbout_contactpg. The other methods I have tried did the same thing. I'm wondering if the pathway is not connecting to the button name correctly.
Comment: I put the code you suggested on my actions layer on the main timeline - is that the right spot? It's where the rest of my code is.
Comment: Check my UPDATE.

Also, you might want to delve into the display tools more.  It makes updating the items on your stage a trivial process.

...of course, you might also want to look into the Cairngorm framework.  With a little fiddling (ok a LOT if you are using Flash rather than Flex) you could set up a "pageManager" that would eliminate the need to actually use the timeline.  Such a class/object is waaaaaay out of scope for this question though.  I offer it as a suggested resource for your future efforts.
Comment: @Prpl_Ppl_Etr My button is actually only on frame 10 (where my About page is). I'm trying to have a link that is something like "Click here to see my Contact Page" (then you click and skip to frame 50).
Comment: @Prpl_Ppl_Etr To clarify: this is the code you suggested? btnAbout_contactpg.addEventListener(MouseEvent.CLICK,this.parent.gotoContact);
function gotoContact(e:MouseEvent){
    var target:Object=e.target;
    var parent=target.parent;
    // if your "pages" are themselves movieclips, you will probably need to uncomment out the line below
    parent=parent.parent;
    parent.gotoAndStop(50);
}
Comment: I put that code on the same frame that the button is on. I received this error code:

Symbol 'contentMc', Layer 'buttons', Frame 10, Line 1 1119: Access of possibly undefined property gotoContact through a reference with static type flash.display:DisplayObjectContainer.
Comment: Yes that is the code I suggested, but since I don't know your specific structure, I can't possible provide you with the actual definitive paths.  I figured you'd be able to determine it once I showed you what was required.

...or after @weltraumpirat told you something similar...

If the concept of parent/child relationships between movieclips, and the resulting path requirements is still confusing to you, you REALLLLLLY need to spend the afternoon doing a few tutorials on the subject.  This is about as basic a conecpt as you're going to run into in Flash programming.

Good Luck!
Comment: @Prpl_Ppl_Etr Hence why I'm glad Flash is pretty much dead. Thanks for trying to help!
Comment: @user1102296 You will run into similar problems with other languages, unless you start trying to understand the basic concepts of programming. It's easy to bash Flash, but most of the horrific ActionScript-based applications out there are just very badly coded. That's what you get for making people think that moving a few keyframes makes you a web designer.


Rails adds `AND (1=0)` to queries

Question: Rails somehow adds AND (1=0) to the SQL query of a model:
CompanyRelation Load (0.2ms)  SELECT `company_relations`.* FROM `company_relations` WHERE `company_relations`.`vendor_id` = 1 AND (1=0)

Comment: You are either making use of a scope (default or otherwise), or have some strange plugin that is doing this.  Can you show the code that builds up the logic for your query?
Comment: I've added the model's code to the question.. It's dead simple.. I use Squeel, removing it doesn't fix anything..
Comment: Could it be CanCan? I use it to autoload my resources..?
Comment: You haven't posted what is triggering the query in question, not to mention how that triggering object is being built...
Comment: I guess I found it: https://github.com/ryanb/cancan/issues/733
Comment: I'm having a similar problem [here](http://stackoverflow.com/questions/21886242/why-is-rails-is-adding-or-1-0-to-queries-using-the-where-clause-hash-syntax-wi/21887717) but I'm _not_ using CanCan.
Answer: Also you can find 1=1 or 1=0 in your query if you do where(params[:data])
and data it's a hash with empty values. For example you have params hash live
{ village: { directions: { id: Empty Array }}}

Answer: Seems to be an issue with CanCan:
http://github.com/ryanb/cancan/issues/733
Answer: This is the first question I found that included "rails  scope 'AND 1=0'".
As mentioned by rossmari, there may be an empty hash. You may unintentionally be applying a scope to the conditions you use to generate a hash. This scope could leave you with an empty hash. For example
Assessment.last.children.for_user(user)

would apply the children scope inside the for_user scope which you might not be expecting. In the example below, a hash of ids is passed through the id parameter.
If you have something like
scope :for_user, lambda { |user|
    where(id: Question.where(assigned_to: user).... #a hash

then try adding unscoped
scope :for_user, lambda { |user|
    where(id: Question.unscoped.where(assigned_to: user).... #a hash

Edit: I've found that when I think I've needed unscoped, there's a good chance I've structured my queries incorrectly.

Rails adds `AND (1=0)` to queries


Basis for Tensor Product of Infinite Dimensional Vector Spaces

Question: If V and W are vector spaces over a common field with bases $V_B = ${$v_i : i \in I$} and $W_B = ${$w_j : j \in J$}, then is {$v_i \otimes w_j: i \in I, j \in J$} a basis for $V \otimes W$ ?
I have several references for the finite dimensional case but they seem to involve either a dimensional argument or reference to dual spaces, neither of which would seem to be appropriate in the infinite dimensional case.
The references that I can find for infinite dimensional spaces focus on "orthonormal bases" (usually in the context of Hilbert Spaces).
So, I'd appreciate any help answering

is this actually true if {$v_i : i \in I$} and {$w_j : j \in J$} are the Hamel (algebraic) bases of infinite dimensional spaces and what is the proof ?
Does it make any difference if only one space is infinite dimensional ?
Is there any difference between countable and larger infinities ?

Addendum 15 March 2015:
Why not simply define the tensor product as $F(V_B \times W_B)$, i.e. the free vector space generated by the set of ordered pairs of basis vectors ? There seems to be a bilinear mapping from $V \times W$ and it appears to satisfy the universal property.
Have I missed something here ?
Comment: @DBS So, we agree. An orthonormal basis may not span an infinite dimensional space. But an orthonormal basis is not the same thing as an algebraic basis, and by definition an algebraic basis does span its space. Now, in some infinite vector spaces the algebraic basis may not be easy to find, or of much use if found, but it always exists (proof from Zorn's lemma).
Comment: @DBS. Thanks for your interest, but I beg to differ. I think that in an infinite dimensional inner-product space, the orthonormal basis aligns with what you are saying. But in any space, the algebraic basis does by definition span the space.
Comment: As a side remark:In infinite dimensions algebraic bases do not span the vector space (there are elements that are not finite linear combinations of the basis elements). So one can consider algebraic tensor products (which is what you probably have in mind) and also completed tensor product (denoted by $\widehat{\otimes}$ in both cases and algebraic basis is given by $v_{i} \otimes w_{j}$.
Comment: The example I had in mind is take $V= L^{2}(S^{1})$, then the functions $e^{2 \pi inx}$  forms an orthogonal basis for $V$ but there are  $L^{2}$ functions which do not have infinitely many non zero fourier coeff. So the algebraic span (which can only have finitely many non-zero basis vectors) is dense (in the natural topology) of $V$ but it doesn't span $V$.
Comment: Yes we agree. i don't know if there is an explicit description of an algebraic basis in the above example though. I would be interested if there is one.
Answer: Yes it is true independent of the cardinality of the bases of the vector spaces. Use the universal property: Let $T$ be any vector space over the given field.
A bilinear map $V \times W \to T$ is uniquely determined by the images of the pairs $(v_i,w_j)_{i \in I,j \in J}$, so we get
$$Bil(V \times W, T) = Abb(\{(v_i,w_j), i \in I, j \in J\},T)= Abb(\{v_i \otimes w_j, i \in I, j \in J\},T)$$
By the universal property $V \otimes W$ is the vector-space with the property
$$Hom(V \otimes W,T) = Bil(V \times W, T)$$
, so we obtain
$$Hom(V \otimes W,T) = Abb(\{v_i \otimes w_j, i \in I, j \in J\},T)$$
, which precisely states that $\{v_i \otimes w_j, i \in I, j \in J\}$ is a basis of $V \otimes W$.
Let us precise this:
Given a map in $f \in Abb(\{v_i \otimes w_j, i \in I, j \in J\},T)$, which means that we are given $f(v_i \otimes w_j)$ for all $i \in I, j \in J$, we have to show that this extends uniquely to a map $F:V \otimes W \to T$.
We define the bilinear map $\hat f: V \times W \to T$ by $\hat f(v_i,w_j) := f(v_i \otimes w_j)$. By the universal property, this gives us a unique map $F:V \otimes W \to T, F(v \otimes w)=\hat f(v_i,w_j)=f(v_i \otimes w_j)$. Hence this is the desired unique map.
The uniqueness of $F$ is trivial anyway, because $\{v_i \otimes w_j, i \in I, j \in J\}$ is clearly a set of generators. We only need to show the existence of $F$ here (And this corresponds to the linear independence).
Comment: Thanks for the response. Unfortunately I don't know what Abb() is and I don't get anything relevant from Google - could you please enlighten me ?
Comment: This is just the set of all set maps between two sets.
Comment: Thanks again. But now when I get to $Bil(V \times W, T) = Abb(\{(v_i,w_j), i \in I, j \in J\},T)= Abb(\{v_i \otimes w_j, i \in I, j \in J\},T)$ I can only see the stated equalities as bijections. So that gives me a bijection between $Hom(V \otimes W,T)$ and $Abb(\{v_i \otimes w_j, i \in I, j \in J\},T)$, is that sufficient to make $ \{v_i \otimes w_j, i \in I, j \in J\}$ a basis ?
Comment: The bijections are natural. Think about this while having the commutative diagram from the universal property in mind.
Comment: To complete my understanding of this can you comment on "Why not simply define the tensor product as $F(V_B \times W_B)$ ?" This would seem to be a lot simpler than involving quotient spaces to show the existence of a tensor product.
Comment: This would work only for vector-spaces and free modules. The tensor product exists in a much more general context.
Answer: I give a "conceptual" answer.
Let $k$ be a field, and $V, W$ vector spaces over $k$. Recall that $k$-vector space $V\otimes_k W$ has the following universal property : if we note $\pi : V\times W\to V\otimes_k W$ the canonical $k$-bilinear map $(v,w)\mapsto v\otimes w$ and $\textrm{Bil}_k (V,W;P)$ the set of $k$-bilinear applications $V\times W\to P$ for a $k$-vector space $P$, then we have : for each $k$-vector space $P$ the map $\textrm{Hom}_k (V\otimes_k W,P)\to \textrm{Bil}_k (V,W;P)$ definied by $f\mapsto f\circ\pi$ is a bijection.
As I think that any answer to your question should emphasize what is true in general, what is proper to the situation (vector spaces = modules over a field) and what things are independent. I will prove the following three general lemmas, with the following hypothesis : from now on, $k$ is not a field but a commutative ring with unit, and $V,W$ are modules over $k$.
Lemma 0. The elements of the form $v\otimes w$ for $v\in V$ and $w\in W$, called elementary tensors (or also simple tensors), generate $V\otimes_k W$ over $k$.
Proof. I give a proof of this lemma using only the universal property of $V\otimes_k W$ and not any of its constructions (as quotient of $A^{(W\times V)}$ for instance). Note $Q$ the sub-$k$-module of $V\otimes_k W$ generated by elementary tensors. Note $\pi' : V\times W\to Q$ the map defined by $(v,w)\mapsto v\otimes w \in Q$. I pretend that $Q$ and $\pi'$ satisfies the same universal property that $V\otimes_k W$ and $\pi$ do. Let $P$ be a $k$-module. The map $\textrm{Hom}_k (Q,P)\to \textrm{Bil}_k (V,W;P)$ defined by $f\mapsto f\circ\pi'$ is a injective. Indeed : if $f\circ \pi' = g\circ \pi'$ for $f,g\in \textrm{Hom}_k (Q,P)$ then it means that $f$ and $g$ are equal on elementary tensors, and as elementary tensor generate $Q$ by definition of $Q$, we have $f=g$. Now, let's show that this map is surjective, so take $b\in \textrm{Bil}_k (V,W;P)$. By the universal property of $V\otimes_k W$ we can find $f\in \textrm{Hom}_k (V\otimes_k W,P)$ such that $b = f\circ\pi$, which obviously imply that $b = f' \circ \pi'$, where the $k$-linear map $f' : Q\to P$ is the restriction of $f$ to the submodule $Q$ of $V\otimes_k W$, that is, the $k$-linear map $f' : Q\to P$ defined by $q\mapsto f(q)$ for $q\in Q$. This shows the surjectivity of the map $\textrm{Hom}_k (Q,P)\to \textrm{Bil}_k (V,W;P)$, which is finally injective and surjective, that is, bijective. This shows that $Q$ and $\pi'$ satisfies the same universal property that $V\otimes_k W$ and $\pi$ do. Thanks to this, we will now show that $Q = V\otimes_k W$. Note $i : Q \to V\otimes_k W$ the canonical injection : it is the map sending an element of $Q$ to the same element but viewed as element of $V\times_k W$. Rephrased, what we want to show is that $i$ is surjective. Now $\pi' : V\times W \to Q$ is a $k$-bilinear map, so that by the universal property of $V\otimes_k W$ and $\pi$, there exists a unique $k$-linear map $\varphi : V\otimes_k W \to $ such that $\varphi\circ \pi = \pi'$. But then $(i\circ\varphi)\circ\pi = i\circ(\varphi\circ\pi) = i\circ\pi' = \pi = \textrm{Id}_{V\otimes_k W}\circ\pi$, and by the universal property $i\circ\varphi = \textrm{Id}_{V\otimes_k W}$, showing that $i$ has a right inverse, and is therefore surjective. $\square$
Lemma 1. If $(v_i)_{i\in I}$ (resp. $(w_j)_{j\in J}$) is a familly of generating elements of $V$ (resp. of $W$) over $k$, then the familly $(v_i\otimes w_j)_{(i,j)\in I\times J}$ is a familly of of generating elements of $V\otimes_k W$ over $k$.
Proof. As $\pi$ is $k$-bilinear, it is clear that any elementary tensor will be linear combination of $v_i\otimes w_j$'s over $k$, and by the previous lemma, the elementary tensors generate $V\otimes_k W$, showing thereby that the elements $v_i\otimes w_j$'s generate V\otimes_k W$
From now on we suppose that $k$ is a field.
Lemma 2. If $(v_i)_{i\in I}$ (resp. $(w_j)_{j\in J}$) is a familly of independant elements of $V$ (resp. of $W$) over $k$, then the familly $(v_i\otimes w_j)_{(i,j)\in I\times J}$ is a familly of independant vector of $V\otimes_k W$ over $k$. $\square$
Proof. Suppose we have a dependance relation $$\sum_{(i,j)\in I\times J} c_{i,j} v_i\otimes w_j = 0$$ where $(c_{i,j})_{(i,j)\in I\times J}$ is a familly a elements in $k$ such that $c_{i,j}\not=0$ only for finitely many indexes $(i,j)$'s. Complete $(v_i)_{i\in I}$ (resp. $(w_j)_{j\in J}$) in a basis $(v_i)_{i\in \overline{I}}$ (resp. $(w_j)_{j\in \overline{J}}$) of $V$ resp. (of $W$) over $k$. Take $(i_0,j_0)\in I\times J$ and let's show that $c_{i_0,j_0} = 0$. For this, consider the bilinear function $V\times W\to k$ sending $(v,w)=\left( \sum_{i\in \overline{I}} \lambda_i v_i, \sum_{j\in \overline{J}} \mu_j w_j \right)$ to $\lambda_{i_0} \mu_{j_0}$. Take by the universal property $f : V\otimes_k W \to k$ to be the linear map associated to this bilinear form. Applying the linear function to the above dependance equation gives $c_{i_0,j_0} = 0$. $\square$
Lemma 2 and 3 applied to the case of a field do answer your question.
Remark. No cardinality hypothesis were made.
Comment: Thanks for the response: I haven't had chance to digest it all yet.
Comment: If you need details, don't hesitate
Comment: I just corrected some typos in my answer.


Qual é o propósito de um parêntesis vazio "()" numa expressão regular?

Question: Pesquisando no Stackoverlow Inglês sobre expressões regulares, deparei-me com uma determinada expressão onde apresenta na mesma um grupo vazio (uma expressão entre parênteses vazia).
Assim:
(DE)()([0-9]{1,12})

Qual é o propósito dessa "grupo vazio" (()) numa expressão regular?
Comment: costumo testar as que faço em "testadores" online, não fez diferença com ou sem. vou olhar com mais cuidado para poder ajudar lhe.

fonte de estudo: http://aurelio.net/regex/guia/
Comment: Pelo pouco que sei, (regex é enorme) não faz sentido algum na expressão q vc postou.
Comment: Muita coisa em expressão regular não faz sentido para mim (porque não entendo para que serve). Mas que tem um propósito tem, senão não seria possível fazê-lo.
Comment: @WallaceMaxters se esqueceu desta? ou ainda desejas uma resposta melhor?
Comment: @GuilhermeLautert acho que talvez caiba apenas uma edição explicando em que caso seria útil. (se você me disser que usar um grupo vazio não é útil em caso nenhum, marco imediatamente).
Answer: Dependendo do caso apenas confundir quem está lendo a regex. Parêntesis indicam captura de grupo, então na expressão (DE)()([0-9]{1,12}) DE vai ser capturado no primeiro grupo, no segundo vamos capturar nada e no terceiro [0-9]{1,12}, sendo que cada grupo pode ser referenciado por $numerodogrupo (na verdade depende da regex engine, algumas não usam cifrão), então temos três grupos: $1, $2 e $3. Exemplo prático, inverter o texto DE25324534 usando a regex que você passou:

var str = 'DE25324534';
var inverted = str.replace(/(DE)()([0-9]{1,12})/, '$3$1$2');
document.write(inverted);

O que ocorre aí é que a string original é substituída por $3 (os digitos) seguida pelo grupo $1 (DE), seguida pelo grupo $2 (não tem nada dentro), assim você pode ver que () solto na regex serve para absolutamente nada neste caso, contudo pode fazer sentido em algumas situações como mostrado na resposta do Guilherme Lautert.
Comment: Não se deve julgar algo pelo primeira abstração que se vê. Esse "serve para absolutamente nada", é muito relativo.
Comment: @GuilhermeLautert também concordo. Na pergunta que vi no SOEN, me pareceu relativo a algo como : "Se eu substituir a regex, não precisarei substituir a ordem da captura de grupos. Basta colocar um grupo vazio, para que a contagem dos grupos fiquem semelhantes na substituição"
Comment: @WallaceMaxters eu montei um exemplo assim, mas esta muito feio, to tentando melhorar '-'
Answer: A priori, nenhum.
Parênteses normalmente são usados para identificar grupos. Grupos, por sua vez, são usados para operações como extração de informações específicas ou localização de áreas para substituição da cadeia de caracteres considerado.
Neste seu caso, o motor de expressão regular apenas criará um grupo vazio, que sequer pode ser localizado.
Comment: Este resposta esta de acordo com o que o grupo representa, "um grupo vazio, que sequer pode ser localizado. ", a implementação vai depender do programador.
Answer: Complementando a Resposta do Cigano.
Grupo são usado para extração de informação ou reutilização.
Um grupo () vazio faz referencia ao nada que em compiladore seria o mesmo que uma transição direta para o próximo estagio.

Exemplo (ruim, mas demostrativo)
var replace = '$1$3$5';

'2016/02/02'.replace(/(\d{4})(\/)(\d{2})(\/)(\d{2})/, replace); // 20160202
'2016-02-02'.replace(/(\d{4})(-)(\d{2})(-)(\d{2})/, replace);   // 20160202
'20160202'.replace(/(\d{4})()(\d{2})()(\d{2})/, replace);       // 20160202

Comment: upvote. Ótimo exemplo e realmente faz sentido tanto na base teórica em finite automaton quanto na utilidade prática. Editei minha resposta para não generalizar tanto e para referenciar a sua.
Comment: Ah, então a ideia é ter uma sequência onde a parametrização é prevista de uma determinada forma. Ou seja, usa-se o grupo vazio para poder forçar o parâmetro com o valor desejado, independente da sequência na regex (podia apenas ter colocado isso na resposta :p)
Comment: @WallaceMaxters é esse exemplo não foi dos melhores, mas sim seria isso.
Answer: Acredito que você tenha visto esta pergunta (pelo menos é a mesma regex), e lá também são listados alguns possíveis usos para este recurso (que explico com mais detalhes abaixo).
Vale lembrar que, como já dito nas outras respostas, na expressão específica que você colocou, sem nenhum contexto adicional, esses parênteses realmente não servem para nada.

Mas dependendo do contexto, ele pode ter seus usos. Lembrando que um par de parênteses cria um grupo de captura, que fará parte do match retornado. Mesmo que não tenha nada dentro dele, será criado um grupo contendo "nada" (o que na maioria das implementações - senão em todas - resulta em uma string vazia).
E quando isso seria útil? Bem, imagine um caso em que tenho uma função que recebe o match de uma regex e usa somente os grupos 1 e 3 (exemplos em Python, mas poderia ser em qualquer outra linguagem que suporte grupos de captura):
def faz_algo(match):
    g1 = match.group(1)
    g3 = match.group(3)
    # ... faz algo com os grupos 1 e 3 (os demais são ignorados)

import re

match = re.match(r'([a-z]+)(\d+)([a-z]+)', 'abc123xyz')
if match:
    faz_algo(match)

No exemplo acima, estou criando três grupos: um com letras, outro com dígitos, e outro com letras. Na função faz_algo, pego somente os grupos 1 e 3 (no caso, eles serão respectivamente abc e xyz).
Agora vamos supor que tenho um caso em que quero reaproveitar a função faz_algo, mas agora eu preciso pegar abc e 123. Neste caso, eu mudaria a regex para:
match = re.match(r'([a-z]+)()(\d+)', 'abc123xyz')

Ou seja, agora o grupo 1 são as letras (abc), o grupo 2 é vazio, e o grupo 3 são os números (123). Desta forma, não preciso mudar a função faz_algo, pois ela continua pegando os grupos 1 e 3. Eu só preciso ajustar a regex para que estes grupos contenham o que eu preciso.
Claro que eu poderia criar outra função que verifica os grupos do match e refatorar faz_algo para receber os valores como parâmetros, em vez de sempre buscar grupos fixos. Mas pode ser que eu não possa modificar a função faz_algo (por exemplo, ela é de uma dependência externa, etc). Enfim, esta é uma situação na qual um grupo vazio seria útil (embora admito que seja uma "solução de elegância questionável").

Outro uso "esotérico" é que um grupo vazio pode ser usado como um "marcador": uma indicação de que a regex "passou" pode determinado ponto.
Vamos supor que tenho vários números sendo lidos de algum lugar, e eu quero verificar quais contém 4 dígitos, mas somente os dígitos de 1 a 4, e todos os dígitos são diferentes (ou seja, 1234 e 3241 são ok, mas 1123, 3333 e 1235 não). Eu sei que dá para resolver de maneira mais fácil sem regex, mas com regex uma opção seria:
import re

r = re.compile(r'^(?:1()|2()|3()|4()){4}\1\2\3\4$')
for n in range(1000000):
    if r.match(str(n)):
        print(n)

Ela é bem confusa e complexa, mas basicamente: (?:1()|2()|3()|4()) é um grupo de não-captura (indicado por (?:), ou seja, o primeiro parênteses não cria um grupo. Dentro dele temos uma alternância com quatro opções: os dígitos de 1 a 4.
Repare que depois de cada dígito tem um grupo vazio. E eles servem apenas para indicar que a regex passou por ali. Ou seja, se ela encontrar um dígito 1, o grupo 1 estará setado (ele conterá a string vazia, mas o que importa é que estará setado no match). O mesmo vale para os outros dígitos: se os quatro grupos estiverem setados, quer dizer que tem pelo menos um digito de cada na string.
A seguir, eu coloco o quantificador {4} para indicar que quero 4 dígitos. Note que aqui eu ainda não garanti a unicidade (a string poderia ser, por exemplo, 1122 - e neste caso somente os grupos 1 e 2 estariam setados).
E como eu faço para garantir que os 4 grupos estão setados? Eu uso as back-references: no caso, \1 refere-se ao grupo 1, \2 ao grupo 2, etc. Como os grupos são vazios, então os valores das back-references serão strings vazias, mas somente se os respectivos grupos estiverem setados.
Ou seja, se algum grupo não estiver setado, a back-reference também não estará, e a regex não encontrará um match. Por exemplo, se o número for 1124, o grupo 3 não estará setado, e portanto \3 também não. Então a regex falha, pois ela tenta procurar por \3.
Se todos os grupos estiverem setados, indica que todos os dígitos de 1 a 4 estão presentes na string - e o quantificador {4} garante que a string tem somente 4 dígitos (e como os grupos são strings vazias, então \1\2\3\4 não interfere no tamanho da string sendo procurada; lembre-se que os grupos estão aí somente para verificar se o respectivo dígito foi encontrado). Aliás, como os grupos são strings vazias, tanto faz a ordem que eu coloco as back-references (lembre-se: elas só estão ali para verificar se o grupo foi setado).
Sim, é overkill. Sim, tem jeitos mais fáceis de verificar isso sem regex. Mas enfim, isso seria um uso para grupos de captura vazios.


301 redirect for some pages and all other pages

Question: I have two websites. Let's say siteA.com and  siteB.com.
Now I want to add 301 redirect to siteB.com.
Some of pages of siteB.com need to be redirected to some specific pages on siteA.com
All other pages of siteB.com neet to redirect to the home page of siteA.com including siteB's home page.
My final requirement is no one can access siteB after adding the redirection.
These are two wordpress sites. How can acomplish this with htaccess file or a wordpress plugin?
Comment: Do `siteA.com` and `siteB.com` point to different vHosts/servers?
Comment: Yes. Different.
Answer: Since siteA.com and siteB.com point to different vHosts/servers then you can remove all the existing directives in siteB.com/.htaccess and use the simpler mod_alias Redirect and RedirectMatch directives.
For example:
# siteB.com/.htaccess

# Specific redirects
Redirect 301 /foo https://siteA.com/another-foo
Redirect 301 /bar https://siteA.com/another-bar
Redirect 301 /baz https://siteA.com/another-baz

# Redirect everything else to homepage on siteA.com
RedirectMatch 301 ^ https://siteA.com/

Test first with 302 (temporary) redirects to avoid potential caching issues.
NB: Redirecting everything else to the homepage on the other site will likely be seen as a soft-404 by search engines and isn't particularly helpful for users. It is often preferable to serve a more descriptive 404 instead.

My final requirement is no one can access siteB after adding the redirection.

Since everything is redirected, siteB.com is effectively inaccessible.
Reference:

https://httpd.apache.org/docs/2.4/mod/mod_alias.html#redirect
https://httpd.apache.org/docs/2.4/mod/mod_alias.html#redirectmatch


How do I split a string, convert to double, and output a string again? Java! (Code not working)

Question: I am a beginner java coder on an assignment. Please don't report as too vague/duplicate etc, I really need help tailored to me as I have looked at many other answers and just dont understand whats going on!
This bit of code is where my string - e.g. 5x^3 + 2x^2 will be input

    String P = Polynomial;
    Expression poly = new Variable(P);
    Expression diffpoly = poly.derive();

Here is my code where I need the help:

public class Variable implements Expression
{
    private double coeff1, power1,newcoeff,newpow;
    private String stringpoly;

//public Variable(String[] t)
    public Variable(String p)
      {
        stringpoly = p;
      }
    public Expression derive()
      {
      String[] parts;
      parts = stringpoly.split("x");
      coeff1 = double.parseDouble(parts[0]);
      power1 = double.parseDouble(parts[1]);
      newcoeff = coeff*power1;
      newpower = power1-1;
      String newcoeffstr = Double.toString(newcoeff);
      String newpowerstr = Double.toString(newpower);
      String differentiatedterm = newcoeffstr + "x^" + newpowerstr;
      return new Variable(differentiatedterm);
      }
    public double evaluate(double a)
      {
        return stringpoly;
      }
    public String toString()
      {
        return Double.toString(stringpoly);
}
}

So my issue, is that I am getting errors saying
errors
Can anyone explain these errors for me?
Comment: And unrelated: A) dont tell people to not downvote for "too broad input" - avoid creating downvote-worthy input instead B) improve the naming in your code (by learning about java naming conventions and by using meaningful names ` a`  means **nothing**, and `newcoeffstr`  could be something `newCoefficient` )
Comment: You should remove the javascript tag.
Comment: You put `java` in your title and in your first sentence, then tag it as `javascript`. Nice.
Comment: Wrong approach in the first place: you should really learn to create a **parser** here. Assuming that you just split around `x` is way too naive. You need a *parser* that translates your expression into a **tree** of nodes. The whole point of such exercises is to add more and more features over time. Which will cost you more and more time if you stay with this naive approach. Thus: learn about parsers, and how to build them (and hint: it is not that hard)
Comment: There is a difference between `double` and `Double` in Java. `double` is a primitive type and has no method `parseDouble`. Please check for `Double.parseDouble(String s)`
Comment: Read language spec, read examples, use an IDE, use a debugger. Only then come and ask! Downvote
Answer: double is a primitive datatype in java. It does not represent an object or a class.
To call methods an object or at least a class is required.
Check the documentations for primitive types here
Check the different wrapper classes and how to use them here
You will have to use the double's wrapper class Double to be able to call the function parseDouble(...)
double parsedNumber = Double.parseDouble("1083407810329");


Error:Kotlin: [Internal Error] java.rmi.UnmarshalException

Question: So this came up... Im sitting ducks and i dunno what to do
Also there are some posted solutions but lets be real, i dont know what theyre talking about...
I was kind thinking maybe its time to really learn how to debug, but all of the tutorials i found were already based on either functioning apps or games
Please be nice. Cheers!
Error:Kotlin: [Internal Error] java.rmi.UnmarshalException: Error unmarshaling return; nested exception is:
    java.io.InvalidClassException: com.intellij.util.io.PersistentEnumeratorBase$CorruptedException; local class incompatible: stream classdesc serialVersionUID = -8686679909601592115, local class serialVersionUID = -5823904506976358318
    at java.rmi/sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:273)
    at java.rmi/sun.rmi.server.UnicastRef.invoke(UnicastRef.java:164)
    at java.rmi/java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:217)
    at java.rmi/java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:162)
    at com.sun.proxy.$Proxy12.incrementalCache_getModuleMappingData(Unknown Source)
    at org.jetbrains.kotlin.daemon.RemoteIncrementalCacheClient.getModuleMappingData(RemoteIncrementalCacheClient.kt:37)
    at org.jetbrains.kotlin.load.kotlin.incremental.IncrementalPackagePartProvider$moduleMappings$1.invoke(IncrementalPackagePartProvider.kt:36)
    at org.jetbrains.kotlin.load.kotlin.incremental.IncrementalPackagePartProvider$moduleMappings$1.invoke(IncrementalPackagePartProvider.kt:27)
    at org.jetbrains.kotlin.storage.LockBasedStorageManager$LockBasedLazyValue.invoke(LockBasedStorageManager.java:355)
    at org.jetbrains.kotlin.storage.LockBasedStorageManager$LockBasedNotNullLazyValue.invoke(LockBasedStorageManager.java:474)
    at org.jetbrains.kotlin.load.kotlin.incremental.IncrementalPackagePartProvider.findPackageParts(IncrementalPackagePartProvider.kt:44)
    at org.jetbrains.kotlin.load.java.lazy.descriptors.LazyJavaPackageFragment$binaryClasses$2.invoke(LazyJavaPackageFragment.kt:43)
    at org.jetbrains.kotlin.load.java.lazy.descriptors.LazyJavaPackageFragment$binaryClasses$2.invoke(LazyJavaPackageFragment.kt:36)
    at org.jetbrains.kotlin.storage.LockBasedStorageManager$LockBasedLazyValue.invoke(LockBasedStorageManager.java:355)
    at org.jetbrains.kotlin.storage.LockBasedStorageManager$LockBasedNotNullLazyValue.invoke(LockBasedStorageManager.java:474)
    at org.jetbrains.kotlin.storage.StorageKt.getValue(storage.kt:42)
    at org.jetbrains.kotlin.load.java.lazy.descriptors.LazyJavaPackageFragment.getBinaryClasses$descriptors_jvm(LazyJavaPackageFragment.kt)
    at org.jetbrains.kotlin.load.java.lazy.descriptors.JvmPackageScope$kotlinScopes$2.invoke(JvmPackageScope.kt:44)
    at org.jetbrains.kotlin.load.java.lazy.descriptors.JvmPackageScope$kotlinScopes$2.invoke(JvmPackageScope.kt:36)
    at org.jetbrains.kotlin.storage.LockBasedStorageManager$LockBasedLazyValue.invoke(LockBasedStorageManager.java:355)
    at org.jetbrains.kotlin.storage.LockBasedStorageManager$LockBasedNotNullLazyValue.invoke(LockBasedStorageManager.java:474)
    at org.jetbrains.kotlin.storage.StorageKt.getValue(storage.kt:42)
    at org.jetbrains.kotlin.load.java.lazy.descriptors.JvmPackageScope.getKotlinScopes(JvmPackageScope.kt)
    at org.jetbrains.kotlin.load.java.lazy.descriptors.JvmPackageScope.getContributedClassifier(JvmPackageScope.kt:55)
    at org.jetbrains.kotlin.resolve.scopes.ChainedMemberScope.getContributedClassifier(ChainedMemberScope.kt:33)
    at org.jetbrains.kotlin.resolve.scopes.AbstractScopeAdapter.getContributedClassifier(AbstractScopeAdapter.kt:44)
    at org.jetbrains.kotlin.resolve.lazy.FileScopeFactory$currentPackageScope$1.getContributedClassifier(FileScopeFactory.kt:260)
    at org.jetbrains.kotlin.resolve.scopes.ResolutionScope$DefaultImpls.getContributedClassifierIncludeDeprecated(ResolutionScope.kt:40)
    at org.jetbrains.kotlin.resolve.scopes.HierarchicalScope$DefaultImpls.getContributedClassifierIncludeDeprecated(Scopes.kt)
    at org.jetbrains.kotlin.resolve.scopes.ImportingScope$DefaultImpls.getContributedClassifierIncludeDeprecated(Scopes.kt)
    at org.jetbrains.kotlin.resolve.lazy.FileScopeFactory$currentPackageScope$1.getContributedClassifierIncludeDeprecated(FileScopeFactory.kt:253)
    at org.jetbrains.kotlin.resolve.scopes.utils.ScopeUtilsKt.findFirstClassifierWithDeprecationStatus(ScopeUtils.kt:118)
    at org.jetbrains.kotlin.resolve.QualifiedExpressionResolver.findClassifierAndReportDeprecationIfNeeded(QualifiedExpressionResolver.kt:78)
    at org.jetbrains.kotlin.resolve.QualifiedExpressionResolver.resolveDescriptorForType(QualifiedExpressionResolver.kt:102)
    at org.jetbrains.kotlin.resolve.TypeResolver.resolveDescriptorForType(TypeResolver.kt:932)
    at org.jetbrains.kotlin.resolve.TypeResolver$resolveTypeElement$1.visitUserType(TypeResolver.kt:247)
    at org.jetbrains.kotlin.psi.KtVisitorVoid.visitUserType(KtVisitorVoid.java:923)
    at org.jetbrains.kotlin.psi.KtVisitorVoid.visitUserType(KtVisitorVoid.java:21)
    at org.jetbrains.kotlin.psi.KtUserType.accept(KtUserType.java:42)
    at org.jetbrains.kotlin.psi.KtElementImplStub.accept(KtElementImplStub.java:59)
    at org.jetbrains.kotlin.resolve.TypeResolver.resolveTypeElement(TypeResolver.kt:245)
    at org.jetbrains.kotlin.resolve.TypeResolver.resolvePossiblyBareType(TypeResolver.kt:124)
    at org.jetbrains.kotlin.resolve.TypeResolver.resolveType(TypeResolver.kt:114)
    at org.jetbrains.kotlin.resolve.TypeResolver.resolveType(TypeResolver.kt:85)
    at org.jetbrains.kotlin.resolve.FunctionDescriptorResolver.resolveValueParameters(FunctionDescriptorResolver.kt:419)
    at org.jetbrains.kotlin.resolve.FunctionDescriptorResolver.createValueParameterDescriptors(FunctionDescriptorResolver.kt:301)
    at org.jetbrains.kotlin.resolve.FunctionDescriptorResolver.initializeFunctionDescriptorAndExplicitReturnType(FunctionDescriptorResolver.kt:195)
    at org.jetbrains.kotlin.resolve.FunctionDescriptorResolver.resolveFunctionDescriptor(FunctionDescriptorResolver.kt:128)
    at org.jetbrains.kotlin.resolve.FunctionDescriptorResolver.resolveFunctionDescriptor(FunctionDescriptorResolver.kt:95)
    at org.jetbrains.kotlin.resolve.lazy.descriptors.AbstractLazyMemberScope.getDeclaredFunctions(AbstractLazyMemberScope.kt:115)
    at org.jetbrains.kotlin.resolve.lazy.descriptors.AbstractLazyMemberScope.access$getDeclaredFunctions(AbstractLazyMemberScope.kt:36)
    at org.jetbrains.kotlin.resolve.lazy.descriptors.AbstractLazyMemberScope$declaredFunctionDescriptors$1.invoke(AbstractLazyMemberScope.kt:56)
    at org.jetbrains.kotlin.resolve.lazy.descriptors.AbstractLazyMemberScope$declaredFunctionDescriptors$1.invoke(AbstractLazyMemberScope.kt:36)
    at org.jetbrains.kotlin.storage.LockBasedStorageManager$MapBasedMemoizedFunction.invoke(LockBasedStorageManager.java:512)
    at org.jetbrains.kotlin.storage.LockBasedStorageManager$MapBasedMemoizedFunctionToNotNull.invoke(LockBasedStorageManager.java:587)
    at org.jetbrains.kotlin.resolve.lazy.descriptors.AbstractLazyMemberScope.doGetFunctions(AbstractLazyMemberScope.kt:96)
    at org.jetbrains.kotlin.resolve.lazy.descriptors.AbstractLazyMemberScope.access$doGetFunctions(AbstractLazyMemberScope.kt:36)
    at org.jetbrains.kotlin.resolve.lazy.descriptors.AbstractLazyMemberScope$functionDescriptors$1.invoke(AbstractLazyMemberScope.kt:49)
    at org.jetbrains.kotlin.resolve.lazy.descriptors.AbstractLazyMemberScope$functionDescriptors$1.invoke(AbstractLazyMemberScope.kt:36)
    at org.jetbrains.kotlin.storage.LockBasedStorageManager$MapBasedMemoizedFunction.invoke(LockBasedStorageManager.java:512)
    at org.jetbrains.kotlin.storage.LockBasedStorageManager$MapBasedMemoizedFunctionToNotNull.invoke(LockBasedStorageManager.java:587)
    at org.jetbrains.kotlin.resolve.lazy.descriptors.AbstractLazyMemberScope.getContributedFunctions(AbstractLazyMemberScope.kt:92)
    at org.jetbrains.kotlin.resolve.lazy.LazyDeclarationResolver$resolveToDescriptor$1.visitNamedFunction(LazyDeclarationResolver.kt:125)
    at org.jetbrains.kotlin.resolve.lazy.LazyDeclarationResolver$resolveToDescriptor$1.visitNamedFunction(LazyDeclarationResolver.kt:94)
    at org.jetbrains.kotlin.psi.KtNamedFunction.accept(KtNamedFunction.java:50)
    at org.jetbrains.kotlin.resolve.lazy.LazyDeclarationResolver.resolveToDescriptor(LazyDeclarationResolver.kt:94)
    at org.jetbrains.kotlin.resolve.lazy.LazyDeclarationResolver.resolveToDescriptor(LazyDeclarationResolver.kt:91)
    at org.jetbrains.kotlin.resolve.LazyTopDownAnalyzer.createFunctionDescriptors(LazyTopDownAnalyzer.kt:282)
    at org.jetbrains.kotlin.resolve.LazyTopDownAnalyzer.analyzeDeclarations(LazyTopDownAnalyzer.kt:204)
    at org.jetbrains.kotlin.resolve.LazyTopDownAnalyzer.analyzeDeclarations$default(LazyTopDownAnalyzer.kt:60)
    at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(TopDownAnalyzerFacadeForJVM.kt:112)
    at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration$default(TopDownAnalyzerFacadeForJVM.kt:82)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:554)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:81)
    at org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport.analyzeAndReport(AnalyzerWithCompilerReport.kt:107)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.analyze(KotlinToJVMBytecodeCompiler.kt:545)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules$cli(KotlinToJVMBytecodeCompiler.kt:176)
    at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:163)
    at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:51)
    at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:85)
    at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:43)
    at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:105)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.compile(CompileServiceImpl.kt:1479)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at java.rmi/sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:359)
    at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:200)
    at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:197)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at java.rmi/sun.rmi.transport.Transport.serviceCall(Transport.java:196)
    at java.rmi/sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:562)
    at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:796)
    at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:677)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:676)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.io.InvalidClassException: com.intellij.util.io.PersistentEnumeratorBase$CorruptedException; local class incompatible: stream classdesc serialVersionUID = -8686679909601592115, local class serialVersionUID = -5823904506976358318
    at java.base/java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:689)
    at java.base/java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1958)
    at java.base/java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1827)
    at java.base/java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2115)
    at java.base/java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1646)
    at java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:464)
    at java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:422)
    at java.rmi/sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:270)
    ... 99 more

What was i writing you ask? Well im new so i was learning to code, so just basic stuff
fun main(args: Array<String>) {
    remainingResources()
}

fun remainingResources() {
    var waterMl = 400
    var milkMl = 540
    var coffeeGrams = 120
    var cupsRemaining = 9
    var moneyRemaining = 550
    waterMl -= 200
    milkMl -= 100
    coffeeGrams -= 10
    cupsRemaining -= 1
    moneyRemaining += 5
    outputRemainingResource(waterMl, milkMl, coffeeGrams, cupsRemaining, moneyRemaining)
}
fun outputRemainingResource(printWater: Int, printMilk: Int, printCoffee: Int, printCups: Int, printMoney: Int) {
    println("$printWater of water\n" +
            "$printMilk of milk\n" +
            "$printCoffee of coffee beans\n" +
            "$printCups of disposable cups\n" +
            "$printMoney of money")
}

Comment: ps. Im desperate
Comment: how have you created intellij project? is it a gradle project? how are you executing your main method?
Comment: Somehow I went over to this file which shows

`fun main(args: Array) {
    val values = listOf(3, 2, 5)
    values.forEach {
        var line: String = Integer.toBinaryString(it)
                .padStart(3, '0')
        line = line.replace("1", "X").replace("0", "O")
    }
}`
Comment: and i just added } to the end -_- TBH tho, i dont know how that happened
Comment: This looks like https://youtrack.jetbrains.com/issue/KT-38906. Does rebuild help?
Answer: Its missing a curly brace } at the end


Dúvida código JS

Question: Não consigo fazer mostrar o total de preço no seu respectivo campo.

let acum = 0
document.querySelectorAll("[td]").forEach(elemento => {
    let valorComponente = () => elemento.textContent
    let retiraVirgula = () => valorComponente.replace(",", ".")
    let conversao = () => parseFloat(retiraVirgula)
    acum = acum + retiraVirgula
    document.querySelector("[tdTotal]").textContent = acum
})
table {
    border-collapse: none;
}

td {
    padding: 10px;
}

thead {
    font-weight: bold;
    background-color: rgb(27, 27, 27);
    color: white;
}

tbody tr:hover {
    background-color: rgb(155, 155, 155);
    color: white;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Teste tabela</title>

Registro Animais

                Nome
                Raça
                Peso
                Latido
                Preço

                Billy
                Poodle
                15kg
                Fino
                400,00

                Joke
                pastor alemao
                40kg
                grosso
                2000,00

                Jow
                Poodle
                22kg
                Fino
                1400,00

                Total

Answer: Isso aqui está errado:
valorComponente = () => elemento.textContent

Você sabe o que é essa sintaxe (() => etc...)? Você está criando uma arrow function, ou seja, valorComponente é uma função que retorna o valor de elemento.textContent. Mas o que você quer não é uma função, e sim o próprio valor. Então mude isso para:
valorComponente = elemento.textContent

O mesmo vale para as demais variáveis, em todas elas você criou funções em vez de pegar o valor.
Além disso, no acumulador você deve somar o valor numérico (ou seja, o resultado de parseFloat), e não a string retiraVirgula:
acum = acum + conversao;

Ou seja:

let acum = 0;
document.querySelectorAll("[td]").forEach(elemento => {
    let valorComponente = elemento.textContent;
    let retiraVirgula = valorComponente.replace(",", ".");
    let conversao = parseFloat(retiraVirgula);
    acum = acum + conversao;
    document.querySelector("[tdTotal]").textContent = acum.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });
})
table {
    border-collapse: none;
}

td {
    padding: 10px;
}

thead {
    font-weight: bold;
    background-color: rgb(27, 27, 27);
    color: white;
}

tbody tr:hover {
    background-color: rgb(155, 155, 155);
    color: white;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Teste tabela</title>

Registro Animais

                Nome
                Raça
                Peso
                Latido
                Preço

                Billy
                Poodle
                15kg
                Fino
                400,00

                Joke
                pastor alemao
                40kg
                grosso
                2000,00

                Jow
                Poodle
                22kg
                Fino
                1400,00

                Total

Também coloquei ponto-e-vírgula no final das linhas. Pode parecer "frescura", e sei que o JavaScript "aceita" o código sem ponto e vírgula e "funciona", mas isso evita algumas situações bizarras que podem ocorrer se você não usá-los, como essa e essa (veja mais sobre isso aqui).
Comment: @AlessanderJúnio Se a resposta resolveu o seu problema, vc pode aceitá-la, [**veja aqui**](https://pt.meta.stackoverflow.com/q/1078/112052) como e porque fazê-lo. Não é obrigatório, mas é uma boa prática do site, para indicar a futuros visitantes que aquilo resolveu o problema
Comment: Obrigado pela resposta, me ajudou a entender o erro.

Dúvida código JS


Preciso alterar somente a metade dos registros de uma tabela MySQL

Question: Fiz esta procedure no MySQL para alterar um registro somente da metade da tabela mas ele produz um erro inexplicável:
Ao que parece a encrenca esta no LIMIT que se recusa a aceitar uma variável.
No SQLServer eu usava o TOP (50) PERCENT resolvia o problema, mas no MySQL não encontro solução. Alguém pode me ajudar?
BEGIN
DECLARE CodigoNovaLista INT;
DECLARE QuantidadeTotal INT;
DECLARE QuantidadeListaNova INT;
DECLARE QuantidadeListaAtual INT;

DECLARE EXIT HANDLER FOR SQLEXCEPTION ROLLBACK;
DECLARE EXIT HANDLER FOR SQLWARNING ROLLBACK;

START TRANSACTION;
SELECT QuantidadeTotal = TotalEmails FROM tabelalistas WHERE IDLista = @IDListaAtual;

SET QuantidadeListaAtual =  QuantidadeTotal /2;
SET QuantidadeListaNova = QuantidadeTotal - QuantidadeListaAtual;

INSERT INTO tabelalistas (Nome, IDCliente) VALUES(@NovoNome, @IDCliente);
SELECT CodigoNovaLista = LAST_INSERT_ID();

UPDATE tabelaemailsimportados SET IDLista=CodigoNovaLista WHERE IDLista = @IDListaAtual LIMIT QuantidadeListaNova;

UPDATE tabelalistas SET TotalEmails=QuantidadeListaAtual WHERE IDLista = @IDListaAtual ;
UPDATE tabelalistas SET TotalEmails=QuantidadeListaNova WHERE IDLista = CodigoNovaLista ;

COMMIT;
END

Comment: parece muito simples mas não entendi o motivo de "alterar somente a metade dos registros de uma tabela". No código acima tem um trecho com INSERT e depois vem uns updates estranhos que parece trocar o id lista com o novo.. Mas não entendi o sentido disso.. aliás, não entendi nada. hehehe
Comment: Pode criar um [SQL Fiddle](http://sqlfiddle.com/) demonstrando o problema? Não há nada errado em usar `LIMIT` no `UPDATE` (veja [o manual](http://dev.mysql.com/doc/refman/5.7/en/update.html)). Deve ser algum problema de sintaxe, porem fica difícil de testar sem um exemplo.
Comment: Outra coisa, se alterar aproximadamente 50% dos registros e em qualquer ordem resolve o problema, existe [um método mais fácil](http://stackoverflow.com/questions/11087059/mysql-how-do-i-update-50-of-the-rows-randomly-selected) `UPDATE tabelaemailsimportados SET IDLista=CodigoNovaLista WHERE IDLista = @IDListaAtual AND RAND() < 0.5`.
Answer: Uma alternativa é montar a query numa variável texto e executá-la de forma dinâmica com o comando EXECUTE.
Exemplo:
EXECUTE 'UPDATE tabelaemailsimportados ' ||
    ' SET IDLista=CodigoNovaLista WHERE IDLista = ' ||
    to_char(@IDListaAtual, '9') ||
    ' LIMIT ' || to_char(@QuantidadeListaNova, '9')


jQuery - change the CSS of the menu item's path in the dynamically created menu

Question: I'm using that jQuery Vertical Menu Library www.dynamicdrive.com/dynamicindex1/ddsmoothmenu.htm I want to accomplish the selection of the selected path. Let's say that I go through that menu (in the demo on that site above) by the path:
Folder 2 > Folder 2.1 > Folder 3.1.1 > SubItem 184.108.40.206

When I click on the SubItem 22.214.171.124 I want that the all previous items (from the path above) changes their backgrounds. The code below selects only the top-most item. How to fix that ?
    $('#nav > li').click(function () {
        $(this).children('a').css('background-color', 'red');
        $(this).parents('ul').each(function () { $(this).prev('a').css('background-color', 'red'); });
    });

. In that scenario, my code fails.
Answer: The way the menu seems to be organized, the click event will bubble up from child li to parent li, so you just need to bind the click event to all menu items and set the background for the current element:
$('#nav li').click(function () {
    $(this).children('a').css('background-color', 'red');
});

You still might like to unset the red background when you click on another menu item
Comment: Weird. I tested it on the jQuery Vertical Menu Library link you sent, with a debugger (like Firebug): (`$('#smoothmenu2 li').click(function() {$(this).children('a').css('background-color', 'red');})`) and it worked perfectly. Try it and yourself. If you can't see what's wrong, try to create a fiddle that reproduces the problem
Comment: According to the unsetting the Red background: http://stackoverflow.com/questions/8884987/jquery-strange-function-behaviour
Answer: Solve attempt #1:
    $('#nav a').click(function () {
        $(this).css('background-color', 'red');
        $('a.selected').css('background-color', 'red');
    });

Comment: won't work, because of the way the menu's structured: `li > a`, `li > ul`, `ul` > `li`, the event bubbles from the `a` clicked to `li` to `ul` to `li` etc.


Quasi-random sequence on the unit $2$-sphere for Monte-Carlo based method

Question: Please forgive my possible misuse of the appropriate definitions. I'm looking for a quasi-random sequence of directions in the unit $2$-sphere, to be used in a Monte-Carlo method to calculate an integral over the entire $4 \pi$ solid angle.
I'm currently using a Monte-Carlo approach for the calculation of global illumination for a 3d application, using pseudo-random numbers from a standard software package. The thing is that the convergence is too slow. I've read about it in Wikipedia, and found out that by using quasi-random sequences (like the Sobel sequence) I could improve the convergence speed from $\frac{1}{\sqrt{N}}$ to $\frac{1}{N}$. Is this correct?
NOTE: Please if there is some typing error in the math, I'll appreciate an editor's help.
Answer: Wouldn't a standard quasi-random sequence on a rectangle (eg Sobol) followed by a area-preserving mapping from the rectangle to the sphere (eg Gall-Peters) do the trick?
Surely, we don't have -a priori- guarantees that a good quasi-random sequence will preserve its good properties after the mapping, but it sounds reasonable to expect so.
Another recipe (again, which only sounds reasonable) would be to generate generate the quasi-random sequence in 3D, inside the enclosing cube; if the sample falls outside the sphere, discard it and go for the next; elsewhere, project it over the sphere surface.
Comment: I'll go with the second choice. I already did it once for pseudo-random vectors in the unit sphere. Hope it works. Thanks!


howler.js not working in Android 4.4.4 native browser

Question: I am using howler.js for playing audio in one of my project, I am able to play audio file using howler.js in android native browser for first time. After page refresh audio does not play.
But works fine in google chrome after page refresh also. Any one else faced this issue ?
Answer: Try to refer t this answer, it solves your problem in a different way:
Media Plugin offered by Cordova
Comment: Thanks for the response. I am trying to play absolute mp3 file on page load. Cordova allows absolute mp3 path ?
Comment: yes it allows so, but you have to specify the URI type, for example : http:// or file://
Answer: Below is the howler.js script I am using:
customSound = new Howl({
                        urls: [ urlSound ],
                        format: 'mp3',
                        buffer: false,
                        autoplay: true
                    });


Qual a diferença entre usar uma div e React.Fragment?

Question: Estou estudando React mais a fundo e em um dos cursos que estou acompanhando é citado o uso do <React.Fragment> para renderizar vários elementos de uma vez.
Normalmente nos meus componentes eu utilizo uma
:

Olá mundo

Até logo

Mas vi que também é possível com:
<React.Fragment>

Olá mundo

Até logo

</React.Fragment>

Quais as vantagens de se utilizar o <React.Fragment> em comparação com uma
?
Em quais casos é apropriado utilizar a
 e em quais casos devo utilizar o Fragment?
Comment: Você também pode usar `<>` e `` no lugar da tag ``. O efeito é o mesmo, mas fica mais fácil de ver o código e perceber que aquele elemento não será renderizado.
Answer: Como você deve saber, o JSX é um mero açúcar sintático. Não faz parte da especificação do ECMAScript. Assim, quando compilado, o JSX se torna algo mais ou menos assim:
React.createElement(component, props, ...children);

Portanto, agora entendemos a necessidade de só se retornar um elemento React por componente. Isto é válido, já que retorna somente um elemento:
function MyComponent() {
  return (
    <React.Fragment>
      Foo
      Bar
    </React.Fragment>
  );
}

Contudo, este outro exemplo já não é válido, já que um componente não pode retornar mais de dois elementos:
function MyComponent() {
  // ❗ Errado!
  return (
    Foo
    Bar
  );
}

Desse modo, se você precisar retornar mais de dois elementos em um mesmo nível, o React obriga-o a envolvê-los em um único componente. Anteriormente à introdução dos fragmentos, você deveria utilizar uma tag do HTML ou algum outro componente genérico, o que nem sempre era ideal, já que seria inserido mais um elemento HTML no DOM, podendo inclusive afetar a acessibilidade ou dificultar a componentização tão importante para o React.
A documentação sobre fragmentos explica essas motivações com um pouco mais de aprofundamento.

Quais as vantagens de se utilizar o <React.Fragment> em comparação com uma
?

Conforme colocado acima, a principal vantagem de se utilizar um fragmento é o fato de você poder retornar múltiplos elementos a um mesmo nível sem necessariamente ter que envolvê-los em algum componente que irá renderizar algum nó no DOM.
Por exemplo, no trecho abaixo, uma
 será renderizada:

function MyComponent() {
  return (

      Foo
      Bar

  );
}

ReactDOM.render(<MyComponent />, document.body);

Mas neste outro exemplo, nenhuma outra tag além de strong e span serão inseridas no DOM, já que um fragmento foi utilizado:

function MyComponent() {
  return (
    <React.Fragment>
      Foo
      Bar
    </React.Fragment>
  );
}

ReactDOM.render(<MyComponent />, document.body);

Em quais casos é apropriado utilizar a
 e em quais casos devo utilizar o Fragment?

Utilize a div — ou qualquer outro componente que irá renderizar algo na árvore do DOM — quando você quiser que isso aconteça. Se você não quiser que o componente que "envolve" seja renderizado no DOM, utilize um fragmento.


Is it possible to estimate the standard deviation of a normal distribution if I only have the mean of the population?

Question: I'm not a math or statistics expert and only have a self-taught basic understanding of these things. I'm working on a problem where I know the mean of the population and I want to estimate the standard deviation. This assumes a normal distribution of the population. Is this possible?
For example, if the mean if 32, with possible values between 0 and 100, can I calculate what the standard deviation is with just this information?
Thank you for your help!
Comment: Is the mean just a given? or was it calculated from data? If you have access to the data, estimating the shape of the distribution is just a few steps of R codes away.
Comment: It is calculated from data, but I don't have immediate access to the data. So the real world example of this is if an organization of 100 sales reps has a win rate of 32%. My client can tell me that their win rate is 32%. What I want to be able to do is estimate the percentage of their reps that have win rates in different ranges using standard deviations (e.g. so we can focus on who needs help, who are our model sales reps, etc.).

Eventually, I'll have access to the individual data and can do the calculations with all of the data, but it would be great if I could estimate it first.
Comment: No, you can't get the standard deviation from the mean unless it's a special case such as Poisson distribution.
Answer: Normal distributions with very different standard deviation can have the same mean, so knowing the mean doesn't tell you which standard deviation you had. Indeed for samples from the normal distribution, the sample mean and sample standard deviation are independent, so the mean doesn't tell you anything about the standard deviation.

if the mean if 32, with possible values between 0 and 100

Then you cannot have a normal distribution (normal distributions are necessarily unbounded). On the other hand, the mean and the two bounds together do impose an upper limit on the standard deviation, but it's pretty weak.
Comment: That's a great point and should have been obvious to me. It is indeed a Skewed Distribution curve. With it being a skewed distribution, is there any way to estimate the standard deviation? Or do I need the individual values to be able to calculate the standard deviation?
Comment: 1. While skewness would also indicate non-normality, it could well have been perfectly symmetric yet we would still know - for certain - that the distribution from which your sample was drawn could not actually be a normal distribution.  2. Saying that it's skewed doesn't really help us pin down the standard deviation. ... but the fact that *you were able to go back and check that it was skewed* clearly indicates you have an additional source of information than the mean.  ... ctd
Comment: ctd... Please include *all* available information about the numbers and what they measure, including any graphical displays if possible, *in the text of your question* (via an edit) and if you would be so kind, also comment here (and under the other answer) to indicate any substantive changes. You should also include what you're ultimately trying to achieve (why do you need to know the standard deviation?) ...  @Zig
Answer: The later clarification, in a comment to the question, that these are "win rates" ranging from 0% to 100% makes this a bit more feasible than the earlier answer from @Glen_b posted before that information was available.
You might think of this problem like flipping a biased coin, with a probability p of showing "heads" (a "win"; p = 0.32 for your example). Flipping this coin N times (e.g., N sales attempts) is a binomial sampling problem in terms of the number of "wins." This can look like a normal distribution, but as values can only be non-negative integers it can't strictly be normal.
As documented on the linked Wikipedia page and on this Cross Validated page, the variance of the estimate of p among repeated trials with N flips per trial is: $p(1-p)/N$. So to determine whether a particular sales rep is a "model" or "needs help," you also have to take into account the number of sales attempts.
Comment: OP's case seem to be different from binomial distribution, which you suggest. Each sales rep has a different winning rate. And he wants the distribution of salesmen by winning rate. You're suggesting that all salesmen have the same winning rate, but they play and either win or lose, then your distribution is for the overall winning rate, not idnividual
Comment: My sense is that the OP wants to determine whether individual sales reps have significantly different win rates from an overall company average of 32%, for which a binomial model would be OK. I await further clarification and follow-up from the OP, should he desire.


Como mostra a primeira imagem do post - Wordpress

Question: Estou editando o tema para wordpress http://www.arrastheme.com/  porem surgiu um problema.
Minhas imagens estão hospedadas no picasa e linkadas no post.
As imagens não aparecem na home nem nos arquivos, apenas quando entra dentro do post que é possivel velas.
Tentei atraves desses 2 tutoriais fazer com que a imagem apareça, porem sem sucesso
Tutoriais:
http://www.wprecipes.com/how-to-get-the-first-image-from-the-post-and-display-it
http://css-tricks.com/snippets/wordpress/get-the-first-image-from-a-post/
O script relacionado as imagens é esse:
<?php

/**
 * Containers for storing thumbnail types and its default sizes.
 * @since 1.4.4
 */
$arras_image_sizes = array();

function arras_add_default_thumbnails() {

    $single_thumbs = arras_get_single_thumbs_size();
    arras_add_image_size( 'single-thumb', __('Single Post Thumbnail', 'arras'), $single_thumbs[0], $single_thumbs[1] );
    arras_add_image_size( 'sidebar-thumb', __('Sidebar Widgets', 'arras'), 36, 36);

    do_action('arras_add_default_thumbnails');
}

/**
 * Function to add image size into both theme system.
 * @since 1.4.4
 */
function arras_add_image_size($id, $name, $default_width, $default_height) {
    global $arras_image_sizes;

    $arras_custom_image_sizes = arras_get_option('custom_thumbs');

    // Check from options if a custom width and height has been specified, else use defaults
    if (isset($arras_custom_image_sizes[$id])) {
        $width = $arras_custom_image_sizes[$id]['w'];
        $height = $arras_custom_image_sizes[$id]['h'];
    } else {
        $width = $default_width;
        $height = $default_height;
    }

    $arras_image_sizes[$id] = array(
        'name'  => $name,
        'w'     => $width,
        'h'     => $height,
        'dw'    => $default_width,
        'dh'    => $default_height
    );

    add_image_size($id, $width, $height, true);
}

/**
 * Function to remove image size into both theme system.
 * @since 1.4.4
 */
function arras_remove_image_size($id) {
    global $arras_image_sizes, $_wp_additional_image_sizes;

    unset($arras_images_sizes[$id]);
    unset($_wp_additional_image_sizes[$id]);
}

/**
 * Function to get image size's name, width and height, default or custom.
 * @since 1.4.4
 */
function arras_get_image_size($id) {
    global $arras_image_sizes;

    return (isset($arras_image_sizes[$id])) ? $arras_image_sizes[$id] : false;
}

/**
 * Helper function to grab and display thumbnail from specified post
 * @since 1.4.0
 */
function arras_get_thumbnail($size = 'thumbnail', $id = NULL) {
    global $post, $arras_image_sizes;

    $empty_thumbnail = '';

    if ($post) $id = $post->ID;

    // get post thumbnail (WordPress 2.9)
    if (function_exists('has_post_thumbnail')) {
        if (has_post_thumbnail($id)) {
            return get_the_post_thumbnail( $id, $size, array(
                'alt'   => get_the_excerpt(),
                'title' => get_the_title()
            ) );
        } else {
            // Could it be an attachment?
            if ($post->post_type == 'attachment') {
                return wp_get_attachment_image( $id, $size, false, array(
                    'alt'   => get_the_excerpt(),
                    'title' => get_the_title()
                ) );
            }
            // Use first thumbnail if auto thumbs is enabled.
            if (arras_get_option('auto_thumbs')) {
                $img_id = arras_get_first_post_image_id();
                if (!$img_id) return $empty_thumbnail;

                return wp_get_attachment_image($img_id, $size, false, array(
                    'alt'   => get_the_excerpt(),
                    'title' => get_the_title()
                ) );
            }
        }
    }

    // go back to legacy (phpThumb or timThumb)
    $thumbnail = get_post_meta($id, ARRAS_POST_THUMBNAIL, true);

    $w = $arras_image_sizes[$size]['w'];
    $h = $arras_image_sizes[$size]['h'];

    if ($thumbnail != '') {
        if (!$arras_image_sizes[$size]) return false;
        return '';
    } else if (arras_get_option('auto_thumbs')) {
        if (!$arras_image_sizes[$size]) return false;

        $img_id = arras_get_first_post_image_id();
        if (!$img_id) return $empty_thumbnail;

        $image = wp_get_attachment_image_src($img_id, 'full', false);
        if ($image) {
            list($src, $width, $height) = $image;
            return '';
        }
    }

    return $empty_thumbnail;
}

/**
 * Function to convert image URLs into WPMU compatible URLs for Timthumb
 * @since 1.5.1
 */
function arras_timthumb_wpmu_image_src($url) {
    global $blog_id, $current_site;

    $uploads = wp_upload_dir();

    if ( isset($blog_id) && $blog_id > 0 ) {
        $split = explode( '/files/', $url);
        if ( isset($split[1]) ) {
            $url = 'http://' . $current_site->domain . $current_site->path . 'wp-content/blogs.dir/' . $blog_id . '/files/' . $split[1];
        }
    }

    return $url;
}

/**
 * Function to retrieve the first image ID from post.
 * @since 1.5.0
 */
function arras_get_first_post_image_id($id = NULL) {
    global $post;
    if (!$id) $id = $post->ID;

    $attachments = get_children('post_parent=' . $id . '&post_type=attachment&post_mime_type=image');
    if (!$attachments) return false;

    $keys = array_reverse(array_keys($attachments));
    return $keys[0];
}

function arras_get_single_thumbs_size() {
    $layout = arras_get_option('layout');

    if ( strpos($layout, '1c') !== false ) {
        $size = array(930, 375);
    } else if ( strpos($layout, '3c') !== false ) {
        $size = array(465, 190);
    } else {
        $size = array(620, 300);
    }

    return apply_filters('arras_content_width', $size);
}

/* End of file thumbnails.php */
/* Location: ./library/thumbnails.php */

Answer: O sistema de slider do Arras, assim como qualquer featured-image do Wordpress, funciona com imagens locais.
Ou seja, você deve fazer upload das imagens de destaque dentro do seu wp, usando o menu de Mídia.
Aqui tem um artigo que explica bem como fazer isso e como configurar seu theme com os thumbnails.


Constructing a vector space of dimension $2$ for a cyclotomic field

Question: Suppose that $z_n$ is a primitive $n$th root of unity. I want to find some subfield $F$ of $\mathbb{Q}(z_n)$ with $F \subseteq \mathbb{R}$ satisfying $\mbox{dim}_F \mathbb \,{\mathbb{Q}(z_n)} = 2$ (i.e., the vector space of $\mathbb{Q}(z_n)$ over $F$ has dimension $2$). Is there any way I can go about doing this without going too deep into Galois theory?
Answer: Hint: try $F=\mathbb{Q}(z_n+\overline{z_n})$.
Comment: What does $\overline{z_n}$ denote?
Comment: The complex conjugate of $z_n$.