When using a Neural Network to classify more than two classes, is it better to have multiple output nodes (one for each class) or one output node?

Question: Currently, I am using a neural network to classify data into one of three groups (a logistic activation function is used on all but the output nodes). I can train the neural network in two ways:
1) For each observation $X_{i}$ I can have one output variable $O_{i}$ that can take three values: $1,2,$ or $3$.
Or,
2) For each observation $X_{i}$ I can have three output variables $O_{i1},O_{i2}$, and $O_{i3}$ that would take on the values $0$ or $1$ based on what the class label for that observation is. So for example, if observation $i$ belongs to class 2, $O_{i2}$ would be $1$, whereas $O_{i1}$ and $O_{i3}$ would be $0$.
Are the above two approaches equivalent? Is one better than the other? Are there any theoretical reasons to believe one should produce better results than the other?
Answer: Usually when you design a learning process with neural nets, you have to be aware of any structure you induce. This induced structure might be learned by net, since neural nets are very capable of incorporating patterns. The easiest way to induce a desired or undesired structure (learning bias) in the learning process is to manipulate accordingly the inputs and outputs.
Without further knowledge on your specific problem I suspect that the first option will induce a ordering relation between the outputs. What it means is that the neural net might probably "consider" that the distance between $O_1$ and $O_3$, than the distance between $O_1$ and $O_2$. If there is such an ordering, than you can proceed with this way. Anyway, it might be possible to have to scale the outputs as well, so the final learned values to not be $1, 2, 3$, but smaller values centered at $0$.
However, usually there are no such ordering relations between classes, so the second option "breaks" this possible induced structure. Each option has the same chances to be learned as any other. Going further with this rationale, I believe you have to also consider using softmax node outputs, which have the nice feature that the obtained output values comes from a probability function (the values are in $[0, 1]$ and the sum of the outputs is $1 = \sum_{j=1}^{3}O_{ij}$). For softmax nodes you can see how they are working on wikipedia
Comment: That makes sense; approach one would work for ordinal data whereas approach two would be more suited for nominal data. Thanks for the insight! (Would upvote but not enough karma).


Slideshow of images which are not a field of node

Question: I have used FlexSlider module to create an image slider. It works perfectly. I create a content type, with image field, create several nodes of that type, and finally I create a View of that content type. In the Format of the View, I can choose the FlexSlider style, and I am done.
What I want is to use several large images, which are many (3.000) images, and instead of creating 3.000 nodes, I would like to have the images externally, in a folder and referenced by a table of its own, and do a Flexslider using the View that already have, with mimimum modifications. Is it possible to get the same effect but without using nodes? If I load the images into nodes using Feeds, it takes ages, and I have some problems, so decided to go with the images outside of the nodes. Maybe a SQL alter could do it?
Answer: I have solved the problem by using Lightbox2 module, which allows to render a Slideshow with no need of a View or configuring the images as fields of nodes.
You can see the solution with some code, in this other question and answer of mine. So this is a solution for someone looking for:

A gallery of many many images.
Slideshow with thumbnail.
Thumbnail + Medium image (detail of product, for example), with the Slideshow launched from the Medium image, no the thumbnails.

How to configure a Slideshow with thumbnails in modal window


the MISSISSIPPI problem - 5 letter word and 6 letter word with constraints

Question: 1) Number of ways of selecting 5 letters such that 3 are alike of one type and 2 are alike of another type.
There are only 2 ways of selecting 3 letters of the same type i.e., III or SSS. Now with each of these 2, we can create 2 combinations of either 2S or 2P in the former and 2I or 2P in the latter case. This way, I know there are only 4 possibilities. But what if the number of S's and such repetitions are huge in number ? I want to know a formula (with an explanation please!).
2) My second problem is as follows: This is also simple but I need a formula:
Number of ways of selecting 6 letters out of the word MISSISSIPPI with exactly 2 different 'like pairs'.
I can list out all the pairs:
(SSSS   II),
 (SSS    III),
 (SSSS   PP),
 (IIII   SS),
 (IIII   PP),
 (III    SSS)  (neglect this because this is already done)
 (II     SSSS) (already there)
So, in all 5 such possibilities are there. Am I correct ? Please correct me if I am wrong here itself! :-) Ok, even if this is correct, how to arrive at this with a formula i.e., mathematically ?
Please help!
Thanks!!
kris
Comment: What do you mean by "like pair"? Is it SS a like pair II a like pair so in your list first element is (SSSS II) , in which SS , II are exactly two different like pairs. If am getting you in this way then your answer is right.
Answer:
Number of ways of selecting $5$ letters out of the word MISSISSIPPI such that $3$ are alike of one type and $2$ are alike of another type.

There are two ways of choosing the letter that appears three times since it must be an I or an S.  Once it has been selected, there are two ways of choosing the letter that appears twice since it must be an I, P, or S and cannot be the letter that has been selected to appear three times.  Once the two letters that appear in the word have been selected, the word is completely determined by selecting which three of the five places are filled with the letter that appears three times.
$$2 \cdot 2 \cdot \binom{5}{3}$$

Number of ways of selecting $6$ letters out of the word MISSISSIPPI with exactly $2$ different 'like pairs.'

There are three letters which could appear twice, namely I, S, or P.  We select two of those three to appear twice.  Whichever of those three letters that is not selected to appear twice appears once, as does M.  Thus, if we are looking for a six letter multiset that contains exactly two like pairs, there are $\binom{3}{2} = 3$.  They are
$$\{2 \cdot I, 1 \cdot M, 2 \cdot P, 1 \cdot S\}, \{2 \cdot I, 1 \cdot M, 1 \cdot P, 2 \cdot S\}, \{1 \cdot I, 1 \cdot M, 2 \cdot P, 2 \cdot S\}$$
If you meant how many words of length six contain exactly two like pairs, after we choose the two repeated letters, we must select two of the six places for the repeated letter that appears first alphabetically, two of the remaining four places for the other repeated letter, one of the two places for whichever of the two singletons appears first alphabetically, and fill the remaining spot with the remaining singleton.
$$\binom{3}{2}\binom{6}{2}\binom{4}{2}\binom{2}{1}\binom{1}{1}$$
Comment: Dear Taussig, Thanks for your detailed answer. It explains all the questions I had in my mind and more! In fact, I had only the first option you have addressed in 2nd question in mind when I asked the questions. Thanks!!


A basic question about 0 the one point compactification of $\mathbb R$

Question: It is possible to turn the real line into a compact space by adding a single "point at infinity" which we will denote by $\infty$. The resulting compactification is homeomorphic to a circle in the plane.
Let $x\neq0$ be a "finite" real number. Are the expressions $x\cdot\infty$ and $x/0$ are well defined in $\mathbb R\cup\{\infty\}$? In that case, can we say that $x/0=\infty$ and $x\cdot\infty=\infty$ ?
Answer: One has to pay attention when formulating a question like this: The one-point compactification is a purely topological procedure: $\mathbb{R} \cup \{\infty \}$ is a topological space and it does not come with additional structure. You're asking if one can endow the space with additional structure that is more-or-less sensible (whatever that means; but it particular it should extend the usual structure on the field $\mathbb{R}$).
Indeed, there are way of doing so and here is one typical such extension that I just copied from Wikipedia since it is too long. It plays a relevant role in measure theory.

In particular, your hopes $x/0 = \infty$ and $x \cdot \infty$ are answered affirmatively in case $x \neq 0$. The expressions $0/0$ and $0 \cdot \infty$ remain undefined.
Comment: These are also the only definitions you can make if you want the multiplication-by-x or addition-of-x maps to be continuous on the whole of the one-point compactification.


How do I create a front page?

Question: I am developing new website in D7 and I have installed bootstrap theme on the of it.
So, now I want to create home page/front page for my website and for that I have created a basic page, but I am not able to add CSS and JS in that basic page.
What approach should I use to create a front page in Drupal 7?
Comment: https://www.drupal.org/node/265172 check this link
Answer: There are two option:

Use a different template for the front page you have to name your template page--front.tpl.php and clear the theme registry. Please check Theming Guide for more details.
There's also the Front Page module: http://drupal.org/project/front
Answer: Depends on what your needs are.
One approach is to go with panels. It gives you a nice UI for including blocks, nodes and other pieces of content.

The Panels module allows a site administrator to create customized
  layouts for multiple uses. At its core it is a drag and drop content
  manager that lets you visually design a layout and place content
  within that layout. Integration with other systems allows you to
  create nodes that use this, landing pages that use this, and even
  override system pages such as taxonomy and the node page so that you
  can customize the layout of your site with very fine grained
  permissions.

The second approach, which has become my preferable, is to create your frontpage as a node and add the necessary views or blocks on it.
Regardless of your approach, if you are in need to add js and css  files in the frontpage you can add the following in you template.php file(source):
function yourtheme_preprocess_page(&$vars) {
  if(drupal_is_front_page()) {
    drupal_add_js(drupal_get_path('theme', 'yourtheme') . '/js/your-front-script.js');
    drupal_add_css(drupal_get_path('module', 'example') . '/example.css');
  }
}

Answer: If you look at the frontpage's source code you'll find something like this:

so you may want to create a css rule that applies to .front class.
Answer: create page--front.tpl.php template file inside your theme tpl folder.
It will work

How do I create a front page?


Give a connected graph whose automorphism group has size 3

Question: Find a connected graph whose automorphism group has size 3.
Note: I know such graph must be non-simple.
Comment: An oriented triangle?
Comment: If you're allowed directed graphs, yes.
Answer: Every group is isomorphic to the automorphism group of a simple graph (see Frucht's Theorem), including the cyclic group of order $3$.
To construct a simple graph $G$ whose automorphism group has size $3$, take $K_3$ and, for each edge, replace it by a copy of a graph $G$ with no non-trivial automorphisms ($F$ say, which could be the Frucht graph).  [This operation needs to be performed in the same way for each edge.]
Any automorphism of $G$ must map a copy of $F$ to another copy of $F$, which, since $F$ has no non-trivial automorphisms, can be achieved in precisely $3$ ways.  (Any other automorphisms would give rise to a non-trivial automorphism of $F$.)
Here's a drawing:

(thanks to Mathematica)
Comment: What does "replace an edge by a copy of F" mean? Does this operation give a resultant graph with 3 mutually adjacent F-graphs such that each two share a common vertex?
Comment: I think it has 6 automorphisms instead of 3?!
Comment: got it, thanks!
Comment: There are some exceptions, if the graph G is a tree you must be very careful of which vertices you use to be the end points of the new "edge" and for some trees it will be impossible.
Answer: Here is my favorite, it shows that you do not need an asymmetric graph as the edge.   ,


View: Recent posts all users

Question: I'm working on drupal 7 with Views 3.8. I'm trying to make a view with one post(most recent one) of all users of my site. I found out via this forum I can make a view based on all users. I then add a relationship called User: Representative node. And I choose to sort on [post date].
Now this should work right? But the view doesn't show the most recent post but it shows the oldest post. I tried change descending to ascending or change the sorting to [NID] or [post updated] but nothing seems to work. What can I do?
If it's usefull here's my view:
$view = new view();
$view->name = 'recent';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'users';
$view->human_name = 'Recent';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Recent';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['access']['perm'] = 'access user profiles';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: User: Representative node */
$handler->display->display_options['relationships']['uid_representative']['id'] = 'uid_representative';
$handler->display->display_options['relationships']['uid_representative']['table'] = 'users';
$handler->display->display_options['relationships']['uid_representative']['field'] = 'uid_representative';
$handler->display->display_options['relationships']['uid_representative']['subquery_sort'] = 'node.created';
$handler->display->display_options['relationships']['uid_representative']['subquery_view'] = '';
$handler->display->display_options['relationships']['uid_representative']['subquery_namespace'] = '';
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['relationship'] = 'uid_representative';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['title']['link_to_node'] = FALSE;
/* Sort criterion: User: Created date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'users';
$handler->display->display_options['sorts']['created']['field'] = 'created';
/* Filter criterion: User: Active */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'users';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = '1';
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'recent';
$translatables['recent'] = array(
  t('Master'),
  t('Recent'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('Items per page'),
  t('- All -'),
  t('Offset'),
  t('« first'),
  t('‹ previous'),
  t('next ›'),
  t('last »'),
  t('Representative node'),
  t('Page'),
);

Answer: In your view,

To sort based on Posted Date of content, then You should adding a Sort Criteria: Content: Post date as Descending
To sort based on Updated Date of content, then You should adding a Sort Criteria: Content: Update date as Descending
Comment: Thanks for answering, but as said in my post it doesn't matter if I use Ascending or Descending or a different sort method. Any other suggestions? Thanks in advance

View: Recent posts all users


Creating a function that can assess a column and give an output in a new column

Question: This is my first question, so I will attempt to give as much detail as possible.
I am attempting to create a function in which I can produce a new column containing "1" or "0" as my output based on whether or not the original column had a date listed or it had no value. Below is a small example of what I am trying to achieve:
            Column 1      New Column
    Obs.1   4/23/2012          1
    Obs.2                      0
    Obs.3   1/23/2016          1

I am not sure on  how to go about doing this. I have attempted to use tapply() and ifelse() in conjunction, but have not had any workable code. This is sort of what I am going for:
    TextToNumb <- function(df$column){
    Ifelse(df$column > 0, 1, 0)
    return(df$newcolumn
    }

I would appreciate any help, thanks!
Answer: The tidyverse is your friend.
library(tidyverse) ## This will call multiple packages including dplyr
library(magrittr) ## This makes assignment back to the original dataframe by %<>%
df <- data_frame(Date = c("4/23/2012", "", "1/23/2016"))
df %<>% dplyr::mutate(Bin = ifelse(Date != "", 1, 0))

You do not need to specify a separate function. If you wish to check for whether the column is of type Date as well, you can do the following with the lubridate package, also part of tidyverse:
library(lubridate)
df %<>%
  dplyr::mutate(Bin = ifelse(!is.na(parse_date_time(Date, 'mdy')), 1, 0))

If it is sufficient to check that something is there, you can use the first code. If you are relatively new to R, you can start with reading R for Data Science, which is a great book.
Comment: Thank you. I am somewhat familiar with the tidyverse, I have dplyr, lubridate, and ggplot2, but have not used magrittr. (I began with individual packages not realizing there was an entire set). I am relatively new to R, currently doing some data camp courses and the edX course for statistics and R.
Answer: Adding to @Kim 's response, this might be more direct:
df <- data_frame(Date = c("4/23/2012", NA, "1/23/2016"))
df %<>% mutate(Bin = ifelse(is.na(Date), 0, 1))

Using the "" as a condition might report incorrect results.  I would suggest using is.na instead since the sample data set has a row entry without a value, not "".
Comment: Is there a way to assign values based on the presence or absence of any value, not just a date? (e.g. a value of 345 receives a 1, whereas a blank still yields a 0)?
Answer: Here's one approach using base R, exploiting a behaviour that sometimes comes in handy.
df$is_date = as.numeric(!is.na(df$date))

We use the vectorized function is.na to test each element of the date column for empty values, which gives us a boolean/logical vector of TRUE/FALSE. After reversing these values with !, we can simply convert them to binary integers with as.numeric because, in R,  TRUE and FALSE are actually the same as 1 and 0:
TRUE == 1
[1] TRUE
FALSE == 0
[1] TRUE


is there any differenc between these two selectors in Styled-components? ">" vs "&"

Question: greater than sign(>) refers to the direct parent.
ampersand sign(&) also does refer to its parent.
const Container = styled.div`
  > p{
    color:red;
  }
`

above equals to this ㄱ
const Container = styled.div`
  & p{
    color:red;
  }
`

both versions will make the p tag, which is the direct child of Container, have a red font color....
is that wrong? if so, how are they different?
Comment: it's the same as css selectors, the `& p` variant will select all children. while `> p` will select only direct children. see [css question](https://stackoverflow.com/questions/2636379/what-is-the-difference-between-and-a-space-in-css-selectors) for additional details
Answer: "parent > p" will apply only to paragraphs that are direct children of parent, while "&" will apply to all paragraphs located inside its parent, no meter the level. Putting "& p {}" is equal to putting "parent p {}".


Count and Sort row showing count number

Question: I have a table with structure: id (primary key), name, ep
I want to sort the elements order by id, where name = test, showing the count number of the row..
example:
id - name - ep - count
930 - test - 1 - 1
931 - test - 2 - 2
932 - test - 3 - 3
933 - test - 4 - 4
934 - test - 7 - 5
935 - test - 9 - 6

I have tried:
select name, id, count(*) as count from episodios where name = "test" group by id order by count asc;

But i'm getting error on mysql.. #1055 - Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column
Could someone help me? Thanks!
Comment: which mysql version are you using?
Comment: 8.0.3, in ubuntu 20.04
Answer: mysql 8 has window function ROW_NUMBER

CREATE TABLE tmptable (
  `id` INTEGER,
  `name` VARCHAR(4),
  `ep` INTEGER
);

INSERT INTO tmptable
  (`id`, `name`, `ep`)
VALUES
  ('930', 'test', '1'),
  ('931', 'test', '2'),
  ('932', 'test', '3'),
  ('933', 'test', '4'),
  ('934', 'test', '7'),
  ('935', 'test', '9');

SELECT
`id`, `name`, `ep`,
ROW_NUMBER() OVER (PARTITION BY `name` ORDER BY `ep`) as cnt
FROM
tmptable

 id | name | ep | cnt
--: | :--- | -: | --:
930 | test |  1 |   1
931 | test |  2 |   2
932 | test |  3 |   3
933 | test |  4 |   4
934 | test |  7 |   5
935 | test |  9 |   6

db<>fiddle here
MySQL 5 has this option, as you have problems with the window function, i would recommend updating if possible

CREATE TABLE tmptable (
  `id` INTEGER,
  `name` VARCHAR(4),
  `ep` INTEGER
);

INSERT INTO tmptable
  (`id`, `name`, `ep`)
VALUES
  ('930', 'test', '1'),
  ('931', 'test', '2'),
  ('932', 'test', '3'),
  ('933', 'test', '4'),
  ('934', 'test', '7'),
  ('935', 'test', '9');

SELECT
`id`, `name`, `ep`,
IF(@name = name, @rn :=  @rn + 1, @rn := 1) as cnt
,@name := `name`
FROM
tmptable, (SELECT @rn := 0, @name := '') t1
ORDER BY `name`, `ep`

 id | name | ep | cnt | @name := `name`
--: | :--- | -: | --: | :--------------
930 | test |  1 |   1 | test
931 | test |  2 |   2 | test
932 | test |  3 |   3 | test
933 | test |  4 |   4 | test
934 | test |  7 |   5 | test
935 | test |  9 |   6 | test

db<>fiddle here
Comment: Thanks! Was exaclty what i wanted.. i got only some error/warning in phpmyadmin when went to execute this query, something about alias.. but it worked.
Comment: Try to update, or use the mysql6  version in the meantime, if not possible, the order of the columns must stay, because of the logic
Comment: @kanohn . . . The code uses variables for older versions of MySQL is not correct.  MySQL specifically warns that variables (such as `@name` in this example) should not be referenced in one expression and assigned in  another, because the order of evaluation of `SELECT` expressions is not guaranteed.  Use `row_number()`.
Comment: @gordonlinoff I got the expression warning/error on row_number() code, and i'm using Mysql 8, the other code with name i don't got errors, however both codes worked fine, just the first i got the warning, no idea why.
Comment: @kanohn . . . I'm just warning you that the variables are not guaranteed to "work fine" and may stop working at some point. Use `row_number()` -- if you have MySQL 8+ it should work.

Count and Sort row showing count number


Select all div siblings by using BeautifulSoup

Question: I have an html file which has a structure like the following:

</div

I would like to select all the siblings div without selecting nested div in the third and fourth block. If I use find_all() I get all the divs.
Answer: You can find direct children of the parent element:
soup.select('body > div')

to get all div elements under the top-level body tag.
You could also find the first div, then grab all matching siblings with Element.find_next_siblings():
first_div = soup.find('div')
all_divs = [first_div] + first_div.find_next_siblings('div')

Or you could use the element.children generator and filter those:
all_divs = (elem for elem in top_level.children if getattr(elem, 'name', None) == 'div')

where top_level is the element containing these div elements directly.


Prove that for all positive integers $n$: When $n$ and $n^3$ are expressed in base $3$, they have the same ones digit.

Question: Note: I have attempted to prove the statement above using mathematical induction, but I am not entirely certain of its correctness. I would appreciate any guidance or feedback on the proof.*
Proof:
To prove that for all positive integers $n$, when $n$ and $n^3$ are expressed in base $3$, they have the same ones digit, we can use mathematical induction.
Let $P(n)$ be the statement: "When $n$ and $n^3$ are expressed in base $3$, they have the same ones digit."
Base Case (n = 1):
Let's check if $P(1)$ is true.

$1$ in base $3$ is just $1$.
$1^3 = 1$ in base $3$ is also just $1$.

The ones digit of $n$ and $n^3$ is the same (both are $1$), so $P(1)$ is true for the base case.
Inductive Step:
Assume that $P(k)$ is true for some positive integer $k$, which means when $k$ and $k^3$ are expressed in base $3$, they have the same ones digit. We will prove that $P(k+1)$ is true, which means when $(k+1)$ and $(k+1)^3$ are expressed in base $3$, they also have the same ones digit.
Now, let's consider $(k+1)$ and $(k+1)^3$:

$(k+1)$ in base $3$ may have a ones digit of $0$, $1$, or $2$. We'll consider each case:

Case 1: If the ones digit of $(k+1)$ is $0$:
In this case, $(k+1)$ is divisible by $3$. Therefore, $(k+1)^3$ will also be divisible by $3$, and its ones digit in base $3$ will be $0$.
Case 2: If the ones digit of $(k+1)$ is $1$:
In this case, $(k+1)$ leaves a remainder of $1$ when divided by $3$. Therefore, $(k+1)^3$ will leave the same remainder when divided by $3$ (since the cube of a number with a remainder of $1$ is still $1$ when divided by $3$), and its ones digit in base $3$ will be $1$.
Case 3: If the ones digit of $(k+1)$ is $2$:
In this case, $(k+1)$ leaves a remainder of $2$ when divided by $3$. Therefore, $(k+1)^3$ will leave the same remainder when divided by $3$ (since the cube of a number with a remainder of $2$ is still $2$ when divided by $3$), and its ones digit in base $3$ will be $2$.
In all three cases, the ones digit of $(k+1)$ and $(k+1)^3$ is the same in base $3$.
So, by induction, we have shown that for all positive integers $n$, when $n$ and $n^3$ are expressed in base $3$, they have the same ones digit.
Comment: You never use the inductive hypothesis, and in each case, you just state the conclusion that you want to reach without providing a reason, e.g. *"since the cube of a number with a remainder of $1$  is still $1$ when divided by $3$"*
Comment: Looks ok but there is no real need for induction.
Comment: @SammyBlack enlighten me kindly how to fix if there is an error.
Comment: @coffeemath which other way we can do this?
Comment: $n^3-n=n(n+1)(n-1)$ is divisible by $3$.
Comment: @Jean-ClaudeArbaut what do you mean by this statement?
Comment: I mean that this statement is trivially true (among three consecutive numbers, exactly one is divisible by $3$). This then means that $n^3$ and $n$ differ by a multiple of $3$, hence their unit digits are identical.
Comment: @Ameer786 Instead of induction, just show it for the three cases where k has last digit 0,1,2 when written in base 3. Of course you  need to *prove* that if k has last digit d when written in base 3 so does k^3, for each of d=0,1,2. [you really did not do that in your induction proof either]
Answer: This can be proved directly without induction.
Hint: What are the factors of $n^3 - n$ and what does that tell us about divisibility by $3$?

 Since $n^3 - n = (n-1)n(n+1)$, which are $3$ consecutive integers, one of the factors is a multiple of $3$, so $n^3 - n = 3k$ for some integer $k$. So each of $n^3$ and $n$ must have the same remainder upon division by $3$, i.e. the same unit digit in base $3$.
Comment: By the way, this works for any prime $p$: expressed in base $p$, the numbers $n$ and $n^p$ have the same units digit. This is one of many ways to state [Fermat's Little Theorem](https://www.wikiwand.com/en/Fermat%27s_little_theorem).
Comment: I guess... I mean, it makes it not an induction proof.
Comment: I appreciate the your way but is my induction proof correct or not?
Comment: No. You never use the induction hypothesis, at least not explicitly.
Comment: That doesn't make the induction proof incorrect - it just makes it silly.
Answer: The induction proof is not wrong, but since you never use the induction hypothesis, it could be simplified to a direct proof. To prove that $n$ and $n^3$ have the same ones digit in base $3$, simply consider the same three cases:

The ones digit of $n$ is $0$;
The ones digit of $n$ is $1$;
The ones digit of $n$ is $2$.

In each case, you already have an argument that shows that $n^3$ has the same ones digit as $n$ - you're just writing it for $k+1$ instead of $n$.

There is, however, an interesting inductive argument. Here is how that looks (I will pick back up from the second paragraph of the inductive step in the question):
Now, let's consider $k+1$ and $(k+1)^3$.
Clearly, $k+1$ has the next ones digit after $k$'s ones digit: if $k$ ends in $0$, $1$, or $2$, then $k+1$ ends in $1$, $2$, or $0$, respectively.
We can also check that $(k+1)^3$ has the next ones digit after $k^3$'s ones digit, because $$(k+1)^3 - k^3 = 3k^2 + 3k+1.$$ Adding $3k^2+3k$ does not affect the ones digit, so the only relevant effect is adding $1$.
By the inductive hypothesis, $k$ and $k^3$ have the same ones digit, and we've just proven that both $k+1$ and $(k+1)^3$ advance that digit by exactly one step; therefore they must also have the same ones digit!
Note that here, in the last paragraph, we did use $P(k)$ to prove $P(k+1)$, which is what makes induction necessary.


Question about D7 Organic Groups, Memberships, and Views

Question: I have been using OG and Views on Drupal 7. I think it's great but am having one problem. Here's the situation: I am creating views of content, and am wanting to show which group each piece of content is a "member" of. To do this, I bring in a "group membership" relationship and then another group relationship, which then lets me show the GID, title, etc., from the Organic Group.
But here's the problem: as soon as I introduce the "OG membership" relationship into the mix, it begins to show each piece of content twice (or 3 or 4 times) if that content is posted into 2, 3, or 4 groups. I think this is because in the og_memberships table, each membership has its own ID.
What I'd like to do is show each piece of content once, but have a "multiple" type setting on the OG field area, the same way I can show multiple imagefields or Taxonomy terms that are all related to one node.
Anyone got experience with this?
Answer: That sounds more like an issue with the SQL query, called a Cartesian join.  It's where you join every row of one table to every row in another table, or to itself, resulting in lots of duplicated rows. Dump the SQL that the View is creating and run it by itself in the database client to see if that's the source of the problem.


Flipping a shape made by user input

Question: So currently I have to create a shape made out of asterisks based on user input.
This is my code currently that will create the shapes
num = int(input("Enter a number: "))
for i in range(1,num+1):
     for j in range(1,i+1):
         print("*",end="")
     print()

with the output of:
*
**
***
****
*****

and
num = int(input("Enter a number: "))
for i in range(num,0,-1):
    print("*"*i)

output:
*****
****
***
**
*

I need to flip them to look like:
    *
   **
  ***
 ****
*****

and
*****
 ****
  ***
   **
    *

I am struggling to find a solution, though I'm sure it must be quite simple to flip them.  Thanks in advance!
Comment: An obvious method would be `print(" "*(num-i),"*"*i)`
Answer: Look at the rjust method to right-justify your strings: ("*" * i).rjust(num)
Answer: you can just print the spaces
num = 5
for i in range(1, num+1):
    print(' ' * (num - i) + '*' * i)

    *
   **
  ***
 ****
*****

Flipping a shape made by user input


How to add an iptables rule that UFW can't create in Ubuntu?

Question: UFW is working really well for me except in the cases where it doesn't...
I want to be able to add another rule manually that will be applied on boot?

where should i put this rule?
how should I make it start at boot?
how do I make it play nicely with UFW?
Comment: ufw is one of those "what you see is all you get" things that make it easier for newbies. If you need to do more than it can do, consider switching to iptables completely. That "working really well for me" is a good proof that you can try something (iptables) more complicated (but also more flexible).
Comment: Related: https://askubuntu.com/questions/1006834/ufw-rules-disappear-after-manually-adding-them-to-user-rules-ubuntu-16-04
Answer: According to this Ubuntu wiki page (scroll down to "Advanced Functionality"), you can achieve what you want by putting your own iptables rules into the following files:

/etc/ufw/before.rules
/etc/ufw/after.rules

The before file is evaluated before any ufw rules are applied; the after file is evaluated after. (There are also corresponding before6 and after6 rules files, for your ip6tables rules.)
These rules files are expected to be in iptables-restore-compatible syntax, presumably because ufw simply loads them using iptables-restore. Finally, note that you need to stop and restart ufw after you make any changes to the rules files.
Comment: Note that you can (perhaps unintentionally) change the precedence of iptables rules if you forget to standardize the use of -I or -A when using these files. -I (insert) adds rules to the TOP of the chain, evaluated first, while the -A (append) adds them to the bottom of the chain. This might cause unexpected results if you use -I in the .after file, for example. Just a thought.
Comment: Does the order of the rules matters? How do I know if I want my rule before or after UFW?
Comment: This is definitely how UFW was envisioned, but you can actually add rules to `user.rules` as well, if you include the required comments. See the other answer on this page from @F1Linux that explains more about this bizarre config...
Answer: UFW will purge any MANUALLY added rule in /etc/ufw/user.rules which is NOT prefaced with a comment:
### tuple ### allow tcp 80 0.0.0.0/0 any 0.0.0.0/0 out
-A ufw-user-output -p tcp --dport 80 -j ACCEPT

When UFW sanity checks the rules on startup, it expects an accompanying comment.  If it's NOT present, even if the syntax of the rule is correct, UFW will still purge it.
And don't just use any arbitrary comment: it MUST be the comment that UFW would insert when creating a user rule via the cli, ie:
sudo ufw allow http/tcp

So if you want to pre-seed a series of rules in a ruleset in a simple file, you'd still need to create the rules via UFW's CLI interface to learn the syntax of the comments it expects for the rule to pass validation and persist.
Try the foregoing with and WITHOUT the comment and reload the specimen HTTP rule above; you'll remark only with the comment does the manually added rule survive a restart (ufw enable) of UFW.
This is really counter-intuitive behaviour and not documented at all.
Comment: This is because the `user.rules` file is not supposed to be edited directly; it is used by ufw to store rules added via the `ufw` command by the user. From the Ubuntu documentation: `/var/lib/ufw/user[6].rules or /lib/ufw/user[6].rules (0.28 and later): rules added via the ufw command (should not normally be edited by hand) `
Comment: "UFW will purge any MANUALLY added rule in /etc/ufw/user.rules which is NOT prefaced with a comment:" so annoying. Why would they do that?!
Comment: Great explanation!
It's a bit puzzling for me why this core behavior is not clarified clearly on most of the docs I've seen
Comment: You're right Mei, but it seems they de-facto "accepted" people wanted to edit and also backup the `user.rules` file, which is why it was moved from `/lib/` to `/etc/` ...however better documentation would definitely be nice.
Comment: Here's that discussion: https://bugs.launchpad.net/ufw/+bug/728128


Deriving MLE of $\theta$ in $\text{Exp}(\theta,\theta)$ distribution

Question: Suppose $X_1,X_2,\ldots,X_n$ are i.i.d variables having a two-parameter exponential distribution with common location and scale parameter $\theta$ :
$$f_{\theta}(x)=\frac{1}{\theta}e^{-(x-\theta)/\theta}\mathbf1_{x>\theta}\quad,\,\theta>0$$
I am wondering if it is possible to derive a maximum likelihood estimator (MLE) of $\theta$.
The likelihood function given the sample $x_1,\ldots,x_n$ is
$$L(\theta)=\frac{1}{\theta^n}e^{-n(\bar x-\theta)/\theta}\mathbf1_{x_{(1)}>\theta}\quad,\,\theta>0$$
, where $\bar x=\frac{1}{n}\sum\limits_{i=1}^n x_i$ and $x_{(1)}=\min\limits_{1\le i\le n} x_i$.
Since $L(\theta)$ is not differentiable at $\theta=x_{(1)}$, I cannot apply the second-derivative test here.
Even if I could say that $L(\theta)$ is increasing and/or decreasing in $\theta$ under the constraint $\theta<x_{(1)}$, I am not sure what choice of $\theta$ maximises $L(\theta)$. Differentiation is not valid as I understand. I think it is safe to assume $x_{(1)}<\bar x$, so the constraint is actually $\theta<x_{(1)}<\bar x$.
If MLE is unique, then it is likely to be a function of the sufficient statistic $(\overline X,X_{(1)})$. However I don't see how to derive it in this particular model. Any suggestion would be great.
Comment: @angryavian I just ran a small simulation using Python, and it gives a unique maximizer not equal to $x_{(1)}$. Not sure what gives, just thought I'd mention it.
Comment: you can not generate observations less than $\theta$, hence the MLE of $\theta$ is most probably the minimum order statistic
Answer: The joint likelihood is $$\mathcal L (\theta \mid \boldsymbol x) = \theta^{-n} e^{-n(\bar x - \theta)/\theta} \mathbb 1(x_{(1)} \ge \theta).$$  Since the unique critical point of the unrestricted likelihood occurs for $$0 = \frac{d}{d\theta} \left[\log \mathcal L \right] = -\frac{n}{\theta} + \frac{n\bar x}{\theta^2} = \frac{n}{\theta^2}(\bar x - \theta)$$ or $\theta = \bar x \ge x_{(1)}$, and the likelihood is increasing on $\theta \in (0, x_{(1)}]$, it follows that the global maximum must be the minimum order statistic $\hat \theta = x_{(1)}$.
It is worth noting that while the MLE can exceed the true value of $\theta$, it cannot be larger than the minimum order statistic, since in such a case, such an estimate could not generate at least one observation in the sample.  Also note that the MLE cannot be smaller than the true value of $\theta$, since such an estimate could only have been generated from a sample with an observation that is smaller than $\theta$, which is impossible.  In short, we must always have $$0 < \theta \le \hat \theta \le x_{(1)} \le \bar x.$$
Comment: So is the unique mle $\hat\theta=x_{(1)}$ or is any $\hat\theta$ satisfying $0<\hat\theta< x_{(1)}$ a possible answer? (you have included zero as a value of $\theta$ in the last line) If you have any confirmation using simulation, please share that as well. Also, is differentiating the likelihood necessary?
Comment: @StubbornAtom The inclusion of $0$ was an oversight, apologies.  The increasing nature of $\mathcal L$ w.r.t. $\theta$ would preclude choosing any $\hat \theta \in (0, x_{(1)})$.  Indeed, since you do not know $\theta$, but you know $\theta \le \hat \theta$, in a sense, you cannot choose any other value except $\hat \theta = x_{(1)}$.


Transformar texto para italico on hover!

Question: Boas, eu tenho um paragrafo e quero que ele fique com font-style: italic; quando passo o rato por cima, que propriedades devo por no :hover?! Gostava que fosse uma transição de 0.3segundos
Comment: Infelizmente não tem como fazer transição com estilo de fonte.
Comment: pode usar javascript?
Comment: @MagicHat pode, desde que o script seja uma coisa simples para eu entender :D mas já tenho uma resposta para aquilo que queria , não precisa de se dar ao trabalho
Answer: Não tem como, primeiro porque o único pseudo-elemento que existe para linhas é o ::first-line e ele só vai pegar a primeira linhas, segundo o font-style diferente do font-weight não suporta valores numéricos para que seja feito uma transição entre o não itálico e o itálico.
Mas nem tudo esta perdido
Você pode simular o itálico usando transform e se considerar parágrafos por
 será possível, um exemplo funcional:

Nota: para evitar o efeito de pulo (o tal bug), basta adicionar: transform: skewX(0.001deg);

.container p {
    transform: skewX(0.001deg); /*evita o "efeito de pulo"*/
    transition: transform .3s ease-in-out;
}

.container p:hover {
    transform: skewX(-20deg);
}

foo bar baz

Hello World!

Olá Mundo!

Claro que isto não é itálico, se você tiver estilos nos parágrafos, como bordas ou background eles poderão ser afetados também, para evitar isto você pode adicionar  para cada paragrafo sem estilo e fazer assim por exemplo:

.container p {
    background: #ccc;
    border-radius: 5px;
    margin-bottom: 5px;
    padding: 5px;
}

.container p span {
    display: inline-block;
    transform: skewX(0.001deg); /*evita o "efeito de pulo"*/
    transition: transform .3s ease-in-out;
}

.container p:hover span {
    transform: skewX(-20deg);
}

         foo bar baz

         Hello World!

         Olá Mundo!

Tentando remover o blurry durante a animação
Infelizmente o titulo diz "tentando" porque não é algo 100% garantido, isso depende muito do hardware e do software que usa, o problema do efeito "blurry" nos textos é bem comum no Chrome, as técnicas (tentativas) que existem são:
Usar -webkit-font-smoothing: subpixel-antialiased;:
Deve ficar assim:
.container p {
    transition: transform .3s ease-in-out;
    -webkit-font-smoothing: subpixel-antialiased;
}

E no segundo exemplo:
.container p span {
    display: inline-block;
    transition: transform .3s ease-in-out;
    -webkit-font-smoothing: subpixel-antialiased;
}

No entanto em computadores com driver de vídeo genérico provavelmente não vai funcionar como esperado, ou talvez não funcione de maneira alguma.
Usar transform: translateZ(0) ...
Isso é um hack, ele por algum motivo no Chrome ajuda na aceleração de renderização, mas pelo que li em alguns casos funciona e em outros não, provavelmente depende do equipamento do usuário:
.container p:hover span {
    transform: translateZ(0) skewX(-20deg);
}

E no segundo exemplo:
.container p:hover span {
    transform: translateZ(0) skewX(-20deg);
}

Pode experimentar ambos, ainda sim como citei antes, provavelmente vai depender do equipamento (hardware e software).

Nota: @keyframes não resolve o problema do efeito blurry, o que ocorreu na resposta do hugo é que ele usou a fonte maior, se usar inicialmente transform: skewX(0.001deg);, antes da transição e colocar 2em da fonte vai ficar quase idêntico ao keyframes

#comtransform {
    font-size: 2rem;
    font-weight: bold;
    color: blue;
    transform: skewX(0.001deg); /*evita o "efeito de pulo"*/
    transition: transform .3s ease-in-out;
}

#comtransform:hover {
    transform: skewX(-20deg);
}

@keyframes

Comment: @Droopy infelizmente não, é o efeito da distorção e o tipo da fonte que causam isto.
Comment: acabei de adicionar esse pormenor e corrigiu logo o blur, uma solução bastante inteligente =)) obrigado pela ajuda
Comment: Exactamente o que queria, obrigado ficou excelente =))
Comment: não tem como retirar o blur enquanto as letras inclinam?!
Comment: Acabei de utilizar a tentativa de retirar o blurry mas infelizmente não funcionou :s
Comment: @Droopy editei a resposta, parece que adicionar `.container p {
        transform: skewX(0.001deg); ...` no elemento antes da animação/hover ajudou a melhorar o blur e até corrigiu um efeito de pulo que ocorria nas letras.
Answer: Fiz um teste usando @keyframes no lugar do transition E o resultado ficou até interessante, diminuiu bastante aquele buggizinho na altura do texto.
Fiz um exemplo simples, veja o resultado.

p#anima {
    font-size: 2em;
    font-weight: bold;
    color: red;
    transition: all 300ms;
}
p#anima:hover {
    transform: skewX(-10deg);
}

p#key{
    font-size: 1.2rem;
    font-weight: bold;
    color: blue;
}
p#key-small{
    font-size: 0.6rem;
    font-weight: bold;
    color: blue;
}
p#key-big{
    font-size: 3rem;
    font-weight: bold;
    color: blue;
}
p#key:hover, p#key-small, p#key-big {
    -webkit-animation-name: example; /* Safari 4.0 - 8.0 */
    -webkit-animation-duration: 500ms; /* Safari 4.0 - 8.0 */
    animation-name: example;
    animation-duration: 500ms;
    animation-iteration-count: 1;
    animation-fill-mode: forwards;
}
p#key:not(:hover), p#key-small:not(:hover), p#key-big:not(:hover) {
    -webkit-animation-name: rever; /* Safari 4.0 - 8.0 */
    -webkit-animation-duration: 500ms; /* Safari 4.0 - 8.0 */
    animation-name: rever;
    animation-duration: 500ms;
    animation-iteration-count: 1;
    animation-fill-mode: forwards;
}

/* Safari 4.0 - 8.0 */
@-webkit-keyframes example {
    from   {transform: skewX(-3deg);}
    to {transform: skewX(-10deg);}
}
/* Standard syntax */
@keyframes example {
    from   {transform: skewX(-3deg);}
    to {transform: skewX(-10deg);}
}

/* Safari 4.0 - 8.0 */
@-webkit-keyframes rever {
    from   {transform: skewX(-8deg);}
    to {transform: skewX(-0deg);}
}
/* Standard syntax */
@keyframes rever {
    from   {transform: skewX(-8deg);}
    to {transform: skewX(-0deg);}
}

transition transform

@keyframes

@keyframes-small

@keyframes-big

Comment: Exatamente Hugo! Somente from e to fica perfeito! - Só pra constar, efeito do "pulo" (o tal bug) foi removido com `transform: skewX(0.001deg);`, veja a resposta: https://pt.stackoverflow.com/a/264942/3635
Comment: O 25% e o 50% podem ser removidos que o efeito será o mesmo, ao menos no Chrome.
Comment: @GuilhermeNascimentoP. Nem tinha reparado rss, parece que só por ser @keyframe já atenua o efeito. Nesse caso seria melhor usar `from {transform: skewX(0deg);}`  `to {transform: skewX(-10deg);}` []´s
Comment: Outra coisa que notei, o keyframe não removeu o blur, foi o tamanho da fonte que você usou que fez o efeito desaparecer, ou seja isso não resolve, se usar a fonte pequena o efeito blur ainda ocorre. Só pra avisar mesmo.
Comment: @GuilhermeNascimentoP. na verdade o que mudou mesmo foi aquele pulinho que a fonte dava no início. O Blur não tinha melhorado muito mesmo não. Parece que a formatação do Estilo da font também pode afetar um pouco esse efeito de Blur indesejado. Parece que quando o Elemento já tem o `skewX` antes da animação acontecer o "saltinho" da fonte some!
Comment: Então uso, esse problema do *efeito blurry* ocorre devido a capacidade de aceleração grafica do hardware ou software, em monitores de retina, como Mac OSX é provavel que o blurry nem seja notado, mas em outros casos (efeitos css) mesmo com retina pode ocorrer, depende do efeito, depende do software e hard. Editei a resposta e adicionei um exemplo com `font-size: 2em`: https://pt.stackoverflow.com/a/264942/3635
Comment: Obrigado pela resposta mas basta adicionar `transform: skewX(0.001deg);` no p e o efeito blur deixa de se notar


visibility between containers built with different docker-compose configuration

Question: I need to use the service api_mysql in sass_php. Containers are built with different docker-compose.yml files and I understand they belong to different network and they can't see betweem them. The following is my current configuration, but then when I want to use the service I get:
"php_network_getaddresses: getaddrinfo failed: Name does not resolve":
$ docker network ls
NETWORK ID          NAME                 DRIVER              SCOPE
bcad56c87a8c        repo1_api           bridge              local
196f42d7cbea        repo2_api           bridge              local
79b41a714b48        repo2_sass          bridge              local

docker-compose-1.yml
networks:
  api:

services:

  api_mysql:
    ...
    networks:
      api:

  api_php:
    ...
    depends_on:
      - api_mysql
    networks:
      api:

docker-compose-2.yml
version: '3'

networks:
  api:
  sass:

services:

  sass_mysql:
    ...
    networks:
      sass:

  sass_php:
    ...
    depends_on:
      - sass_mysql
    networks:
      api:
      sass:

Answer: As they live in different networks so do their domain names. The DNS used by sass_php does not access the domain names available in repo1_api network. It can access the ones in repo2_api network but this network is not used by api_mysql.
So to remediate, you can declare your network outside your docker-compose files and add it that way:
networks:
  default:
    external:
      name: my-pre-existing-network

Ref: https://docs.docker.com/compose/networking/#use-a-pre-existing-network
Or you can EXPOSE the api_mysql ports to your localhost and access by it.
I would prefer the first method.


Rankine-Hugoniot for Burgers equation with Lorentzian initial data

Question: We have the following equation with initial condition
\begin{align*}
     u_y + uu_x &= 0\\
u(x,0)&=\frac{1}{1+x^2}\quad x\in\mathbb{R}
\end{align*}
let's say $g(x)=\dfrac{1}{1+x^2}$ and corresponding to the manifold  $\Gamma$ in the $xyz$ space given by
\begin{equation}
    x = s,\quad y = 0,\quad z = g (s)
\end{equation}
The characteristic differential equations
\begin{equation*}
    \frac{dx}{dt}=z\quad  \frac{dy}{dt}=1\quad \frac{dz}{dt}=0
\end{equation*}
Integrating each of the expressions we have
\begin{align*}
\int dx&=\int z dt\\
x&=zt
\end{align*}
also
\begin{align*}
\int dy&=\int 1 dt\\
y&=t
\end{align*}
and
\begin{align*}
\int dz&=\int 0 dt\\
z&=0
\end{align*}
combined with the initial condition  for $t=0$ lead to the parametric representation
\begin{equation*}
    x=s+zt,\quad y=t, \quad z=g(s)
\end{equation*}
now as
\begin{equation*}
s=x-zt\quad \text{and}\quad y=t \quad \text{and}\quad z=g(s)
\end{equation*}
For the solution $z=u(x,y)$ then yields the implicit equation
\begin{equation*}
u=g(x-uy)=\frac{1}{1+(x-uy)^2}
\end{equation*}
now the study is going to be done of Weak (or Integral) Solutions
as the characteristic is given by
\begin{equation*}
x=\frac{y}{1+\xi^2}+\xi
\end{equation*}
it is necessary that this characteristic presents shock to do the study according to the study made by the book (artial Differential Equations in Action From Modelling to Theory) page 199 to find $y_s$ (breaking time) and
the location $x_s$ the following is done where $q(u)=u^2 / 2$ then $q'(u)=u$ and $q''(u)=1$
\begin{equation*}
z(\xi)=-q''(g(\xi))g'(\xi)=-1\cdot \frac{-2x}{\left(1+x^2\right)^2}=\frac{2x}{\left(1+x^2\right)^2}
\end{equation*}
and the maximum point of $z(\xi)$ is $\left(\sqrt{\frac{1}{3}},\:\frac{3\sqrt{3}}{8}\right)$ then $\xi_M=\sqrt{\frac{1}{3}}$ and $z(\xi_M)=\frac{3\sqrt{3}}{8}$ then
\begin{equation*}
y_s=\frac{1}{z(\xi_M)}=\frac{1}{\frac{3\sqrt{3}}{8}}=\frac{8}{3\sqrt{3}}
\end{equation*}
and
\begin{equation*}
x_s=q'(g(\xi_M))y+\xi_M=\frac{1}{1 + (\sqrt{1/3})^2}\left(\frac{8}{3\sqrt{3}}\right)+\sqrt{\frac{1}{3}}=\frac{2}{\sqrt{3}}+\sqrt{\frac{1}{3}}
\end{equation*}
therefore $\displaystyle (x_s,y_s)=(\frac{2}{\sqrt{3}}+\sqrt{\frac{1}{3}},\frac{8}{3\sqrt{3}})$
1)My question is already having all these data, how can I do the study of  Rankine-Hugoniot condition?
Your answers would be of great help. Thank you very much. I remain attentive to your answer.
Answer: The characteristic curves satisfy
$$
x= x_0 + g(x_0) y, \qquad u = g(x_0)
$$
where $g(x) = (1+x^2)^{-1}$ is the initial data, i.e.
$
u = g(x-uy)
$
in implicit form. The shock time is given by
$$
y_s = \frac{-1}{\inf_{x_0} g'(x_0) } = \frac{8}{3\sqrt{3}} \simeq 1.54
$$
for $x_0 = 1/\sqrt{3}$. Therefore, the results in OP look correct, except the potential mistake in the expression of $x_s$. The Rankine-Hugoniot condition for the inviscid Burgers equation is still valid in the usual form
$$
x_s'(y) = \tfrac12 \left( u_\ell + u_r\right),$$
$$\text{with}\qquad x_s(y_s) = \frac{1}{\sqrt 3} + \frac{8}{3\sqrt{3}}\, g\left(\frac{1}{\sqrt 3}\right) = \sqrt 3 \simeq 1.73
$$
where $u_\ell$, $u_r$ represent the value of $u = g(x-uy)$ on the left and on the right of the discontinuity $(x_s(y), y)$ with $y \geq y_s$. See this post where a simpler case is tackled analytically.


trying to submit a view and getting 405 error

Question: I'm trying to implement a review section in a user profile but I keep getting this 405 error when i try to submit a review even tho when i create a review in the admin panel it shows on the profile normaly. if you could help.
Thanks in advance
Code:
Model
class Review(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    expert = models.ForeignKey(Expert, on_delete=models.CASCADE)
    timestamp = models.DateTimeField(auto_now_add=True)
    content = models.TextField()

Form
class ReviewForm(forms.ModelForm):
    content = forms.CharField(widget=forms.Textarea(attrs={
    'rows':3,
    }))
    class Meta:
        model = Review
        fields = ('content',)

View
class ExpertDetailView(DetailView):
    model = Expert

    def expert(self, *args, **kwargs):
        form = ReviewForm(self.request.POST)
        if form.is_valid():
            expert = self.get_object()
            review = form.instance
            review.user = self.request.user
            review.expert = expert
            review.save()
            print ('worked')

        print ('worked')

    def get_object(self, **kwargs):
        object = super().get_object(**kwargs)
        return object

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context.update({
            'form': ReviewForm()
        })
        return context

And finaly the Template

Leave a comment below

      <form method='POST'>
          {% csrf_token %}
          {{ form|crispy}}

          <button class='btn btn-primary' type='submit'>review</button>
      </form>

Comments

      {% for review in object.reviews %}

{{ review.content }}

              {{ review.timestamp|timesince }} ago

      {% endfor %}

Comment: Can you post the error django returns ?
Answer: A 405 means that the method is not allowed. This makes sense since you did not write a def post(request, *args, **kwargs), and a DetailView will by default only
That being said, it is probably not a good idea to implement all the logic yourself. You can let the ModelFormMixin already let you do most of the work:
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic.edit import ModelFormMixin

class ExpertDetailView(LoginRequiredMixin, ModelFormMixin, DetailView):
    model = Expert
    form_class = ReviewForm
    success_url = 'some-url'

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        form = self.get_form()
        if form.is_valid():
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

    def form_valid(self, form):
        review = form.instance
        review.user = self.request.user
        review.expert = self.object
        form.save()
        return super().form_valid(form)

Note: You can limit views to a class-based view to authenticated users with the
  LoginRequiredMixin mixin [Django-doc].
Comment: @Talal: ah, well that should be `self.object`.
Comment: Thank you so much for your help. Just one extra thing if you could help me with. i get expert is not defined which most likely be in the form_valid function section. if you could help me define the expert in this instance.


Referencing a hashed svg from the html (webpack)

Question: I'm using file-loader to hash my svg spritesheet to ./dist/svg/sprite.e3452.svg
{
    test: /\.(svg)$/,
    use: {
        loader: 'file-loader',
        options: {
            name: '[name].[hash:5].[ext]',
            outputPath: './svg/'
        }
    }
}

It might be a simple question, but how can I reference an svg file from the html when the name changes with the hash?
For example here:
<svg class="close__icon">
    <use xlink:href="svg/sprite.svg#ios-trash-outline"></use>
</svg>

I use HtmlWebpackPlugin for similar problems with my hashed js files, but can't find anything similar for my svgs.
Thanks
Answer: I don't know if you solved or not but I just had same problem and here the solution.
Webpack insert the sprite svg in the dom and you can access each id with an underscore after the id of the sprite, in your case:
<svg class="close__icon">
    <use xlink:href="#sprite_ios-trash-outline"></use>
</svg>


kibana warning on Elasticsearch plugin

Question: I just installed and am running ElasticSearch (customized version)/Kibana as below:
<code>ES: 5.1.1
Kibana: 6.0.1
CentOS: 7.3
</code>
After I started Kibana it shows me an warning below:
This version of Kibana requires Elasticsearch v6.0.1 on all nodes. I found the following incompatible nodes in your cluster: v5.1.1 @ 127.0.0.1:9200 (127.0.0.1)
so I proceed to download the lastest version of ElasticSearch 7.2.0
I restarted ES and confirmed it is running on 7.2, I restarted Kibana and it is still showing the warning but warning shows the ES version is 7.2 yet it still complains version is low.

This version of Kibana requires Elasticsearch v6.0.1 on all nodes. I
  found the following incompatible nodes in your cluster: v7.2.0 @
  127.0.0.1:9200 (127.0.0.1)

Does it mean I have to install a different version of Kibana/elasticsearch instead of the latest?
How do I get this fixed?
Thank you very much.
Answer: I think I might have the answer now as per this compatibility matrix:
https://www.elastic.co/support/matrix#matrix_compatibility
I am downloading new Kibana and see if it works, I will update here so this post serves something for whoever read it later.
UPDATE: I just confirmed this is the root cause and now it is not showing any warning like that.

kibana warning on Elasticsearch plugin


Socket "cortando" bytes em dois pacotes

Question: Estou desenvolvendo uma comunicação via Socket do meu programa com o servidor. Esse servidor é responsável por realizar uma ponte entre meu programa e os usuários que estão conectados a ele, ou seja, o usuário ao executar uma alteração no "programa A", o usuário do "programa B" irá receber essa alteração e aplicar as alterações automaticamente. A quantidade de programas conectados é indefinida. Abaixo um diagrama exemplificando:

Onde em vermelho é o envio de bytes e em azul é o recebimento. A conexão entre o servidor e o cliente é única e não se fecha. Onde há duas setas de recebimento em azul, significa as duas alterações enviadas em vermelho.
Tudo funciona corretamente. O problema surgiu quando fui enviar uma quantidade de bytes maior do que estava testando e percebi que o objeto Socket "cortou" o envio dos bytes para o servidor, separando-o em 2 pacotes, que, consequentemente, foi recebido em duas partes.
Acontece que esses bytes fazem parte de um único objeto JSON, e ao receber os pacotes, o evento ProgressEvent.SOCKET_DATA é despachado duas vezes, com a primeira e segunda parte do objeto JSON.
O código de envio é:
function enviar(json:Object):void {
    var str:String = JSON.stringify(json); // transformo json em string
    socket.writeUTFBytes(str); // escrevo a string no objeto socket
    socket.flush(); // faço o envio
}

Ao receber (Essa função é executada 2 vezes, "cortando" os bytes em dois pacotes):
function receber(e:ProgressEvent.SOCKET_DATA):void {
    var str:String = socket.readUTFBytes(socket.bytesAvailable); // transformo os bytes em string
    var json:Object = JSON.parse(str);
}

Há algum tipo de limitação de envio da quantidade de bytes? Devo realizar um gerenciamento de filas dos pacotes e separar por processos? Isso acontece em qualquer linguagem?
Comment: Caro biio, o limite de tamanho de pacotes existe em qualquer tipo de programação via Socket, o que ocorre é que muitas vezes é feito implicitamente e só é notado como no teu caso onde o pacote chega separadamente. Não conheço actionscript para te auxiliar quanto a isto mas sei que com sockets em C++ é necessário utilizar a API do sistema operacional para criar a socket e também para alterar o tamanho do pacote enviado e recebido. Espero que alguém consiga te ajudar mais especificamente.
Answer: O procedimento padrão (e necessário!) quando se faz programação em sockets é repetir a recepção até que se tenha recebido o número de bytes esperado.
Como é que se sabe o número de bytes a ser recebido ? Isso é responsabilidade da aplicação. Um método comum é colocar um header (cabeçalho) fixo no início de cada mensagem, contendo o tamanho da mensagem a seguir. O primeiro passo é a aplicação fazer a recepção deste header fixo. Mesmo neste passo é necessário eventualmente fazer recepções repetidas. Após a recepção deste header fixo, a aplicação sabe o tamanho da mensagem a seguir, e portanto faz recepções repetidas até receber o total de bytes da mensagem.
A necessidade desse procedimento advém do fato de que o protocolo TCP transmite e recebe bytes, não mensagens. Assim, quando uma aplicação faz um send de 300 bytes não existe nenhuma garantia de que no outro lado esta mensagem chegue em um único pedaço de 300 bytes. Teoricamente, a mensagem pode chegar em 3 pedaços de 100 bytes, por exemplo, isto é permitido pelo protocolo TCP. Com mensagens pequenas normalmente a cada send corresponde um receive do outro lado, mas à medida que se aumenta o tamanho das mensagens aumenta também a probabilidade de que elas cheguem em vários pedaços do outro lado.
Comment: @biio sua "tarefa" é ir lendo os dados num buffer. Quando der o numero de bytes do header, pegue estes bytes e consuma na aplicação. **Importante:** se você leu a quantidade indicada no header e sobraram bytes, **mantenha** esta sobra no buffer, pois faz parte da  próxima mensagem que está chegando.
Comment: @biio a alteração feita não muda em nada o que foi respondido e o que eu comentei, é simplesmente isso que o JoséX disse. De qualquer forma, pra cada cliente vai ser uma conexão diferente, e em cada conexão, os bytes não mudam de ordem. Essa é uma das diferenças entre TCP e UDP, por exemplo. Em TCP, o que for enviado, vai ser recebido na mesma ordem. Só sugiro tomar um cuidado nas próximas perguntas que fizer no site para por todos os detalhes já de início, pois uma alteração substancial pode invalidar as respostas já dadas. No caso atual, não faz diferença, mas é bom evitar.
Comment: @biio Só uma observação extra: não confunda a conexão com o listener. Normalmente um listener pode "ouvir" vários clientes, mas uma vez iniciada, cada conexão é independente.
Comment: @biio Se for o mesmo socket em TCP, não são paralelas, são sempre sequenciais. Se está abrindo várias conexões, de qq forma tb não vão se misturar os pacotes (e provavelmente algo está estranho na aplicação, pois normalmente se usa o mesmo canal pra comunicação toda). Se vai muitiplexar dados intercalando num stream, continua sendo responsabilidade da aplicação como vai marcar cada bloco. O importante é que em TCP, se você mandar 5000 bytes e a carga for dividida em 3 partes, as 3 partes chegarão na sequência original, então não tem muito com que se preocupar.
Comment: Obrigado pela resposta! Já havia tentando algo parecido, mas vou tentar explicar melhor: um dos problemas que provavelmente irei enfrentar é quando a aplicação possuir mais de uma alteração sendo enviada via Socket pelo servidor. O servidor estará enviando duas alterações paralelas simultaneamente para a aplicação, divididas em vários pacotes com bytes em quantidades indefinidas. Como posso colocar o _header_ no começo do começo das alterações e saber que os pacotes com os bytes restantes são da primeira ou segunda alteração? A aplicação iria se perder, não iria?
Comment: @Bacco, desculpa insistir. Eu estou quase entendendo ou talvez seja minhas explicações que estão um pouco confusas, rsrs. O meu cliente recebe os dados das alterações do servidor, e este é responsável por receber as alterações de outros clientes. Essas alterações são enviadas por uma única conexão socket, ou seja, na mesma conexão eu posso estar recebendo do servidor (Que recebe de outros clientes) **n** alterações. Se as alterações forem enviadas paralelas, porém em fila, ambos os pacotes de bytes são recebidos em fila também?
Comment: @Bacco, fiz uma alteração na pergunta com uma imagem exemplificando o que eu quero dizer, rsrs.

Socket "cortando" bytes em dois pacotes


How to describe the dynamics of this gamble?

Question: Suppose you have a $100 and you are offered a chance to play a game involving a fair coin toss:

If you throw heads your wealth increases by 50%.
If you throw tails your wealth decreases by 40%.

Assume that there is no upper bound to your wealth, i.e., you play the game until you are bankrupt. Let's assume that bankruptcy is an absorbing state and it is reached when your wealth is less than a dollar.
How one might describe the dynamics of your wealth when you go from coin toss $n$ to $n+1$. Moreover, what is the probability that you have increased your wealth after $N$ tosses?
Comment: How about taking the log of the wealth?
Comment: What do you mean "describe the dynamics"?  It seems you have described it.  Note that your wealth after $n$ tosses only depends on the number of heads among those $n$ as long as you do not go bankrupt.
Comment: Where can I go to play this game?
Comment: What I really wanted to find is the probability that after N tosses you have increased your wealth. Of course I realize as N goes to infinity the probability of bankruptcy is close to 1. Considering that this game is non-ergodic I was wondering how to show that the probability of increasing your wealth is smaller the more tosses you make.
Comment: Take the log. You get a classic random walk. Using the convolution, you should obtain the PMF at every step. Can you take it from there? If not, consult a book on (discrete-time, continuous-space) Markov processes.
Comment: @saulspatz Just curious. If I may ask, why do you want to play it?
Comment: @RodrigodeAzevedo If I understand it right, it's a fair game, but the house pays $5$ to $4$.
Comment: @saulspatz $$x_{k+1} = \begin{cases} \frac32 x_k & \text{ if heads}\\ \frac35 x_k & \text { if tails}\end{cases}$$ Since $\frac32 \cdot  \frac35 < 1$ isn't this contractive? Am I missing something?
Comment: @RodrigodeAzevedo I'm really confused now.  If I have $\$10$ and I win then I have $\$15$ but if I lose I have $\$6$.  That means I bet $4$ to win $5$.  How can that be disadvantageous on an even-money chance?
Comment: @saulspatz The expected value of each gamble is \begin{equation} EV=1.5*0.5+0.6*0.5=1.05\end{equation} However I modeled this game in python and found that if 30 players make 100 tosses almost all of them will become poorer than they were before. I guess that this happens because if you throw the dice N times, with N approaching infinity, you will get equal number of heads and tails. In this case your wealth is: \begin{equation} 1.5^{\frac{N}{2}} \times 0.6^{\frac{N}{2}}=0.9^{\frac{N}{2}}\end{equation} This means that on each coin toss you are really losing money.
Comment: @nipohc88 That doesn't make sense to me.  The expectation on each toss is positive.  The expectation on a sequence of tosses is the sum of the expectations on each toss.  By linearity, it must be positive.
Comment: @nipohc88 Okay, I see.  The outliers who win a lot win vast fortunes, but most people go broke.
Comment: @saulspatz Yes, the expectation is positive but it does not matter for you as an individual. Suppose you get a heads and then a tails, your wealth is 1.5*0.6=0.9. I suppose a similar example is that of a russian roulette with a large payoff if you survive. Suppose 100 people play and the gun has 99 empty bullets and 1 real bullet. The expeected value of this will be positive as 99 people will become much wealthier. However, this expected value is irrelevant for you as a player, because if you play this game over and over again at some point you will die and be ruined.
Comment: @saulspatz Yes, exactly as n approaches infinity total wealth has increased due to outliers who have made yuuge amounts of money, but probably 99.99999% of people have gone broke. So it probably is not a good game.
Comment: @RodrigodeAzevedo I'm sorry if this is asking too much, but I am only a high school student and my understanding of probability is not particularly advanced. Could you explain what you mean by taking the log of wealth, as well as how to model the random walk?
Answer: Now that I finally understand the problem, I have a suggestion for approximating a solution.  Change the rules so that the game ends either when the player goes bankrupt or when he has played $N$ times.  Now the chain is finite, with two absorbing states, and we can compute the time to absorption and the probability of absorption in each state by standard methods.  Since we know that the number of steps to absorption in the second absorbing state is $N$, and we also know the probability of absorption in that state, we can easily compute the average time to absorption in the first state.
The transient states are of the form $(w,\ell)$ meaning $\ell$ losses and $w$ wins, where $w+\ell<N$.  Not all possibilities appear, because $\left(\frac35\right)^5<\frac1{10}$ so any player who has lost $5$ times more than he has won has gone bankrupt.
My thought is to try it for various values of $N$, until it stops changing.  The main programming challenge is constructing the transition matrix.
Thanks for this programming problem.  It will help beguile my isolation today.

Suppose we make a cutoff of $M$ rolls. Let $X$ be the average number of rolls until the game ends, whether by bankruptcy or cutoff, let $B$ be the event of bankruptcy, and $C$ the event of cutoff.  We have
$$\begin{align}
E(X)&=\Pr(B)E(X|B)+\Pr(C)E(X|C)\\
&=(1-\Pr(C))E(X|B)+\Pr(C)M
\end{align}$$
My program uses standard method to compute $E(X)$ and $\Pr(C)$ and then uses the above equation to solve for $E(X|B)$ the average time to bankruptcy among those players who went broke.
Here are the outputs from some successive runs:
<code> 50 21.7034134587 .7138047863
100 31.2102201519 .8850110529
150 36.8849173664 .9436954032
200 40.4551201780 .9692561812
250 42.9567867921 .9828229050
300 44.6233194430 .9900053029
</code>
The first number is the cutoff value, the second is the average time to bankruptcy, and the third is the probability of bankruptcy.  It's starting to level off, and it's also starting to take a few minutes to run.  I'll try to run it overnight with large cutoffs, and let you know what happens tomorrow.
EDIT
Since I first posted this, I realized that there were a lot of superfluous states in my original script.  For example, with $M=100$, a player who wins $54$ games and loses $46$   does not go bankrupt, so once a player wins $54$ games, we know he will not go broke.  To compute the number of steps to absorption correctly, we just keep track of the number of games such players have played.  When $M=100$, this reduced the number of transient states from $2488$ to $1453$.  Of course, we could compute the average time to bankruptcy, by eliminating the cutoff state, and forcing players to go bankrupt, so that any player with $53$ wins would lose from then on.  This would reduce the number of transient states, by another $46$, but it would not allow computation of the probability of bankruptcy, which is nice to know.  The script below is the revised one.
Here's my script, if you want to check it, which I would appreciate.
<code>'''
Player starts with bankroll of $100.  A fair coin is tossed;
if it comes up heads, bankroll increases by 50%.  If tails,
bankroll decreases by 40%.  Game ends if bankroll is less
than $1, or after M plays.  What is the expected time
to bankruptcy?

In order to economize on the number of states, we compute
the number of wins W that will ensure the player from going
broke.  Once a player has W wins, we only track how many
games he's played.

Usage: python bankrupt.py M
'''
import numpy as np
from scipy import linalg
from sys import argv
import math
from resource import getrusage, RUSAGE_SELF

def bankrupt(state):
    win, lose = state
    if lose - win >= 5: return True
    return (3/2)**win * (3/5)**lose < 1/10

def maxWins(M):
    # player with this may wins won't go broke in M rolls
    alpha = math.log(3/2)
    beta = math.log(3/5)
    gamma = math.log(1/10)
    return math.ceil((gamma-beta*M)/(alpha-beta))

def test(M):
    count = 0
    states = []
    index = { }
    W = maxWins(M)

    for wins in range(W):
        for losses in range(M-wins):
            state = (wins, losses)
            if bankrupt(state):
                index[state] =-1
            else:
                states.append(state)
                index[state] = count
                count += 1
    for s in range(W, M):
        states.append((s,0))
        index[s,0] = count
        count += 1

    S = len(states)
    P = np.zeros((S+2, S+2))
    for i, (wins, losses) in enumerate(states):
        if W <= wins < M-1:
            P[i, index[wins+1,0]] = 1
            continue
        if wins == M-1:
            P[i, S+1] = 1
            continue
        w = (wins+1, losses)
        if wins == W-1 and sum(w) < M:
            P[i, index[W+losses,0]] = .5
        elif sum(w)== M:
            P[i,S+1] = .5
        else:
            P[i,index[w]] = .5
        loss = (wins, losses+1)
        if sum(loss)== M:
            # bankruptcy on roll N
            # counts as a bankruptcy
            if bankrupt(loss):
                P[i,S] = .5
            else:
                 #stop whether a win or a loss
                P[i,S+1] = 1
        else:
            idx = index[loss]
            if idx == -1:
                P[i, S] = .5
            else:
                P[i, idx] = .5

    R = P[:S, S:]
    P = np.eye(S) - P[:S, :S]
    N = linalg.inv(P)   # fundamental matrix
    MEG =1024**2
    print(f"{S} states, {getrusage(RUSAGE_SELF)[2]//MEG} MB")

    # Expected time to absorption is sum of first row
    steps = sum(N[0,:])

    # Probability of N rolls is the (0,1) element of NR
    stop = N[0,:] @ R[:, 1]

    answer = (steps - M*stop)/(1-stop)
    return answer, 1-stop

M = int(argv[1])
steps, prob = test(M)
print(M, steps, prob)
</code>
Answer: Unless otherwise specified, if we are asked if something is a good bet we answer in terms of expected value.  If the expected value of the payoff is greater than the bet, we say it is good.  That is fine when you will play the game lots of times, so the law of large numbers kicks in and you confidently expect that much profit.  It is also fine for a small number of plays where the stake is not enough to change your life.  Being one dollar richer than you are now is probably about as nice as being one dollar poorer is bad.  When the stake becomes meaningful, at the extreme when it involves bankruptcy, the linear approximation is not a good one.  Losing all your money is a lot worse than doubling your money is good.  When people propose a bet where bankruptcy is one of the possible outcomes and say it is unconscionable, they are asking the wrong question.  They should define a utility function to be maximized, then we can take the expected value of that function and see if it is a good bet or not.
One utility function I have seen is the log of your money.  That has the nice properties of making bankruptcy infinitely bad and being convex upward so that increases in your fortune become progressively less interesting than losses, both of which are in accord with many people's perception.  Of course many other functions satisfy these two conditions, but logs are nice because they are easy to compute with.  In the case of this problem, a head adds $\log 1.5 \approx 0.405$ while tails adds $\log 0.6 \approx -.511$.  If this is your utility function, this is a bad bet each time.


Javascript Object.defineProperty() for newebies

Question: I need to create a property of an element with no id. Here's what i mean:
var createdElement = document.createElement('div');
Object.defineProperty(createdElement, 'id', 'someId');

Comment: You haven't actually asked a question. Are you looking for a tutorial? Is there a specific thing you've tried to accomplish that hasn't worked? If so, how?
Comment: Take a look at [the documentation](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty): if you're using defineProperty you need to pass a descriptor object (`{value: x, enumerable: true}`), not just the property value. If you just want to set the property value, you can do a standard property assignment (`x.y = z`).
Answer: Strictly responding to your question, the way you used is malformed. Should be something like this:
var createdElement = document.createElement('div');
Object.defineProperty(createdElement, 'id', {
  value:'someId',
  enumerable: true,
  writable: true
});

That's said, it's a totally weird way to achieve what you want. You can simply do:
var createdElement = document.createElement('div');
createdElement.id = 'someId';

Answer: First Way
You can do this using .createElement() from Javascript. So you dont need Object.defineProperty().
Here it is at use:
var btn = document.createElement("BUTTON");
btn.setAttribute("id", "uniqueIdentifier");

Second Way
You can also set ID by the .Id() like this for example:
HTML

JS
var abcElements = document.querySelectorAll('.abc');

// Set their ids
for (var i = 0; i < abcElements.length; i++){
    abcElements[i].id = 'abc-' + i;
}

This will assign the ID 'abc-' to each element. So it would come out like this:

Comments on your Question
By the way learn to write a better topic title here.
Comment: `var = ` is invalid JavaScript.
Comment: the negativity of ones and the helpfulness of others. thanks
Comment: No Problem @Toffer any time!
Comment: Using `setAttribute` is odd. Just assigning to properties (if available, like `.id` is in this case) is the best practice.
Comment: @Gary Missed it there sorry
Comment: @Toffer Edited the anwser, take a look at the other way that Bergi Proposed!


Adding onClick function to select elements

Question: I have a select tag of dynamically added elements. I need to add an event listener to each of the elements in the select tag except the first which:
adds the text of the element to a list,
makes the focus of the list the first element again, and
removes or hides the clicked element.
The first element is a 'none' element which doesn't need any event listener.
I've tried something like
for (var i = 0; i < array.length; i++)
{
    var name = array[i];
    var selectElement = document.getElementById(selectElementId);

    addToSelectNode(document.getElementById(selectElementId), name);

    var thisNode = selectElement.childNodes[i];

    if (thisNode.value != "none")
    {
        thisNode.addEventListener("click", function(event)
        {
            appendNodeToList("artist-list", i);
            selectElement.selectedIndex = 0;
            selectElement.remove(selectElement.i);
            selectElement.style.display = "none";
        });
    }
}

function addToSelectNode(element, optionText)
{
    var newSelectElement = document.createElement("option");
    newSelectElement.text = optionText;
    element.add(newSelectElement);
}

function appendNodeToList(listId, text)
{
    var newNode = document.createElement("LI");
    var textNode = document.createTextNode(text);
    newNode.appendChild(textNode);
    document.getElementById(listId).appendChild(newNode);
}

Didn't work at all though
Comment: I'd recomment you using some framework, most probably VueJS, for that
Comment: please add [Minimal, Complete and verifiable example](https://stackoverflow.com/help/mcve) with you codes and errors
Answer: A few hours later I've solved my own question. The problem stemmed from trying to remove items in the select tag which just wasn't working - I'm nut sure if it's possible but making it disabled solved it. Anyway here's the result.
HTML:
<select id="artist-select-list">
            <option value="none">none</option>
</select>

JavaScript:
window.onload = function()
{
    var dropdown = document.getElementById("sampleDropdown");
    var n = array.length;

    // Loop to add to <select> dropdown
    for (var i = 1; i <= n; i++)
    {
        addToSelectNode(dropdown, array[i - 1]);
    }

    // Loop to add id's to each element in the dropdown
    for (var i = 0; i <= n; i++)
    {
        dropdown[i].id = "selectNum" + i;
    }

    // Loop to add event listener
    for (var i = 0; i < dropdown.length; i++)
    {
        dropdown[i].addEventListener("click", function(event)
        {
            // Regardless of which option the user clicks move shown option to "none" (first index in dropdown)
            dropdown.selectedIndex = 0;

            if (event.target.id != "selectNum0")
            {
                // Disable once clicked
                event.target.disabled = true;

                // Do other things here in relation to event.target
            }
        });
    }
}

var array =
[
    "sampleText1", "sampleText2"
];

function addToSelectNode(element, optionText)
{
    var newSelectElement = document.createElement("option");
    newSelectElement.text = optionText;
    element.add(newSelectElement);
}


tags salvas no bd sendo impressas como texto

Question: Olá, estou imprimindo um valor salvo em um campo text do mysql, que contém tags 'p' em sua composição, o problema é que ele está imprimindo essas tags como texto e não como html, alguém sabe qual seria o problema? Estou usando angular para imprimir os valores do banco.
Answer: Utilize a diretiva ng-bind-html para exibir conteúdo HTML:

Caso o serviço $sce esteja ativado, será necessário marcar o conteúdo HTML como confiável. Neste caso, implemente um filtro que será concatenado ao pipeline:

var app = angular.module('sampleApp', []);

app
.filter('trustAs', function($sce) {
        return function (input, type) {
            if (typeof input === "string") {
                return $sce.trustAs(type || 'html', input);
            }
            return "";
        };
    })
.controller('SampleController', function ($scope) {
  $scope.variavel ='teste de HTML';
});

Fontes:
ngBindHtml - AngularJS directive components
https://stackoverflow.com/questions/19415394/with-ng-bind-html-unsafe-removed-how-do-i-inject-html
Comment: Isso aí, deu certo. Eu não estava conseguindo fazer funcionar aqui pois tenho o $sce ativado e não sabia que tinha que fazer todo esse código.
Comment: @BernardoKowacic na verdade o filtro só precisa ser definido uma vez, e pode ser reutilizado em outras partes do código. Fico feliz que tenha funcionado!


Getting info from an external database - Base table or view not found

Question: Currently working on getting some info from an external application's database onto my user profile page as a test.
I've run into a snag that I can't seem to get past. This is probably something so simple, but I'm pulling my hair out over it.
I have 2 databases - one is Drupal, and the other is from SocialEngine. These are both hosted on the same server(not localhost).
My error is this: Base table or view not found: 1146 Table 'uitv.engine4_users' doesn't exist: SELECT email FROM {engine4_users} WHERE enabled = :enabled; Array ( [:enabled] => 1 )
Awesome. Okay, well I think I can see the issue here... engine4_users is actually in the uitv_social database, while my Drupal installation is in the 'uitv' database. I've used db_set_active($social); which relates to my database settings in settings.php - and I've set it back to the default database after I query the social one.
What am I missing here? (Drupal 7 database documentation seems to be blank on this subject)
[EDIT: I did something silly - use db_set_active('yourdbkey'); - and make sure your query is right. Hope this helps a Googler. Curiously, I had done this several times before, but since the query was incorrect it wasn't giving me anything, obviously.]
Comment: Can you write your solution up as an answer and accept it, so that the question is marked as resolved. Alternatively, you could also close it.
Answer: I know you answered your own question with a solution -- here is additional info.
The helper functions db_select(), db_update(), db_insert(), db_merge() all use the default database connection defined in settings.php. As you pointed out you can use db_set_active() to set an active database within a given scope of code. I personally dont like this approach, because X months from writing the code you will forget that, "oooohhh I used db_set_active X lines above" and run into annoying maintenance issues.
There is another solution, dont simply use the helper db functions. Use their parent Objects, which they are wrapping ... as in below:
<code>    // 'remote_database' is a 2nd db connection defined in settings.php
    $query = Database::getConnection('default', 'remote_database')->select('survey_item', 'si');
$query->fields('si', array('item_id', 'presentation_order', 'question_type', 'stem', 'choice_1','choice_2', 'choice_3', 'choice_4', 'choice_5', 'choice_6', 'choice_7', 'choice_8'));
$query->condition('survey_id', $current_row->survey_id);
$query->orderBy('presentation_order', 'ASC');
$current_row->form_items = $query->execute()->fetchAll();
</code>
So you can create a Query as I have above by specifying the connection first. You may do this for all ->select() or ->update() or ->insert() functions which drupal supplies wrappers for.
Or, you can even pass as a 3rd argument to a SelectQuery() constructor the connection to use for the query, see the docs here:
http://api.drupal.org/api/drupal/includes--database--select.inc/class/SelectQuery/7
<code>  // This is the constructor for SelectQuery() from select.inc
  public function __construct($table, $alias = NULL, DatabaseConnection $connection, $options = array()) {
$options['return'] = Database::RETURN_STATEMENT;
parent::__construct($connection, $options);
$this->where = new DatabaseCondition('AND');
$this->having = new DatabaseCondition('AND');
$this->addJoin(NULL, $table, $alias);
</code>
}
So you can also start a db_select() query as follows to tie it to a non default connection in another means:
<code>$query = new SelectQuery('my_table', 'table_alias', Database::getConnection('default', 'remote_database'));
// other things you build onto your query
// $query->addJoins(...); $query->fields(...); ...
return $query->execute()->fetchAll();
</code>
So in a nutshell -- the db helper functions are convenience when talking to 1 database. Beyond that, you can specify per-query what connection to use ... if you like more fine control of your queries and not use db_set_active() all over the place.


Power BI - DAX - ADDCOLUMNS - Syntax Error - Invalid token, Line 3, Offset 2,

Question: This is from the Coursera Power BI course.  I'm trying to create a create a "Sales in USD" calculated table.  I was instructed to select a New Table in Power BI and type the following:
Sales in USD =
     ADDCOLUMNS(
        Sales,
        "Country Name", RELATED(Countries[Country]),
        "Exchange Rate", RELATED('Exchange Data'[Exchange Rate]),
        "Exchange Currency", RELATED('Exchange Data'[Exchange Currency]),
        "Gross Revenue USD", [Gross Revenue] * RELATED('Exchange Data'[Exchange Rate]),
        "Net Revenue USD", [Net Revenue] * RELATED('Exchange Data'[Exchange Rate]),
        "Total Tax USD", [Total Tax] * RELATED('Exchange Data'[Exchange Rate])
    )

It generated "The following syntax error occurred during parsing: Invalid token, Line 3, Offset 2,  ."
I've looked online for how the ADDCOLUMNS function is used, and the code above seemed to comport with the explanations that I read online.
What am I - I mean Coursera - doing wrong?
Answer: I'm trying to get this same script in the Coursera's final project to work too and it won't.  This isn't the first time the code or files I downloaded for this course don't work, but in the second half of this project they make us create measures based on this table, so it's hard to skip around this.
I got mine to work.  You need to fix the squiggly red lines because the syntax for the tables aren't named right.  Look at mine:
Sales in USD =
ADDCOLUMNS(
    Sales,
    "Country Name", RELATED(Countries[Country]),
    "Exchange Rate", RELATED('Exchange Data'[ExchangeRate]),
    "Exchange Currency", RELATED('Exchange Data'[Exchange Currency]),
    "Gross Revenue USD", [Gross Revenue] * RELATED('Exchange Data'[ExchangeRate]),
    "Net Revenue USD", [Net Revenue] * RELATED('Exchange Data'[ExchangeRate]),
    "Total Tax USD", [Total Tax] * RELATED('Exchange Data'[ExchangeRate])
)

Mine is fine now.
Answer: I suspect some of the quotes and apostrophes may be "dirty" or there are some invisible whitespace characters. This happens sometimes when copying/pasting code from websites.
Try copying/pasting the below or from your question.
Sales in USD =
  ADDCOLUMNS(
    Sales,
    "Country Name", RELATED(Countries[Country]),
    "Exchange Rate", RELATED('Exchange Data'[Exchange Rate]),
    "Exchange Currency", RELATED('Exchange Data'[Exchange Currency]),
    "Gross Revenue USD", [Gross Revenue] * RELATED('Exchange Data'[Exchange Rate]),
    "Net Revenue USD", [Net Revenue] * RELATED('Exchange Data'[Exchange Rate]),
    "Total Tax USD", [Total Tax] * RELATED('Exchange Data'[Exchange Rate])
  )

If that doesn't work, then please update your question with a screen grab of your expression in Power BI. The wavy red-underlines should hopefully help identity the culprit.


Laravel - Session e Array

Question: Estou precisando fazer criar um array:
array(
   0 => 0,
   1 => 0,
   2 => 1,
   3 => 0,
   4 => 0,
   5 => 1,
   6 => 0)

dentro de um session:
session('session_array')

e depois adicionar e resgatar individualmente os valores de acordo com cada key do array. Como faço isso? Não consegui entender muito bem vendo a documentação do laravel.
Answer: Caso você esteja utilizando o Laravel 4
A sessão é criada da seguinte forma:
Session::put('key',['um','dois']);

para exibir os dados Session::get('key.um')
Para o laravel 5
para criar
session()->put('key','value');

para exibir
session()->get('key');

Answer: Se você quer adicionar esses array em uma valor da sessão onde você já tinha inserido agum dado, a melhor forma seria usar o método push
session()->put('session_array', 1);

session->push('session_array', 2);

session->push('session_array', 2);

var_dump(session('session_array')); // [1, 2, 3]

Você também pode definir o array diretamente na key específica:
session()->put('session_array', $array)

Você também pode acessar definir valores através da notação por ponto:
 session('session_array.nome', 'Wallace');
 session('session_array.1', 10);
 session('session_array.2', 20);

Alternativamente você também pode definir um array diretamente:
session(['session_array' => [1, 2, 3, 4, 5]);

Para pegar os valores, você pode fazer das seguintes forma:
  //equivale a $_SESSION['session_array']['name']

 session('session_array.name');

 session('session_array.1');

Comment: `session('session_array.name')` está retornando o array todo.
Comment: Nesse caso, você deve ter definido o `array` nele todo.
Comment: Ele está retornando: `Array ( [0] => 1 [1] => 1 [2] => 1 [3] => 1 [4] => 1 [5] => 1)`

Laravel - Session e Array


Two large decreses in loss function with ADAM optimizer

Question: I am training an RNN with tensorflow using the ADAM optimizer. The loss with respect to iteration has a sort of "two stage" decrease. As shown in the image below.

The task itself if just trying to regress time series data with the squared difference loss. I half the learning rate every 3000 iterations, but the above is over ~2000 so the learning rate is constant. The batch size is 16 (GPU limitation), and initial learning rate is 0.0005.
What could the cause of these "two stages" be? I have seen this loss over time in papers before, but there usually isn't an explanation. Could it be getting out of a saddle point, or an artifact of the optimizer?
Answer: The two regimes of behavior probably reflect a saddle point, or a region of the parameter space that is just very shallow.  This image gives a nice conceptual illustration.

Adaptive learning rates and momentum allow the optimizer to escape a region with a shallow gradient or saddle point. Quickly adapting to changing curvature is the goal of methods like adam, but some recent research has found that the gains due to Adam are marginal ("The Marginal Value of Adaptive Gradient Methods in Machine Learning" by Ashia C. Wilson, Rebecca Roelofs, Mitchell Stern, Nathan Srebro, Benjamin Recht).
This can also happen if you're reducing the learning rate at the particular epoch where the drop happens. But since you don't mention that you're specifically doing this, it's probably due to a saddle point.


Where can I find custom content type templates file?

Question: Sorry for ask this easy question, I know the net its full of tutorials, but the info is a bit confusing since they are always showing the diference between D7 and D8 (i didn't use a CMS before so it is not helpfull enough)
My "news" custom content displays itself without classes, with the title of every field in the content and I want to modify the creation template.
Am I allowed to do that? or its supposed to reach this goal through other way?.
Thanks in advance
Comment: Which Drupal version are you using?
Comment: @NoSssweat D8 ofc
Answer: It's all in here Twig Template naming conventions
Nodes
Pattern: node--[type|nodeid]--[viewmode].html.twig
Base template: node.html.twig (base location: core/modules/node/templates/node.html.twig)

Theme hook suggestions are made based on these factors, listed from the most specific template to the least. Drupal will use the most specific template it finds:

1. node--nodeid--viewmode.html.twig
2. node--nodeid.html.twig
3. node--type--viewmode.html.twig
4. node--type.html.twig
5. node--viewmode.html.twig
6. node.html.twig
Note that underscores in a content type's machine name are replaced by hyphens.

The higher the number the less specific, For example, the last one (6) it affects everything.
While (1) affects a specific node with a specific view mode, Ex: node--1--teaser.html.twig will only affect /node/1 with teaser view.
For your case, you want to use (4), so in your case, its node--news.html.twig
Answer: I suppose that you want to create custom template for the content type. To do this create a file called "node--content-type-name.html.twig". And save this file in your theme's template directory.
Then in this template file define the html structure. Type the field name which you want to display in your template like {{ content.field_name }}.
To find the field name just goto content type -> manage fields, there you will find the machine name of that particular field.
 P.S : This solution is for Drupal 8
Comment: Yes, it'll be like  {{ content.field_name }}
Comment: Thank you Sachin, but to clear up things. It can be for example:

Comment: Guess its more like  {{content.news-header}}


IIS Digest Authentication against multiple domains

Question: How do I authenticate across multiple (AD) domains on IIS 6 using digest authentication?  Is the domain that the server resides on the only authenticate-able domain?
Answer: While MS documentation isnt particularly clear in this point, making some search we see on Autentification Methods on IIS:

It connects to a DC for validating the user and pass on both methods, but digest uses MD5 to send user and pass (¡Problem of security!)

So, if you look for integrated method, there's posts where explains that multidomain access is correct if you have a trust relationship between those domains. MultiDomain IIS
I think we can suppose that Multidomain works with digest method with trust relations between domains, based on MS info
Question: Can't you switch to integrated to use Kerberos and improve security? MD5 is quite easy to crack.
Hope this helps.


Doctrine : Lazy loading properties

Question: It looks like when I forget to put leftJoin in my queries, Doctrine will lazy-load relations after I pick them. Ie if I do something like:
<code>$property = PropertyTable::getInstance()->createQuery('o')
  ->leftJoin('o.Features f')
  ->execute() ;
</code>
I will still be able to access $property->Attraction , even if I didn't load them in this query. So I guess Doctrine does it internally by calling another 'SELECT'. Is there a way to prevent this auto-loading by throwing some exception? This would help me create better and faster queries.
Answer: Have you looked at the actual sql it produces?
Try <code>->getSql()</code>. It is likely it is doing another query when you attempt to access a related field.
If you want to avoid that, don't access related fields!
Comment: Yes, I have tried that and no, it doesn't load Attraction's. But I am able to access them via $property->Attraction . I would like some exception thrown so I can't make a mistake when I write a query. As I make really big programs, it is very easy to skip something like that.
Comment: I believe you can access them because it triggers a new query, and it is therefore intended behaviour. I think the solution here is not the change the machine, but to pay more attention to how you use the machine.
Comment: Yes, but the idea is to prevent auto-fetching. It is very easy to skip some join in quick-development of big programs.

Doctrine : Lazy loading properties