Android Room: How to Migrate Column Renaming?

Question: Issue
My app is crashing because I am not handling migration properly. I'm looking for a solution to migrate the name of 1 column in my table.
In my project I a have a room table named 'content' with a Double attribute 'archivedCount'. In the latest version of the app the attribute archivedCount attribute is re-named to dismissCount, still as type Double.
Original Content model
@Entity(tableName = "content")
data class Content(@PrimaryKey var id: String, var archiveCount: Double) : Parcelable {...}

New Content model
@Entity(tableName = "content")
data class Content(@PrimaryKey var id: String, var dismissCount: Double) : Parcelable {...}

Attempted Solution
After reading a Google Developer Advocate's explanation Understanding migrations with Room, I attempted her solution outlined in the post's section Migrations with complex schema changes which entails making a copy of the original table, deleting the old table, then renaming the newly created table.
With the following approach below there is a runtime error on this line: database.execSQL("INSERT INTO content_new (id, dismissCount) SELECT id, archiveCount FROM users"); because I already cleared my app's cache so the old table no longer exists.
Can I update a single column without re-creating the entire table?
static final Migration MIGRATION_1_2 = new Migration(1, 2) {
@Override
public void migrate(SupportSQLiteDatabase database) {
    // Create the new table
    database.execSQL(
            "CREATE TABLE content_new (id TEXT, dismissCount REAL, PRIMARY KEY(id))");
    // Copy the data
    database.execSQL("INSERT INTO content_new (id, dismissCount) SELECT id, archiveCount FROM users");
    // Remove the old table
    database.execSQL("DROP TABLE content");
    // Change the table name to the correct one
    database.execSQL("ALTER TABLE content_new RENAME TO content");
  }
};

Comment: Have you read [this](https://stackoverflow.com/questions/805363/how-do-i-rename-a-column-in-a-sqlite-database-table)?
Comment: Stop putting single quotes around your table and column names.
Comment: What does IntelliJ have to do with this?  What _SQLite_ errors are you still getting?
Comment: @TimBiegeleisen IntelliJ is showing a warning that it is not a valid SQL command. **COLUM** is higlighted in red and it says *TO expected, got 'COLUMN'* This is the specific error I'm receiving in runtime which causes the crash: `android.database.sqlite.SQLiteException: near "COLUMN": syntax error (code 1 SQLITE_ERROR): , while compiling: ALTER TABLE content RENAME COLUMN archiveCount TO dismissCount`
Comment: Yeah...that's what I was going to say.  You may have to drop and recreate the table in your case.  By the way, for future reference for a question like this, please tell us your SQLite version in the question.
Comment: I know this is an older question, but as of November 2020, this is still 100% not doable with the current room db logic. You cannot rename a column since the SQLite version is not up to 3.25 and until that point you need to create a new table, copy the table data, drop the old table, and rename the new table. It's extremely tedious, but it's the only working way that isn't a hack like renaming the serialized vars.
Comment: Thank you @TimBiegeleisen. How would I format the SQL command as the post doesn't provide an example. I'm trying this, but the IDE does not like the syntax: `database.execSQL("ALTER TABLE 'content' RENAME COLUMN 'archiveCount' TO 'dismissCount'")`. Is it possible my syntax is correct,  and IntelliJ just has not updated to this new rule?
Comment: It turns out my syntax in the comment above causes a crash. How would I format this new SQL action? `android.database.sqlite.SQLiteException: near "COLUMN": syntax error (code 1 SQLITE_ERROR): , while compiling: ALTER TABLE 'content' RENAME COLUMN 'archiveCount' TO 'dismissCount'`
Comment: @TimBiegeleisen I removed the quotes within the command `database.execSQL("ALTER TABLE content RENAME COLUMN archiveCount TO dismissCount")`. IntelliJ still does not like the syntax.
Comment: What version of SQLite are you using?
Comment: The API I'm on uses **3.19**. From your link it looks like I'll have to wait until they update to **3.25**.
Comment: Will do! May you upvote as this is going to be a common issue for developers on Android once Room is adopted more widely.
Comment: Does this answer your question? [How do I rename a column in a SQLite database table?](https://stackoverflow.com/questions/805363/how-do-i-rename-a-column-in-a-sqlite-database-table)
Answer: Solution
Thanks to the guidance from @TimBiegeleisen we discovered that the Android implementation of SQLite 3.19 for API 27 and 28 has not yet upgraded to the version 3.25 SQLite which allows this feature outlined in this StackOverflow post.
Once Android upgrades a command such as this to alter a table column will be possible: database.execSQL("ALTER TABLE content RENAME COLUMN archiveCount TO dismissCount")
Comment: Is it still not there in SQLite?

I have written this:
database.execSQL("ALTER TABLE Expense RENAME COLUMN price TO amount");

Getting an error
android.database.sqlite.SQLiteException: near "COLUMN": syntax error (code 1 SQLITE_ERROR): , while compiling: ALTER TABLE Expense RENAME COLUMN price TO amount

And also I get hint at that line: got COLUMN, expected TO
Comment: It really needs to be noted that this does not work on Android devices that are not using SQLite 3.25, which at the time of this comment is **ALL** of them, so this answer is not correct as of 2020-11-11. The only solution I have found is to use the logic to create a new table, copy over the data, drop the old table, and rename the new table.
Answer: There is a solution without migration - use ColumnInfo:
data class Content(@PrimaryKey var id: String,  @ColumnInfo(name = "archiveCount") var dismissCount: Double) : Parcelable{...}

Database column will be still archiveCount, but in Kotlin property will be renamed.
Comment: Thanks @atarasenki, this is a nice workaround. However, it does not solve the root of the issue and is more of a "band aid" type solution.


Wildcards in Virtual Hosts with dynamic logs?

Question: My Apache Virtual Hosts config currently has several repeats of this;
<VirtualHost *:80>
    ServerName example1.com
    ServerAlias www.example1.com

    DocumentRoot /home/example1.com/www

    LogLevel warn
    ErrorLog /home/example1.com/logs/error.log
    CustomLog /home/example1.com/logs/access.log combined

    Alias /dev /home/example1.com/dev
    ScriptAlias /cgi-bin/ /home/example1.com/cgi-bin
</VirtualHost>

How would one go about changing that so all the 'example1.com' instances are replaced with whatever domain the user is currently viewing?
I know of mod_vhost_alias, but I don't see any mention of it being able to do logs or alias (aside from ScriptAlias) dynamically as well. Is there some way to accomplish that? I'd rather not sacrifice separate logs for this.
Answer: You could probably solve the alias with a mod_rewrite rule:
# get the server name from the Host: header
UseCanonicalName Off

# remove www.
RewriteCond %{HTTP_HOST} ^www\.(.*)$
RewriteRule .? - [E=noWWWHost:%1]

# map /dev  to the documentroot for dev
RewriteCond %{REQUEST_URI} !^/~
RewriteCond %{HTTP_HOST} ^www\.
RewriteRule ^/dev/(.*)$ /home/${lowercase:%{ENV:noWWWHost}}/dev/$1

# not using www
RewriteCond %{REQUEST_URI} !^/~
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^/dev/(.*)$ /home/${lowercase:%{HTTP_HOST}}/dev/$1

# make a log that is "splitable" on host
LogFormat "%{Host}i %h %l %u %t \"%r\" %s %b" vcommon
CustomLog logs/access_log vcommon

Edit: Forgot to add that the config above is untested :)
Answer: You can use mod_vhost_alias and change the log format by adding %V (Effective server name) at the beginning of the line.
Then you just have to write a simple shell script or perl program that will parse the raw log and write it to the relevant log file. You can even do it in real time using a piped log: CustomLog "|/path/to/script.pl" combined_vhost
Answer: There are a couple of ways to go about this ... you can create a virtual host with a related log file for every host.  If you are looking for wild card matching it may be easier just to parse the logs later with the given hostname.
Comment: What about Alias? I know there is VirtualScriptAlias, but I don't see any Alias equivalent.


Writing a two variable function $f(x,t)$ in terms of Dirac-Delta $\delta(x)$ function and a function $P(t)$?

Question: How to write a two variable function $f(x,t)$  in terms of Dirac-Delta $\delta(x)$ function and a function $P(t)$?
For example;
I read something in a book. You can find the following picture.
But I don' t understand the logic behind this. Could you explain it?
Comment: Crossposted to https://physics.stackexchange.com/q/487993/2451
Answer: They want a force density but don't have a smooth load. Instead they have a point load. To represent a point load as a force density one can use Dirac $\delta$. A point load $P$ at $x=g$ is represented as the force density $f(x) = P \, \delta(x-g).$
In the example they also have that both the force $P$ and the placement $g$ varies with time $t$. This makes also the force density $f$ depend on $t$. Thus we get
$$f(x,t) = P(t) \, \delta(x-g(t)).$$


maintenance-page--offline template not working

Question: I am following this tutorial. https://www.drupal.org/node/195435.
I have created maintenance page and its working with admin configuration site under maintenance setting. I want to create dboffline mode maintenance page. so for that, i have created another tpl "maintenance-page--offline" in same directory where "maintenance-page.tpl.php" has created. Path is like sites/all/theme/mytheme/templates/.
previously it was working but currently its showing me Additional uncaught exception thrown while handling exception. error. Its not overriding maintenance-page--offline when i am disconnecting DB, by entering wrong password in settings.php file.
Answer: This is caused when class_exists() is being called from within alpha_get_theme() and autoloading fails. I have a patch that fixes this by wrapping those calls in a try/catch block. I'm not quite sure what should be done in the case of an error though, so I have just done nothing.
See theme Omega issue => https://www.drupal.org/node/1722586
It is working for me, I had the same problem.


Need Regex for Comma followed by space then State Abbreviation

Question: I'm very new to regex and I'm trying to find instances of any of the following:
<code>", FL,"
" FL "
" FL,"
", FL "
</code>
where FL can be any US state abbreviation, upper or lower case. (I know some of the above probably overlap.)  Which leads me to the second part of my question:
How do I write regex code that searches for all of the above, and for every US state abbreviation?
(Why am I being asked to edit the question to be more specific?  What's the point of making two posts when both are very related to each other?  You may answer one or both questions if you wish. @The Fourth Bird)
Answer: Check this expression out:
<code>(?<!\w)(?:,\s+)?(?:A[LKZR]|C[AOT]|DE|FL|GA|HI|I[ADLN]|K[SY]|LA|M[EDAINSOT]|N[EVHJMYCD]|O[HKR]|PA|RI|S[CD]|T[NX]|UT|V[AT]|W[AIVY]),?\s?(?!\w)
</code>
Regex Demo
This expression is quite long, so let me explain by parts:
<code> (?<!\w)           # Make sure state not preceeded by text
 (?:,\s+)?         # Optionally match if followed by a , and several whitespace
 (?:A[LKZR]        # Start matching every combination of US state. Use -i flag to ignore case.
 |
  C[AOT]           # E.g. this will match CA/CO/CT
 |                 # or
  DE               # DE
 |                 # or
  FL               # etc...
 |
  GA
 |
  HI
 |
  I[ADLN]
 |
  K[SY]
 |
  LA
 |
  M[EDAINSOT]
 |
  N[EVHJMYCD]
 |
  O[HKR]
 |
  PA
 |
  RI
 |
  S[CD]
 |
  T[NX]
 |
  UT
 |
  V[AT]
 |
  W[AIVY])
 ,?               # Match if , at the end
 \s?              # Match if whitespace at the end (was in your examples)
 (?!\w)           # Make sure state is not succeeded by letters
</code>
Dont forget to set the -i flag, which will ignore letter case.
Comment: Figured it out.  Just add (?i) at the very beginning of the regex code.
Comment: I have two questions/comments: (1) Doesn't `(?:,\s+)?` require at least one space following the comma? So it only matches `',FL'` without `(?:,\s+)?` matching the `,` (the group was optional). Which means you will also match `FL` in `AFLCIO` and that can't be desirable. (2) Which state's abbreviation is  AE? Is this a territory? There are other "states" I don't recognize.
Comment: @RonaldAaronson Thank you for your comment, fixed both points.
Comment: @vs97 Thanks so much!!  I'm trying to figure out how to set the -i flag.  Can  you teach me how?
Comment: @mrphysics If you are using re.compile, then e.g. - re.compile(r'*expression-here*',
              re.I (capital i)). Also this answer might be useful - https://stackoverflow.com/questions/500864/case-insensitive-regular-expression-without-re-compile
Comment: @vs97 re.IGNORECASE doesn't work.  I have:
text = "...."
match = re.search(r'expression', text, re.IGNORECASE)
if match:
    text = text.replace(match.group(), '[State]')

The change is not made if I have something like New York, ny
Answer: /, (PA|FL|...)/i
I'll leave the remaining 48 states as an exercise for the reader ;)
Answer: <code>/(?: (?:A[KLRZ]|C[AOT]|D[CE]|FL|GA|HI|I[ADLN]|K[SY]|LA|M[ADEINOST]|N[CDEHJMVY]|O[HKR]|P[AR]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY])(?:,| ))|(?:, (?:A[KLRZ]|C[AOT]|D[CE]|FL|GA|HI|I[ADLN]|K[SY]|LA|M[ADEINOST]|N[CDEHJMVY]|O[HKR]|P[AR]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY])(?:,| ))/i
</code>


Theme a link with l - redirect to translated version

Question: I'd like to insert a link in my node templates that displays when viewing nodes of a particular type (news). That link should lead to the news archive (node/26). Node 26 is a normal drupal page made in swedish (with a menu item and so on). On that page a block is displayed with a viewed list of news items.
There is a translated version of node/26 - translated with normal multi language modules.
What I'd lite for the system is to redirect from node/26 to the english translated version (node/27) if the current users language is english.
I have the module Translation Redirect activated - but it does not redirect.
If a redirect can't be achieved - is there any way that the link function can create the link depending on what the current language is (preferably without if-cases for each language).
Version is Drupal 7.
Thank you very much for any replies!
Comment: Try `Internationalization` module
Answer: I ended up doing it this way:
$nodepath = "node/26";
$languagepaths = translation_path_get_translations($nodepath);
$currentlanguage = i18n_language()->language;
$path = $languagepaths[$currentlanguage];

if (preg_match('/^node/',$path)) {
    $path = "". drupal_get_path_alias($path, $currentlanguage);
} else {
   $path = $nodepath;
}

Answer: <?php
global $language;
$link = url('node/26',array('language' => $language));
?>
<a href="<?php print $link?>">My Page

credit to mojzis solution.
Comment: This should be the accepted answer.
Answer: according to the docs it should be enough to do something like this :
global $language;
$link = l('GO THERE','node/26',array('language' => $language));


How to calculate shipping cost based off by weight and distance?

Question: I am writing a package shipping program in my c++ class. I am supposed to prompt the user for weight, then prompt them for the distance the package is going, then calculate the shipping. I am struggling with calculating shipping. The shipping rate is a flat rate of $1.10 per each 500 miles or portion thereof, so what could I write that calculates the shipping of a package based off the distance and rate above?
<code>#include<iostream>

using std::cout;
using std::cin;
using std::endl;

double weight, distance;
const double twoOrLess = 1.10;
const double twoToSix = 2.20;
const double sixToTen = 3.70;
const double tenToTwenty = 4.80;

int main()
{
    cout << "Welcome to Shippers R Us!" << endl
         << "------------------------"  << endl;

    do
    {
        cout << "Package weight(in Kg, 0 to end): ";
        cin >> weight;

        while (weight < 0 || weight > 3000)
        {
            if (weight == 0)
            {
                break;
            }
            else if (weight < 0)
            {
                cout << "weight must be greater than zero." << endl;
                cout << "------------------------" << endl;
                cout << "Package weight(in Kg, 0 to end): ";
                cin  >> weight;
            }
            else if (weight > 20)
            {
                cout << "We do not ship iteams weighing more than 20 kilograms." << endl;
                cout << "------------------------" << endl;
                cout << "Package weight(in Kg, 0 to end): ";
                cin >> weight;
            }
        }

        if (weight == 0)
        {
            break;
        }

        cout << "Distance(in miles): ";
        cin >> distance;

        while (distance < 10 || distance > 3000)
        {
            if (distance < 10)
            {
                cout << "Distance must be between 10 and 3,000 miles." <<
                endl << "Distance(in miles): ";
                cin >> distance;
            }
        }
        // This is where I need to calculate shipping
    } while (weight != 0);
    return(0);
}
</code>
Comment: That's an interesting question. Is the distance supposed to be handled in blocks of 500? You'll need to make this brutally clear in the question otherwise people will leap to the more obvious solution.
Comment: Anyway, you have a math problem, not a programming problem, at this point, so forget about the code. How would you handle this if you had a pen and a piece of paper and someone shouting numbers at you to process? Start your solution there. It may not be optimal, but it gets you started. You'll find a lot of computer problems can be solved the same way the human would solve them, and often that solution is fast enough.
Comment: You can use a percentage here. If the user enters `300` miles then, `(300 / 500) * 1.10` will give you `$0.66` to ship their package. If they enter `1000` miles then, `(1000 / 500) * 1.10` will give you `$2.20` to ship their package.
Comment: *"I am struggling with calculating shipping."* -- good, you know what to focus on. Now make your **example** code focus on this part. We are not grading your assignment, so we have no need to see your full program. Strip out the fluff I/O. Hardcode example values, such as `double weight = 2.4; // Would be user input` and `double distance = 42.3; // Would  be user input`. How focused does your code become when you get rid of the I/O and error checking?
Comment: But that will not give the same answer if the user enters something like 644? I need it to print the $1.10 price for every 500 miles, so if the user entered 644 I need it to calculate it to be $2.20 for shipping because it is 1.10 for every 500 miles
Comment: Yes the distance is handled in blocks of 500s, so miles between 0 and 500 would equal $1.10 and then miles 501-1000 would equal $2.20 and so on
Comment: The idiotic approach is subtraction in a loop. You can perform integer division and add 1, but you have to guard against the edge cases (eg 500 / 500 +1 = 2. Ooops).
Answer:
The shipping rate is $1.10 per 500 miles

I'm not sure if this is what you mean but, you can divide the distance by 500, and then multiply that by the shipping rate, for instance if the distance is 500, that divided by 500 is 1 times 1.10 would be the price.
therefore
<code>price = (distance/500)*1.10;
</code>
Comment: But that will not give the same answer if the user enters something like 644? I need it to print the $1.10 price for every 500 miles, so if the user entered 644 I need it to calculate it to be $2.20 for shipping because it is 1.10 for every 500 miles
Comment: multiplier = (distance-(distance%500))/500;
if(distance%500)
    multiplier = multiplier+1;
price = multiplier * 1.10


Integral with a fixed parameter

Question: For a parameter $a\ge 1$
How to calculate

$$\int_0^1 \frac{2\sqrt2}{(\sqrt2+1)(1-u^2)+2au}\ du$$?

I note $p(u) = (\sqrt{2}+1)(1-u^2)+2au$
The roots of $p$ are
$$u=\frac{-2a-2\sqrt{a^2+(\sqrt2+1)^2}}{-2(\sqrt2+1)}=\frac{-a-\sqrt{a^2+(\sqrt2+1)^2}}{-(\sqrt2+1)}=\frac{-a-\sqrt{a^2+2\sqrt2+3}}{-(\sqrt2+1)}$$
and
$$u=\frac{-2a+2\sqrt{a^2+(\sqrt2+1)^2}}{-2(\sqrt2+1)}=\frac{-a+\sqrt{a^2+(\sqrt2+1)^2}}{-(\sqrt2+1)}=\frac{-a+\sqrt{a^2+2\sqrt2+3}}{-(\sqrt2+1)}$$
So
$$\begin{align*}\frac{1}{(\sqrt2+1)(1-u^2)+2au}
&=\frac{1}{-(\sqrt2+1)\left(u-\frac{-a-\sqrt{a^2+2\sqrt2+3}}{-(\sqrt2+1)}\right)\left(u-\frac{-a+\sqrt{a^2+2\sqrt2+3}}{-(\sqrt2+1)}\right)}\\
&=\frac{1-\sqrt{2}}{\left(u-\frac{-a-\sqrt{a^2+2\sqrt2+3}}{-(\sqrt2+1)}\right)\left(u-\frac{-a+\sqrt{a^2+2\sqrt2+3}}{-(\sqrt2+1)}\right)}\\
&=\frac{1-\sqrt{2}}{\left(u+\frac{-a-\sqrt{a^2+2\sqrt2+3}}{(\sqrt2+1)}\right)\left(u+\frac{-a+\sqrt{a^2+2\sqrt2+3}}{(\sqrt2+1)}\right)}\\
&=\frac{2a}{u+\frac{-a-\sqrt{a^2+2\sqrt2+3}}{(\sqrt2+1)}}+\frac{2a}{u+\frac{-a+\sqrt{a^2+2\sqrt2+3}}{(\sqrt2+1)}}\end{align*}$$
What I wrote is it right? and how can I continue?
Thanks
Comment: i changed the title?
Answer: Some Preliminary Steps:
$\require{amsmath}$
$\DeclareMathOperator\arctanh{arctanh}$
$$\begin{aligned}
&(\sqrt2+1)(1-u^2)+2au=-(\sqrt2+1)\left(u^2-\frac{2au}{\sqrt2+1}-1\right)=\\&-(\sqrt2+1)\left(u^2-\frac{2au}{\sqrt2+1}+\frac{a^2}{(\sqrt2+1)^2}-\left(1+\frac{a^2}{(\sqrt2+1)^2}\right)\right)=\\&-(\sqrt2+1)\left(\left(u-\frac{a}{\sqrt2+1}\right)^2-\left(1+\frac{a^2}{(\sqrt2+1)^2}\right)\right)=\\&-(\sqrt2+1)\left(1+\frac{a^2}{(\sqrt2+1)^2}\right)\left(\left(\frac{(\sqrt{2}+1)u-a}{\sqrt{a^2+2\sqrt2+3}}\right)^2-1\right).
\end{aligned}$$

Your integral can now be expressed as:
$$-\frac{2\sqrt2(\sqrt2+1)}{a^2+2\sqrt2+3}\operatorname{\LARGE\int}\frac{1}{\left(\frac{(\sqrt{2}+1)u-a}{\sqrt{a^2+2\sqrt2+3}}\right)^2-1}\,du.$$
Let
$$\begin{aligned}
& s =\frac{(\sqrt{2}+1)u-a}{\sqrt{a^2+2\sqrt2+3}}\\
& ds=\frac{\sqrt{2}+1}{\sqrt{a^2+2 \sqrt{2}+3}}\,du
\end{aligned}$$
and by substituting for $s$, the integral becomes
$$\frac{2\sqrt2}{\sqrt{a^2+2\sqrt2+3}}\operatorname{\LARGE\int}\frac{1}{1-s^2}\,ds=\frac{2\sqrt2\,\arctanh(s)}{\sqrt{a^2+2\sqrt2+3}}+C=\frac{2\sqrt2\,\arctanh\left(\frac{(\sqrt{2}+1)u-a}{\sqrt{a^2+2\sqrt2+3}}\right)}{\sqrt{a^2+2\sqrt2+3}}+C$$
Now, to find the indefinite just plug in the endpoints, to obtain:
$$\boxed{\frac{2 \sqrt{2} \left(\arctanh\left(\frac{\sqrt{2}+1-a}{\sqrt{a^2+2
   \sqrt{2}+3}}\right)+\arctanh\left(\frac{a}{\sqrt{a^2+2
   \sqrt{2}+3}}\right)\right)}{\sqrt{a^2+2 \sqrt{2}+3}}}$$

Integral with a fixed parameter


Como fazer o navegador renderizar o  com alguns espaços no texto?

Question: Tenho uma
 que servirá para armazenar informações. Eu quero fazer uma espécie de "tabela", formatando os textos e os valores para que fiquem mais ou menos dessa forma:
Hot Dog    2,99
Pizza         7
Carro     91000
Lasanha Sd.  13

É um exemplo bem tosco mesmo mas é nesse formato que eu quero meu texto. Para realizar esta tarefa, eu tentei utilizar o código abaixo:
const info = document.getElementById("info");
info.innerHTML = "";

const totalEpisodes = `<span>${getTotalEpisodesWatched(list).padStart(10)}</span><br/>`;
const meanScore = `<span>${getMeanScore(list).padStart(10)}</span><br/>`;

info.innerHTML += "Total Episodes:".padEnd(15) + totalEpisodes;
info.innerHTML += "Mean Score:".padEnd(15) + meanScore;

O problema é que quando eu criei esse código, eu esqueci completamente que os espaços não iriam aparecer no resultado final. Eu sei que posso utilizar o   para gerar um TAB mas o que preciso é realmente de espaçamentos em branco para realizar a formatação corretamente.
Então a minha dúvida é: como posso fazer o navegador renderizar os espaços no elemento?
Comment: Não seria melhor utilizar uma `table` ou `grid` para isso? Linhas podem quebrar e perder a formatação, e se o seu site for renderizado com uma fonte não mono-espaçada vai ficar estranho.
Comment: Só pra constar que ` ` não é um tab. Alem disso, porque você não adiciona um _code snippet_?
Comment: @user140828 sim eu pensei em usar um ``, porém não quero aquelas linhas da tabela e não quero aquela formatação padrão dela. Se for para usar um `` eu quero que a tabela fiquei com a cara de uma `` (sem linha, borda, ou qualquer outro detalhe) e com a formatação que eu mostrei na pergunta.
Comment: @LuizFelipe se eu fosse usar um *code snippet* para representar o que eu tento fazer no código, ficaria muito grande a pergunta pois eu precisaria colocar o HTML, etc, etc. Então eu coloquei apenas a parte do código JS que é o mais importante.
Comment: E como eu falei no comentário acima, não me importo de utilizar `` contanto que eu consiga a formatação que eu quero. Mas ainda assim como a pergunta é sobre renderizar espaços em branco no browser, seria bom uma resposta sobre isso para ajudar outras pessoas e não só a mim.
Comment: Espaço em branco é ` `. Dois espaços em branco ` `. Quatro espaços em branco ` `
Comment: Chegou a ver isso: https://pt.stackoverflow.com/q/421374/112052?
Comment: Chegou a ver isso (2): https://pt.stackoverflow.com/questions/454404/alinhamento-de-elementos-no-html-e-css/454432#454432
Comment: @hkotsubo era exatamente isso que eu estava procurando. Eu não achei no site antes essa questão porque o título da pergunta não deixava claro que era sobre espaços em branco em HTML.
Comment: Esqueça a formatação no seu código! O correto é usar CSS. Código é para processar; CSS é para formatar. Mas, como sei que todo programador é cabeça-dura, se você quiser **muito** usar seu código da forma como o escreveu, você sempre pode usar as tags  ... .
Answer: Para ser sincero com você, não faz sentido você querer reinventar a roda. Se você quer simplesmente mostrar informações de uma forma tabulada, o elemento
 é ideal para o que você precisa, bastando formatar algumas células com a propriedade text-align, veja:

#info tr td:last-child {
  text-align: right;
}

    Hot Dog
    2,99

    Pizza
    7

    Carro
    91000

    Lasanha Sd.
    13

Note que por padrão a tabela não mostra bordas.
Além de você estar utilizando o elemento próprio para isso, você não precisa de gerenciar a lógica de espaços no JavaScript, deixando isso a cargo do CSS.
Existem alguns poucos casos em que tabelas não são ideal para mostrar dados tabelados (como recriar uma planilha do estilo do Excel), mas não creio que esse simples quadro de informações seja um deles. :)
Comment: Luiz o código CSS não está funcionando aqui. Eu copiei e colei certinho o código CSS da resposta porém ele não afeta o ``.
Comment: @JeanExtreme002 Você modificou o HTML? Simplesmente não funciona...?
Comment: Simplesmente não funciona. E uma coisa que ta me deixando aflito, é que os `tr` estão dentro do `` que está dentro da ``. Estou inserindo os dados na tabela dessa forma table.innerHTML += `Dado:${dado}`;
Comment: Você chegou a ver se o CSS funciona no _snippet_ acima? Porque aqui está funcionando.
Comment: Consegui fazer funcionar. Tava dando problema por algum motivo porque eu criei as `` com `innerHTML` ao invés de usar o `.createElement`. Obrigado Luiz.
Comment: Luiz o código funciona mas o `tr` não possui a mesma largura da tabela. Sendo assim os dados não ficam "encostando" ao lado direito da tabela como deveria. O que devo fazer?
Comment: @JeanExtreme002, nesse caso acho melhor você abrir uma outra pergunta para tentar exemplificar um pouco melhor o seu problema. Uma outra opção é irmos para o chat. :-)
Comment: To achando que se eu abrir uma outra pergunta eu vou tomar uma chuva de downvote que nem nessa ;p Melhor ir para o chat mesmo.


$(f(1 - f(x)) = 1 - x^9$, $f(1) = 0$ and $f'(1) < 0$, then where is the real number $r$ such that $f(r) = r^{99}$?

Question: If $f(1 - f(x)) = 1 - x^9$, $f$: R $\to$ R is differentiable, $f(1) = 0$ and $f'(1) < 0$, how to show there is a real number $r$ such that $$f(r) = r^{99}?$$
Edit: Taylor Theorem makes no use. I try to take $a = 1 - {1 \over n}$, where n is also a real no. Then as $f'(1) < 0$, $f$ is decreasing at $x = 1$ and $f(a) > f(1) = 0$. By mean-value theorem, $$f(a) - f(1) = f'(a_0)(a - 1), a < a_0 < 1$$
Let $g(x) = f(x) - x^{99}$, then clearly $g(1) < 0$ and $g(r) = 0$.
How about showing $g(a) > 0$? Or to take $a$ as something else?
Answer: After almost 4 years I finally think of these. Let me know anywhere wrong.
Firstly if $f(1 - f(x)) = 1 - x^9$, then let $a \in \mathbb{R}$ so that $f(a) = 1$, hence \begin{align} f(0) = f(1 - f(a)) = 1 - a^9. (1) \end{align}
Also we rearrange the terms in expressing $f(1 - f(x))$ to be $f(x) = 1 - f^{-1}(1 - x^9)$, then \begin{align} f(0) = 1 - f^{-1}(1 - 0) = 1 - a. (2) \end{align}
Combining $(1)$ & $(2)$, we have $a^9 - a = 0$, which $a = 1$ (rejected, or $f(1)$ has $2$ values), $0$ or $-1$ (rejected).
If $a = -1$, i.e. $f(-1) = 1$, then $f(1 - f(-1)) = f(0) = 1 - (-1)^9 = 2$. If we let $g(x)$ as I tried above, $g(0) = 2 > 0$. However, by differentiating $f(1 - f(x))$ against $x$, we have $f'(1 - f(x))\cdot -f'(x) = -9x^8$.
\begin{align} \Rightarrow f'(1 - f(-1)) \cdot -f'(-1) = f'(0)f'(-1) &= -9; \\ f'(1 - f(0)) \cdot -f'(0) = f'(-1)f'(0) &= 0 \end{align}
produces contradiction, so we have to reject this possibility.
If $a = 0$, i.e. $f(0) = 1$, then $g(0) = 1 > 0$ as well without the confusion on (the product of) the derivatives. Now the mean-value theorem becomes useful that

differentiabilty of $f$ (so does of $g$) guarantees continuity on at least $[0, 1]$.
$g(0) = 1 > 0 > -1 = g(1)$.

So $\exists \text{ } r \in [0, 1] \Rightarrow g(r) = 0$, i.e. $f(r) = r^{99}$. $\Box$


Let $R$ be a Noetherian ring. Then all finitely generated $R$-modules are Noetherian

Question: Here is an excerpt of my lecture notes:
" Claim I: Let $M$ be $R$- module and $N$ be submodule of $M.$ Then $M$ is Noetherian iff $N, \ M/N$ are Noetherian.
Def: The ring $R$ is Noetherian iff the regular $R$-module is Noetherian.
Claim II:  Let $R$ be a Noetherian ring. Then all finitely generated $R$-modules are Noetherian
Proof: By Claim I, every free $R$-module of finite rank is Noetherian and hence every finitely generated $R$-module. "
How do we deduce from Claim I that every free $R$-module of finite rank is Noetherian and hence every finitely generated $R$-module? Please advise/instruct me. Thank you.
Answer: If $R$ is Noetherian, then the regular module ($R$ as a module over itself, say as a left module) is Noetherian. Denote the regular module by $R$ as well.
Then $R\oplus R$ is Noetherian as it has $N=R\oplus 0$ as a Noetherian submodule with Noetherian quotient (isomorphic to $R$). By induction, $R^n$ is Noetherian.
If $M$ is finitely generated by $n$ elements it is a quotient of $R^n$ modulo the submodule consisting of the relations between those generators. Hence $M$ is Noetherian.
Comment: Because this is the module I need to look at in order for my argument to work. I argue by induction, I first look at $R^2$ ($=R\oplus R$, the external direct sum of the two modules, i.e. the cartesian product as a set equipped with componentwise addition and scalar multiplication), then at $R^n$. In fact, it would do to just look at $R^n$ and decompose it as $R\oplus R^{n-1}$ since we already looked at $R$, but it's a little clearer this way.
Comment: Consider $f ~:~ R\oplus R \to R, ~ (a,b) \mapsto a$. This is a surjective homomorphism of modules with kernel $N=0\oplus R$. Now the claim follows from the first isomorphism theorem.
Comment: This is also a consequence of the isomorphism theorem. Let $M=\langle m_1,...,m_n\rangle$. Then the obvious morphism $R^n \to M$ is surjective and its kernel is the submodule I was referring to. I am getting the feeling you should do some revision on basic concepts of module theory... EDIT: The "obvious morphism" is given by $e_i \mapsto m_i$, i.e. the $i$-th standard basis vector is mapped to the $i$-th generator of $M$.
Comment: I thought so. Note that the external direct sum is a construction (of a new module) whereas the internal direct sum is a property of a ("pre-existing") module. The two concepts are related by the fact that the module $M_1\oplus_{\text{external}} M_2$ is the internal direct sum of the 2 submodules $M_1\oplus 0$ and $0\oplus M_2$.
Comment: I meant what I wrote, the module $M:=M_1\oplus M_2$ (this is the external direct sum, it is common to denote that by $\oplus$, but you can use $\times$ as well) decomposes as the internal direct sum $M=(M_1\oplus 0)\oplus (0\oplus M_2)$, where $0$ abbreviates $\{0_{M_1}\}$ or $\{0_{M_2}\}$, respectively. Remember that the external direct sum is a construction, the internal one is a property of a module. So $\cong$ would rather denote an isomorphism of $M_1\times M_2$ with another external direct sum (i.e. a newly constructed module)...
Comment: Thank you. In the 2nd line of your proof, why is $R+R$  a direct sum?
Comment: Noted. I initially thought you meant internal direct sum.
Comment: I think you mean: $M_1 \times M_2\cong (M_1 \oplus \{0_M\}) \oplus (\{0_M\} \oplus  M_2) \ ?$
Comment: Thank you for the instruction. Back to your proof, may I know why $(R \times R) / N \cong R \ $ and hence $(R \times R) / N$ Noetherian?
Comment: Finally, could you explain what you meant by $M$ is quotient of $R^n$  modulo the submodule consisting of the relations between those generators? i.e. modulo the submodule?
Comment: Thanks for your great instruction!
Answer: Every finitely generated $R$-module is a quotient of a free $R$-module, and since quotienting preserves Noetherian-ness, it suffices to show that every free $R$-module is Noetherian. This can be proved by induction. The simplest free $R$-module is $R^{1} = R$, which we already know is Noetherian. The next one to consider is $R^{2}$ (recall that all free $R$-modules look like $R^n$ for some $n$). Consider the exact sequence
$$ 0 \to R \to R^{2} \to R \to 0$$
Where $R \to R^2$ is given by inclusion (in the first coordinate), and $R^2 \to R$ is projection onto the second coordinate. By Claim I, $R^2$ is Noetherian. Proceed inductively using the exact sequence
$$0 \to R^{n-1} \to R^{n} \to R \to 0$$


Múltiplos Prototypes

Question: Gostaria de saber como adicionar um prototype para uma função que já está instanciada em um prototype. Exemplo abaixo:
app.js
'use strict';

function NivFire(){
    this.db = "", this.admin = "", this.reference;
}

NivFire.prototype = {
    Fire : function(credential,url){},
    Ref : function(ref){ }
};

NivFire.prototype.Ref.prototype = {
    Set: (args) => {},
    Push: (args) => {}
};

module.exports = NivFire;

main.js
var NivFire = require("./app.js");
var nivfire = new NivFire();
nivfire.Fire( require('./nivellirfirebase.json'), "https://nivellir-97d87.firebaseio.com" );

nivfire.Ref("users").Set({
  name : "User1"
});

Quando esse código é executado, retorna o TypeError: Cannot read property 'Set' of undefined.
Answer: Use Object.defineProperty() para definir uma nova propriedade diretamente em um objeto, ou modificar uma propriedade já existente em um objeto. Para evitar repetições de código e facilitar a manutenção, crie um novo modulo, aqui dou o nome do arquivo como definePropriedade.js
let config = {
  writable: false,
  enumerable: false,
  configurable: true
};

const definePropriedade = (obj, nome, valor) => {
  config.value = valor;
  Object.defineProperty(obj, nome, config);
}

module.exports = definePropriedade;

depois importe no arquivo que será utilizado, no caso app.js
let definePropriedade = require('./definePropriedade.js');

agora basta chamar o método informando o protótipo:
// Define a propriedade: "Fire"
definePropriedade(NivFire.prototype, 'Fire', (credential,url) => {
  console.log(credential, url);
});

quando for definir a propriedade de uma propriedade, basta chamar o método novamente dentro dele mesmo e informar o valor this como protótipo:
// Define a propriedade: "Ref"
definePropriedade(NivFire.prototype, 'Ref', (ref) => {
  console.log(`Usando Ref: ${ref}`);
  // Define a propriedade: "Set"
  definePropriedade(this, 'Set', (args) => {
    console.log(`Usando Set: ${JSON.stringify(args)}`);
  });
  // Define a propriedade: "Push"
  definePropriedade(this, 'Push', (args) => {
    console.log(`Usando Push: ${JSON.stringify(args)}`);
  });
  // Para que funcione "Ref('users').Set({ name : 'User1' })"
  // deve retornar o objeto
  return this;
});

Veja funcionando em repl.it
Referência

Object.defineProperty()

Múltiplos Prototypes


Why not allowing std::string initialization from array of chars?

Question: In C++ you can initialize an std::string object from a char * and a const char * and this implicitly assumes that the string will end at first NUL character found after the pointer.
In C++ string literals are however arrays and a template constructor could be used to get the correct size even if the string literal contains embedded NULs. See for example the following toy implementation:
#include <stdio.h>
#include <string.h>
#include <vector>
#include <string>

struct String {
    std::vector<char> data;
    int size() const { return data.size(); }

    template<typename T> String(const T s);

    // Hack: the array will also possibly contain an ending NUL
    // we don't want...
    template<int N> String(const char (&s)[N])
        : data(s, s+N-(N>0 && s[N-1]=='\0')) {}

    // The non-const array removed as probably a lot of code
    // builds strings into char arrays and the convert them
    // implicitly to string objects.
    //template<int N> String(char (&s)[N]) : data(s, s+N) {}
};

// (one tricky part is that you cannot just declare a constructor
// accepting a `const char *` because that would win over the template
// constructor... here I made that constructor a template too but I'm
// no template programming guru and may be there are better ways).
template<> String::String(const char *s) : data(s, s+strlen(s)) {}

int main(int argc, const char *argv[]) {
    String s1 = "Hello\0world\n";
    printf("Length s1 -> %i\n", s1.size());
    const char *s2 = "Hello\0world\n";
    printf("Length s2 -> %i\n", String(s2).size());
    std::string s3 = "Hello\0world\n";
    printf("std::string size = %i\n", int(s3.size()));
    return 0;
}

Is there any specific technical reason for which this approach wasn't considered for the standard and instead a string literal with embedded NULs ends up being truncated when used to initialize an std::string object?
Comment: To start with, after `char a[100] = "foo"; std::string s = a;`, `s.length()` probably shouldn't be 100.
Comment: Probably because having strings with embedded null-characters is an exceptional case, which could be handled other ways.
Comment: "a string literal with embedded NULs ends up being truncated when used to initialize an std::string object" -- only if one does it worng.
Comment: @T.C.: good point... I actually quite often build strings into arrays and then convert them to `std::string`. Removed the non-const version...
Comment: @Cheersandhth.-Alf: I'm not sure what you mean... how do you initialize an `std::string` object from a literal containing embedded `NUL`s ?
Comment: T.C. is right. Not only is it unintended, it would silently affect the semantics of existing programs. So this is a hypothetical question anyway; ISO WG21 isn't going to break programs like that.
Comment: @MSalters: there is a much bigger issue...  who would want `std::string x = "foo";` to have size 4? The `NUL` is however part of the array...
Comment: @6502: True, but you'd presume the rule would be to ignore any trailing `\0` (as that breaks lots of existing programs). You specifically mentioned embedded NUL. So you could still write `std::string x = "foo\0";` and get size 4. The only NUL ignored is the trailing one.
Comment: @MSalters: true... fixed the toy example. The semantic is however sort of a mess and it's reasonable this wasn't done in the standard.
Answer: C++14 introduces a suffix for string literals to make them into std::string objects, so the main use case is no longer relevant.
#include <iostream>
#include <string>
using namespace std;
using namespace std::literals;

int main() {
    string foo = "Hello\0world\n";
    string bar = "Hello\0world\n"s;
    cout << foo.size() << " " << bar.size() << endl; // 5 12
    cout << foo << endl; // Hello
    cout << bar << endl; // Helloworld
    return 0;
}

Comment: Upvoted for remembering that which I managed to forget. Thanks.
Answer: Initializing a std::string with a literal that contains embedded nullbytes requires passing both the starting pointer and the length to a constructor.
That's easiest if there is a dedicated takes-array-reference constructor template, but as you note

such a template, with only the array argument, would be considered a worse match than the constructor taking simply char const*, and
it would be unclear whether a final terminating nullvalue should be included or not.

The first point means that the physical code interface would be a single templated constructor, where only the documentation (and not your editor's tooltip for example) would tell the full story about what it acccepted or not. One fix is to introduce an additional dummy resolver argument. That reduces convenience.
The second point is an opportunity for introducing bugs. The most common use of the constructor would no doubt be ordinary string literals. Then, now and then, it would be used for literals and/or arrays with embedded nullbytes, but curiously with the last character choppped off.
Instead one can simply first name the value,
char const data[] = "*.com\0*.exe\0*.bat\0*.cmd\0";
string s( data, data + sizeof( data ) );    // Including 2 nulls at end.

All that said, when I've defined my own string classes I've included the takes-array-argument constructor, but for a very different reason than convenience. Namely, that in the case of a literal the string object can simply hold on to that pointer, with no copying, which provides not only efficiency but also safety (correctness) for e.g. exceptions. And an array of const char is the most clear indication of literal that we have in C++11 and later.
However, a std::string can't do this: it's not designed for it.

If this is often done then one might define a function like this:
using Size = ptrdiff_t;

template< Size n >
auto string_from_data( char const (&data)[n] )
    -> std::string
{ return std::string( data, data + n ); }

Then one can write just
string const s = string_from_data( "*.com\0*.exe\0*.bat\0*.cmd\0" );

Disclaimer: none of the code touched or seen by a compiler.

[I missed this on a first writing, but was reminded by Hurkyl's answer. Now heading for coffee!]
A C++14 string type literal chops off the final \0, so with such literal the above would have to include that terminating nullvalue explicitly:
string const s = "*.com\0*.exe\0*.bat\0*.cmd\0\0"s;

Apart from that, C++14 string type literals appear to provide the sought for convenience.
Comment: I missed the elephant in the room. For sure no one would love the ending `NUL` in the string.


Migration from a remote database PDOException

Question: I'm setting up a database migration. For now, I'm using the ssh tunnel to access the remote databse.
Here is the configuration in the Migration class:
<?php
...
Database::addConnectionInfo('for_migration', 'default', array(
  'driver' => 'mysql',
  'database' => 'database',
  'username' => 'user',
  'password' => '****',
  'host' => '127.0.0.1',
  'port' => '1000',
  'prefix' => '',
));

// Conect to the remote $databases
$query = Database::getConnection('default', 'for_migration')
    ->select('Content', 'ct');

// Better descriptions for wineid and name; best_vintages is added in prepareRow()
$source_fields = array(
  'id' => t('article ID'),
  'contenido' => t('Contenido'),
);

// Create a MigrateSource object, which manages retrieving the input data.
// Tell the source class not to try to join the map table.
$this->source = new MigrateSourceSQL($query,
    $source_fields,
    NULL,
    array('map_joinable' => FALSE)
    );

$this->destination = new MigrateDestinationNode('article');

$this->map = new MigrateSQLMap($this->machineName,
    array(
        'id' => array('type' => 'int',
                           'not null' => TRUE,
                           'description' => 'Article ID',
                           'alias' => 'id',
                          ),
        ),
        MigrateDestinationNode::getKeySchema(),
        'for_migration'
    );

// @todo Mapped fields
$this->addFieldMapping('body', 'content');
?>

When I try to access the migration UI page the count of items is correct, but I get and error when I try to load the task page to visualize the mappings and elements.
DOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM Content ct LIMIT 1 OFFSET 0' at line 1: SELECT FROM {Content} ct LIMIT 1 OFFSET 0; Array ( ) in MigrateSourceSQL->fields() (line 211 of /Users/brightsitesSM/Sites/devdesktop/independentpoc-dev/docroot/sites/all/modules/migrate/plugins/sources/sql.inc).

Probably there is something missing in the code as the SELECT in the SQL query is empty.
Here are the screenshots of the migration page:

... and the task page error:
Comment: The problem is that there are no fields in the SQL query (`SELECT FROM` is invalid SQL). Does that shed any light?
Comment: also the select is for `->select('Contenido', 'ct');` but your PDO error says `SELECT FROM Content` ... you need to check your table names and field names your using.
Comment: I think I had a similar issue with db_select. try to add `->fields('ct')` to your select.
Comment: Thanks. Yes, that's the issue I'll try adding fields to the db_select as @sareed sudgested. I think there is the issue.
Comment: @tenken sorry, that's a typo. The table name is ok.
Answer: The problem with the code is the connection to the database. There aren't fields in the select.
SELECT FROM {Content} ct

To solve that one of the solutions is adding ->fields('ct'); to the database connection. This will select all the fields from the table ct:
SELECT ct.* FROM {Content} ct

Comment: Information about how fields function works [here](https://api.drupal.org/api/drupal/includes!database!select.inc/function/SelectQuery%3A%3Afields/7).


Show $X_1^5+X_1^2X_2+X_1X_2+X_2$ is irreducible

Question: For a field $K$, is the polynomial $X_1^5+X_1^2X_2+X_1X_2+X_2$ irreducible in $K[X_1,X_2]$?
I think I have to show it for $K(X_1)[X_2]$ but I don't know how to do that.
Comment: That's the context, yes
Answer: Hint: Use Eisenstein's criterion (from left to right $X_2\nmid1$, $X_2\mid X_2$, $X_2\mid X_2$ and $X_2^2\nmid X_2$). Then use Gauss' lemma to pass back from the fraction field (the polynomial is primitive).
Answer:
Use Eisenstein's criterion with the ideal $\langle X_2\rangle.$
Now you can say that your polynomial is irreducible in $K(X_1)[X_2]$.
Use that the polynomial is primitive to conclude that it is irreducible in $K[X_1X_2]$


Determining the name of a certain alternate tuning?

Question: For example if the tuning is
C A D G B E
What is that called? Not Drop C is it?
Comment: They aren't all going to have names
Comment: A key part of the "Drop D" tuning is that the low three strings form a "power" chord — root, fifth, octave, in this case DAD — making chording easier. I would assume a "Drop C" tuning would have CGC. CAD does not form a useful chord, but you could easily play low melody notes in C up the neck and just drone on the slacked C. I could see this as a useful tuning, but I would never call CADGBE "Drop C"
Comment: This is *not* drop C. Drop C would be C-G-C-F-A-D.
Comment: I'd call that drop C but obviously other people would disagree. They don't all have names and the names that exist aren't universal. To specify a tuning, the best way is to list the notes of the tuning.
Comment: @user1079505 - how do you work that out? Bottom string drops to C, 2 tones, and the others drop 1 tone. Who camee up with that rule?
Comment: @RockwellRice maybe we should devise a naming system that provides names for all systems: Dadgibbee, Cadgibbee, Cigicfad, etc.
Answer: If drop D is D A D G B E, because the E is dropped to D, then logic says C A D G B E is drop C. Unfortunately, someone (trying to find who) decided that's not how to do it, so make of it what you will...
EDIT: according to Wiki, it is in fact a variation of drop C tuning - just drop low E to C!
Comment: If, starting from "E standard", you move all strings by the same interval, so that the 6th string is X, the name is "X standard". If you additionally drop the 6th string by 2 semitones to Y you get "Drop Y". So Drop D is E standard with the 6th string tuned to D. Drop C is D standard with 6th string tuned to C. I don't know who came up with this, but this seems to be a popular agreement.
Answer: Some people understand "drop C" to mean CGCFAD (or, drop D transposed down a whole step).  Other people understand "drop C" to mean CADGBE (or, standard tuning, and you drop your E to C).  So I would not just call it "drop C".
A somewhat common and less ambiguous name would be "E drop C" - since you are tuning to E and then dropping the E to C.  Then the other "drop C" would be called "D drop C", by the same logic.
In writing, I would just write "CADGBE" tuning.  It's clearer, more widely understood, and no longer to write out than "E drop C".  At the very least, if you want to call it something else, you should start by saying the term you chose to use means "CADGBE" tuning.
Answer: So there are two ideas going here and both are correct.
The "drop" on Drop D, I believe, refers only to dropping the string down to D.  However, the reason that works so well and is so widely used is because then the lowest three strings form a power chord DAD, which makes playing power chords easier in rock music because you can just lay one finger down and cover all three.
While this tuning could be called Drop C (what determines that is how often that term gets used by musicians and then it just becomes known, it isn't simply a matter of defining it in text book/dictionary sense), it also does not serve a similar useful function on the guitar as Drop D. But ya, you could call this drop C, however if no one knows what you mean by that, what difference does it make?
I think the above discussions show that simply applying a label to it is kind of a moot point unless everyone is on the same page, and since this tuning isn't a very widely used one, you will have conflicting ideas.


Performance of Ridge and Lasso Regression depend on set.seed?

Question: I try to do a ridge and lasso regression for out of sample predictions.
The optimal lambda is chosed via cross validation.
I run my results for different seeds in R. And depending on the seed i get a different result.
Now i ask myself do efficiency of this shrinkaged methods realy depend on the seed?
I mean do i have to find the right seed to produce an modell that gives me the smallest mse?
Comment: A closely related question is addressed at https://stats.stackexchange.com/questions/80407 : you might enjoy reading that thread, too.
Comment: Related to @whuber's comment: [If so many people use set.seed(123) doesn't that affect randomness of world's reporting?](https://stats.stackexchange.com/q/205961/1352)
Answer: Each time you run a cross validation you get an estimate of the true population test error.  Different random seeds give you different estimates of this population quantity, but each is an estimate of the same underlying truth.
If you re-seed the random number generator in a quest to drive down the estimated test error you are going to bias your estimate of the test error downwards (this is sometimes called seed-hacking, and is a bad practice).  If you take your final test error estimate to be the minimal you have seen over many runs of the random number generator, then you're definitely going to end up with a very optimistic estimate of the test error, and should not be surprised when your model performs much worse in production.
Instead, pick a seed and stick with it.  My personal seed is 154.
Comment: Lol. Concatenate.
Comment: Personally, I roll several 10-sided die each time I need to make a reproducible seed.
Comment: The real question is if you sum the results or concatenate them...
Comment: @MatthewDrury maybe i can solve the problem with the seed if is use reapeted cross validation?
Comment: I'm unsure what problem you are solving with that?  Are you looking for an estimate of the variance of your test error estimate?
Comment: In the case of repeated CV, you could report something like the interval of results. But reporting only the best result would be seed hacking.


Alimentar progress bar com Js

Question: Fiz uma função javascript que pega o numero de Ids preenchidos e retorna um numero que se transforma na porcentagem da width que faz a barra se mexer, porem, tenho um contador de caracteres que deveria mandar um valor para a progress-bar também, porem como não sou um bom conhecedor de javascript temo que tenha feito algo errado.

TERMOMETRO

$(document).on("input", "#TxtDesc", function () {
    var limite = 0;
    var caracteresDigitados = $(this).val().length;
    var caracteresRestantes = limite + caracteresDigitados;

    $(".caracteres").text(caracteresRestantes);
});

$(function() {

function progress(percent, $element, velocity) {
   percent = percent >= 100 ? 100 : percent;
   var progressBarWidth = percent * $element.width() / 100;
   $element.find('div').stop().animate({ width: progressBarWidth }, velocity, "linear").html("Nivel de relevância");
   var validA = 0;
}

$('#TxtDesc').on('input', function(){
  var value = $(this).val();
  var progressValue = $('#progressText div');
  var color, percent = 0;
if(value.length <= 100){
    color = "red";
    percent = 15;
}else if(value.length <= 199){
    color = "yellow";
    percent = 50;
}else{
    color = "#32CD32";
    percent = 100;
    validA = 30;
}

var Valor = value.length;

progress(percent, $('#progressText'), 300);
progressValue.css("background", color);
$('#progressText').css("border", "1px solid " + color);

  var $progressBar         = $('[id=progressTerm]'), // Barra de Progresso.
      $progressElements = $('[id=progressValorInteiro]'), // Elementos que devem ser checados // para modificar o valor da barra.
      $progressElements2 = $('[id=progressValorMeio]'),
      TOTAL             = $progressElements.length; // Total de elementos.

$progressElements.on('change, blur', function() {

    // Faz um filtro com o total elementos válidos.
    // Nesse caso, campos que não estejam "em branco" e que não estejam marcados
    // como ':invalid'.
    var valid = $progressElements.filter(function() {
      return ($(this).val() || $(this).prop('checked')) && !$(this).is(':invalid');
    }).length;

    var ResultF = (valid + validA);

    // Calcula a porcentagem e altera o valor da width da barra.
    var percent = (ResultF * 100) / TOTAL;

    $progressBar.width(percent);

})

  });

});
</script>

Answer: Galera, quem tiver a mesma duvida, nessa pergunta eu posto o codigo funcionando.
adicionar um id com Jquery
Abraço pessoal.

Alimentar progress bar com Js


Significant p-value and relative risk crossing 1

Question: I am trying to convert results I am finding in scientific articles into relative risks so that I can compare studies in a meta analysis (if there is enough homogeneity in the studies).
I came across a study entitled "Intervention to improve practices of prescribing appropriate medication before an operation; pre-and-post-intervention study".
In the pre-intervention group, 16 out of 233 patients (so 217 with correct prescription) had an incorrect prescription and post intervention 3 out of 137 patients (134 with correct) had an incorrect prescription.
In the paper, a p-value of 0.046 was given, using Fisher's exact test. I checked it using a hand calculation and got 0.049. When I put this result into an RR calculator, I get a RR of 0.32 [0.09, 1.07]. Now I am a relative stats rookie but I thought the 95% CI should not cross 1 if my p-value for comparing two proportions is below 0.05.
Comment: I think your p=0.049 was mistakenly taken from the chi-sq test. I used SPSS to check it, and the 2-side p value of Fisher's Exact test is 0.053; the p value of chi-sq is 0.049. That may explain why the 95% CI of RR crosses 1.
Answer: If you do a two-sided level 0.05 test of hypothesis that the relative risk is different from 1 and get a p-value less than 0.05 then this is equivalent to a two-sided 95% confidence interval that does not contain 1.  So given the p-value of 0.049 you would expect that 1 would fall outside the interval.  What are the possible explanations?
1.  The confidence interval is at a level higher than 95%
2. There is an error in the calculation of the p-value or the confidence interval.
3. The confidence interval is not constructed by inverting the Fisher test (e.g. a chi square approximate test was used for the confidence interval).
I think 3 is very likely to be the reason. The chi square interval is easier to calculate than one using Fisher's test.  Note that the significance level is very close to 0.05 and the upper limit of the confidence interval is just slightjy above 1.0.
Comment: Hey, yes the CI interval was set at 95% and I double checked the p-value calculations. I tried several RR calculator including the one for cochrane studies. The reason number 3 does seem plausible, would have never thought of that myself! Thanks
Answer: Fisher test can be inverted to get a confidence interval about the odds ratio, not about the relative risk. Therefore Michael's reason number 3 is necessarily the good one.


Karaf configuration

Question: When installing karaf in one computer and shifting it to another, lot of base directories have deafult path made during installation.
how to change the variables KARAF_BASE, KARAF_ETC, KARAF_DATA in karaf?
Comment: Possible duplicate of http://stackoverflow.com/questions/29020595/root-file-location-karaf-home-after-moving-karaf-server
Comment: which version of karaf do you use?
Answer: Have a look at your karaf–folder/bin/setenv(.bat/.sh)
Answer: In karaf–folder/bin/karaf.bat, you can override these variables.
Example:
-Dkaraf.etc="%KARAF_HOME%\..."

Note: you can also customize the KARAF_HOME variable at the begin of the karaf.bat script.
Answer: You can change KARAF environment variables in bin/setenv Unix script .

Karaf configuration


How to delete folder from Amazon S3

Question: I'm trying to delete the folder created in a bucket in Amazon S3 and it gives the error

An unexpected error has occurred. Please try again.

How can I delete the folder?
Comment: Please post the code you are using so someone can try to help you.
Comment: Folders do not exist in Amazon S3, but it is possible to create a zero-length object that services as a "marker" for a folder. If you can provide your code and show where you received the error, we would be able to offer some advice.
Comment: amount of information you have provided in your question makes no sense or incomplete( being polite )
Answer: First you need to understand that there is nothing like folder in Amazon s3 bucket
what you see is object which behaves like folder
one/          // so what you see folder is this but its separate object
one/abc.png
one/tow/
one/tow/a.zip

to delete folder you need to delete every object start with one/ and you can do that by deleteMatchingObjects() function
  $s3 = new Aws\S3\S3Client([
        'version' => 'latest',
        'region' => 'us-west-2',
        'credentials.ini' => [
            'key' => $credentials['key'],
            'secret' => $credentials['secret'],
        ],
    ]);
 /* this is what you need*/
 $s3->deleteMatchingObjects($bucket, $obj);

I have used phpsdk v3
Answer: I am using below code in s3.php class. check it out.
/**
* Delete an empty bucket
*
* @param string $bucket Bucket name
* @return boolean
*/
public function deleteBucket($bucket = '') {
    $rest = new S3Request('DELETE', $bucket);
    $rest = $rest->getResponse();
    if ($rest->error === false && $rest->code !== 204)
        $rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
    if ($rest->error !== false) {
        trigger_error(sprintf("S3::deleteBucket({$bucket}): [%s] %s",
        $rest->error['code'], $rest->error['message']), E_USER_WARNING);
        return false;
    }
    return true;
}

How to delete folder from Amazon S3


Sql - Selecionar primeiro e ultimo registro

Question: Possuo as seguintes tabelas:
CREATE TABLE tb_lote
(
  id_lote integer NOT NULL DEFAULT nextval('tb_lote_seq'::regclass),
  ds_lote character varying(255),
  CONSTRAINT pktb_lote PRIMARY KEY (id_lote)
);

CREATE TABLE tb_lote_ticket
(
  id_lote_ticket integer NOT NULL DEFAULT nextval('tb_lote_ticket_seq'::regclass),
  id_lote integer,
  nr_quantidade numeric(12,2) DEFAULT 0,
  CONSTRAINT pktb_lote_ticket PRIMARY KEY (id_lote_ticket),
  CONSTRAINT fk_tb_lote_ticket_tb_lote FOREIGN KEY (id_lote)
      REFERENCES tb_lote (id_lote) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
);

CREATE TABLE tb_processo
(
  id_processo integer NOT NULL DEFAULT nextval('tb_processo_seq'::regclass),
  id_lote_ticket integer,
  id_setor integer,
  dt_inicio timestamp without time zone,
  CONSTRAINT pktb_processo PRIMARY KEY (id_processo),
  CONSTRAINT fk_tb_processo_tb_lote_ticket FOREIGN KEY (id_lote_ticket)
      REFERENCES tb_lote_ticket (id_lote_ticket) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT fk_tb_processo_tb_setor FOREIGN KEY (id_setor)
      REFERENCES tb_setor (id_setor) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
);

E o relacionamento é, Cada lote tem N ticket e cada ticket tem 1 processo.
- Lote    1..N   Ticket
- Ticket  1..1   Processo

Gostaria de saber como realizar um SQL eficiente para saber a dt_inicio de cada lote em cada Setor e ao mesmo tempo a "dt_final".
A dt_final seria a dt_inicio do ultimo processo.
Sql Atual
SELECT
    Lote.id_lote as "Lote.id_lote",
    Setor.ds_setor as "Setor.ds_setor",
    Setor.id_setor as "Setor.id_setor",
    (
        SELECT
            ProcesseTmp.dt_inicio
        FROM
            tb_processo as ProcesseTmp
            LEFT JOIN   tb_setor as SetorTmp ON SetorTmp.id_setor = ProcesseTmp.id_setor
            LEFT JOIN   tb_lote_ticket as LoteTicketTmp ON LoteTicketTmp.id_lote_ticket = ProcesseTmp.id_lote_ticket
            LEFT JOIN   tb_lote as LoteTmp ON LoteTmp.id_lote = LoteOrdemTmp.id_lote
        WHERE
            LoteTmp.id_lote = Lote.id_lote AND
            SetorTmp.id_setor = Setor.id_setor
        ORDER BY
            ProcesseTmp.dt_inicio
        LIMIT 1
    ) as "Processe.dt_inicio",
    (
        SELECT
            ProcesseTmp.dt_inicio
        FROM
            tb_processo as ProcesseTmp
            LEFT JOIN   tb_setor as SetorTmp ON SetorTmp.id_setor = ProcesseTmp.id_setor
            LEFT JOIN   tb_lote_ticket as LoteTicketTmp ON LoteTicketTmp.id_lote_ticket = ProcesseTmp.id_lote_ticket
            LEFT JOIN   tb_lote as LoteTmp ON LoteTmp.id_lote = LoteOrdemTmp.id_lote
        WHERE
            LoteTmp.id_lote = Lote.id_lote AND
            SetorTmp.id_setor = Setor.id_setor
        ORDER BY
            ProcesseTmp.dt_inicio DESC
        LIMIT 1
    ) as "Processe.dt_final",
FROM
    tb_mapa_producao as Processe
    LEFT JOIN tb_setor as Setor ON Setor.id_setor = Processe.id_setor
    LEFT JOIN tb_lote_producao_ordem_ticket as LoteTicket ON LoteTicket.id_lote_ticket = Processe.id_lote_ticket
    LEFT JOIN tb_lote_producao as Lote ON Lote.id_lote = Lote.id_lote
WHERE
    Processe.dt_inicio  BETWEEN '09/09/2015 00:00:00' AND '14/10/2015 23:59:59'
    and 1=1
    and ( Processe.fl_desativado is false OR Processe.fl_desativado is null )
GROUP BY
    Lote.id_lote,
    Setor.ds_setor,
    Setor.id_setor,
ORDER BY
    Lote.id_lote,
    Setor.ds_setor,
    Setor.id_setor,

Dados para teste
tb_lote
    id_lote     |   ds_lote
    1           |   teste1
    2           |   teste2

tb_lote_ticket
    id_lote_ticket  |   id_lote     |   nr_quantidade
    1               |   1           |   10
    2               |   1           |   10
    3               |   1           |   10
    4               |   1           |   10
    5               |   1           |   10
    6               |   1           |   10
    7               |   2           |   10
    8               |   2           |   10
    9               |   2           |   10
    10              |   2           |   10

tb_processo
    id_processo     |   id_lote_ticket  |   id_setor    |   dt_inicio
    1               |   1               |   3           |   2015-10-01 15:00:00
    2               |   2               |   3           |   2015-10-01 15:12:00
    3               |   3               |   3           |   2015-10-01 15:24:00
    4               |   4               |   4           |   2015-10-01 15:36:00
    5               |   5               |   4           |   2015-10-01 15:48:00
    6               |   6               |   4           |   2015-10-01 16:00:00
    7               |   7               |   6           |   2015-10-01 15:12:00
    8               |   8               |   6           |   2015-10-01 15:24:00
    9               |   9               |   6           |   2015-10-01 15:36:00
    10              |   10              |   6           |   2015-10-01 15:48:00

Resultado Esperado
id_lote     |   id_setor    |   dt_inicio               |   dt_final
1           |   3           |   2015-10-01 15:00:00     |   2015-10-01 15:24:00
1           |   4           |   2015-10-01 15:36:00     |   2015-10-01 16:00:00
2           |   6           |   2015-10-01 15:12:00     |   2015-10-01 15:48:00

Ou seja: de cada lote, obter a data de início e fim de cada setor, sendo que a data de início corresponde ao primeiro processo do setor e a data fim corresponde ao último processo do setor.
Comment: Está difícil de entender o problema. Vai ajudar a conseguir boas respostas de você mostrar exemplos de dados em todas as tabelas e o resultado esperado conforme os dados de exemplo. Outro ponto é que talvez uma query mais simples seja mais ineficiente que a tua original no teu cenário real. Será excessivamente trabalhoso, chato e eventualmente ingrato considerar este aspecto nas respostas. Se você nem sabe ainda o quanto sua query é ineficiente é porque eficiência não é um problema - eu tiraria este aspecto da questão.
Comment: Podemos dizer que *de cada lote, você quer a data de início e fim de cada setor, sendo que a data de início corresponde ao primeiro processo do setor e a data fim corresponde ao último processo do setor*?
Comment: @Caffé Exatamente isto.
Comment: @GuilhermeLautert para a gente te ajudar, recomendo colocar a criação das tabelas e dados neste site http://sqlfiddle.com/, e passar a url para a gente. Ai conseguimos te ajudar, pois no teu exemplo acima falta a tabela tb_mapa_producao e tb_setor.
Answer: Aí está:
select
    lote_ticket.id_lote, processo.id_setor,
    min(processo.dt_inicio) as dt_inicio, max(processo.dt_inicio) as dt_final
from
    tb_processo as processo join tb_lote_ticket as lote_ticket
        on lote_ticket.id_lote_ticket = processo.id_lote_ticket
group by
    lote_ticket.id_lote, processo.id_setor
order by
    lote_ticket.id_lote, processo.id_setor

Veja funcionano no SQL Fiddle.
Explicação
Você fez duas subqueries que servem apenas para buscar a data de início e a data fim.
Sua primeira subquery traz a data de início pegando o primeiro registro. A segunda subquery é quase idêntica e traz a data fim pegando o primeiro registro da mesma query só que ordenada inversamente.
Ora, o que você fez foi reproduzir as funções de agregação Min e Max.
Minha query ficou mais simples porque eu usei estas funções internas do banco em vez de reproduzir o seu comportamento com subqueries.


Replicating Shalizi's New York Times PCA example

Question: I am trying to replicate Shalizi's NY Times PCA example found in his Advanced Data Analysis with an Elementary Point of View book. I found sample code and data here
http://www.stat.cmu.edu/~cshalizi/490/pca/
I loaded the R workspace pca-examples.Rdata, and was able to extract a CSV out of it which I placed in
https://github.com/burakbayramli/classnotes/blob/master/app-math-tr/pca/nytimes.csv
In order for PCA using SVD, I did
from pandas import *
import numpy.linalg as lin
nyt = read_csv ("nytimes.csv")
labels = nyt['class.labels']
nyt = nyt.drop(["class.labels"],axis=1)
nyt_demeaned = nyt - nyt.mean(0)
u,s,v = lin.svd(nyt_demeaned.T,full_matrices=False)

Then I tried to project onto the space defined by the eigenvectors
nyt2 = np.dot(nyt_demeaned, u[:,0:2])

Then plot
plot(nyt2[:,0],nyt2[:,1],'.')

and
arts = nyt2[labels == 'art']
music = nyt2[labels == 'music']
plot(arts[:,0],arts[:,1],'r.')
plot(music[:,0],music[:,1],'b.')

I get

This image is different from Shalizi's picture from his book (using the following R code)
load("pca-examples.Rdata")
nyt.pca = prcomp(nyt.frame[,-1])
nyt.latent.sem = nyt.pca$rotation
plot(nyt.pca$x[,1:2],type="n")
points(nyt.pca$x[nyt.frame[,"class.labels"]=="art",1:2],
       pch="A",col="red")
points(nyt.pca$x[nyt.frame[,"class.labels"]=="music",1:2],
       pch="M",col="blue")

Maybe there was a 90 degree error, flip it one way or another, etc. then you could perhaps have the two images to be somewhat close, but even then the distribution isnt exactly right, and the data points for arts are not as clearly seperated from music data points as they are in Shalizi's picture.
Any ideas?
Answer: It turns out Shalizi does some extra normalization, called inverse document-frequency weighting, with this code
scale.cols <- function(x,s) {
  return(t(apply(x,1,function(x){x*s})))
}

div.by.euc.length <- function(x) {
  scale.rows(x,1/sqrt(rowSums(x^2)+1e-16))
}

idf.weight <- function(x) {
  # IDF weighting
  doc.freq <- colSums(x>0)
  doc.freq[doc.freq == 0] <- 1
  w <- log(nrow(x)/doc.freq)
  return(scale.cols(x,w))
}

load("pca-examples.Rdata")
nyt.frame.raw$class.labels <- NULL
nyt.frame <- idf.weight(nyt.frame.raw)
nyt.frame <- div.by.euc.length(nyt.frame)

When I ran SVD on nyt.frame, instead of nyt.frame.raw (after load, the code above is not needed for that, it's just there for demo), the two classes were distinctly seperable. The distribution of points still did not look like Shalizi's picture, but I think I can work with this.
Note: Simply reading nytimes4.csv, the normalized file, is not enough, the data still needs to be centered around 0 (de-meaned).
Note: After skipping dropping a bogus column in nytimes4.csv and demeaning, the output is exactly the same as Shalizi's.
The same thing in Python / Pandas
from pandas import *
nyt = read_csv ("nytimes.csv")
nyt = nyt.drop(['class.labels'],axis=1)
freq = nyt.astype(bool).sum(axis=0)
freq = freq.replace(0,1)
w = np.log(float(nyt.shape[0])/freq)
nyt = nyt.apply(lambda x: x*w,axis=1)
nyt = nyt.apply(lambda x: x / np.sqrt(np.sum(np.square(x))+1e-16), axis=1)

Comment: Thank you for detailing the full solution, that's very helpful!


Find gcd and invertible elements of a ring.

Question:
I have the ring $R = \mathbb{Z}[i\sqrt{7}]$. I need to find (if exists) $\gcd(-5+3i\sqrt{7},10+2i\sqrt{7})$ and all invertible elements of $R$.

I said that gcd dosen't exist because $R$ is not an euclidian domain, but I'm not sure how to prove it. And I don't know how to find its invertible elements. But in general I want to know how should I prove if gcd can be found or not.
Answer: Let $x = a + b\sqrt{-7} \in R$. You can define the norm of $x$ by $N(x) = x \cdot \bar x = a^2 + 7b^2$. You can prove that the norm is multiplicative.
This means that if $x$ is invertible in $R$, then $N(x)N(x^{-1}) = 1$, so $N(x) = 1$. What are the possible $x$'s?
For your gcd problem, if there is a nontrivial $x$ such that $x$ divides both $-5 + 3\sqrt{-7}$ and $10 + 2\sqrt{-7}$, then $N(x)$ divides both $N(-5 + 3\sqrt{-7}) = 88$ and $N(10 + 2\sqrt{-7}) = 128$. So $N(x)$ divides $8$. What are the possible $x$'s? There are not much $x$ in this list. You can test which one can be the gcd.
Remark: Under the "natural norm" $N$ defined above, we can say that $R$ is not an Euclidean domain, by constructing $a, b \in R$ such that the division $a = bq + r$ is not possible. On the complex plane $\mathbb C$, consider the rectangle with vertex $0, 1, 1+\sqrt{-7}$ and $\sqrt{-7}$. Since the diagonal is of length $\sqrt{8} \approx 2.8$, there is a point $z \in \mathbb Q + \sqrt{-7}\mathbb Q$ such that the distance of $z$ to any vertex is $> 1$. Let $b \in \mathbb N$ so that $a = bz \in R$. Then you will see that the Euclid division of $a$ by $b$ does not exist.
Comment: So If $R$ is not an Euclidian Domain can we discuss about gcd on $R$?
Comment: Yes. We still can say $c \ | \ a$ if $a = qc$ for some $q$. And a gcd of $a$ and $b$ is an element $d$ such that (i) $d \ | \ a$ and $d \ | \ b$; and (ii) for any $d'$ such that $d' \ | \ a$ and $d' \ | \ b$, $d \ | \ d'$. So it need not be unique (can be up to a unit), but is still defined.
Comment: Ok, and one more thing. At the gcd problem, shouldn't I find an x in $R$ such that its norm is 8. Or why should its norm divide 8 instead of being 8?
Comment: Because the norm of the gcd can actually be smaller. For instance, the gcd of $1 + \sqrt{-7}$ and $1 - \sqrt{-7}$ is 1 since $1 + \sqrt{-7}$ is not divisible by $1 - \sqrt{-7}$ or 2 (just divide them in $\mathbb Q[\sqrt{-7}]$ and verify that the quotient is not in $R$).
Comment: Ok so In my case the gcd is 2?
Comment: The elements in $R$ with norm dividing 8 are, $\pm(1 \pm \sqrt{-7})$, $\pm 2$ and $\pm 1$. You need to check divisibility for each. After calculation you shall see that the gcd is something of norm 8 in this case.
Comment: Ok so let's say if $R = \mathbb{Z}[i\sqrt{3}]$ and I need to find gcd of $(3+i\sqrt{3},2-i\sqrt{3})$. I found its norm of gcd must divide 1. So the only case is + and - 1, am I right?
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/71655/discussion-between-hw-chu-and-raducu-mihai).


Calculate Tithe from Income

Question: Hi I need help calculating the amount I need to donate as tithe (1/10 of income) every year.
Say my annual income before tax is $50000 and the tax rate is 30%. Which means my income after tax is $50000 x 0.7 = $35000. So I will donate $3500 as tithe.
Now since donation is tax free in my country, any donation >= $2 can claim the tax back. Which means I can claim back 30% of $3500, which is $1050.
That $1050 now becomes my income and I should again donate 1/10 of it as tithe, which is $105.
The same process repeats again after claiming tax back for that $105 donation until the donation is < $2 where it is too little to be claimable.
Without doing the whole process repeatedly over multiple tax claims and donations, I want to know the exact amount I should donate as tithe in one go (obviously will be > $3500), so that the tax claimed back is kept for myself.
Please answer with formula of variables rather than exact amount used in this example.
Answer: We care about three quantities: the amount of money you make before taxes $(G)$, the amount you offer as tithe $(T$), and the amount you pay in taxes $(X)$.
You don't pay any taxes on the amount you give away as tithe, but you do pay taxes on the rest. Therefore, with a tax rate of 30%, we have in general:
$$X = 0.3\cdot(G-T)$$
You want to give away 10% of your after-tax income as tithe:
$$T = 0.10  (G-X) $$
Let's combine these two equations to eliminate $X$ so that we have:
$$T = 0.10G - 0.10(0.3G-0.3T)$$
$$T = 0.07G + 0.03T$$
$$0.97T = 0.07G$$
$$\boxed{T = \frac{7}{97}G}$$
$$T \approx 0.0721 \cdot G$$
For example, if you make \$50000 before taxes, you would pay around \$3608.24 in tithe—slightly more than the \$3500 you would pay if you didn't use the recursive formula.

Note: If I understand your situation correctly, we can ignore the \$2 limit as long as you're giving away the entire tithe $T$ all in one payment and its total value is greater than \$2. For example, if you just give your entire tithe of \$3608.24 all at once, it's not taxable.

And in the general problem where tithes are untaxed and you want to recursively pay $p$ percent of your income as tithe given $q$ percent tax rate, the same algebraic reasoning shows you should pay
$$T = \frac{p(1-q)}{1-pq}G$$
which agrees with our earlier answer.
Comment: Wow impressive! All points in the question checked with detailed explanation, definitely the kind of answer I am looking for and I've learnt a lot from you, thank you!
Answer: You want to find:
$$3500+105+3.15+\cdots=\frac{3500}{1-0.3\cdot 0.1}=\frac{3500}{0.97}\approx 3608.247.$$
Note: $T_{n+1}=0.03T_n, T_1=3500$.
Comment: Thank you, you are quick but I found yours a bit hard to understand where the numbers come from (my bad), so I picked the other.
Comment: I am with you, the one you picked is comprehensive. To help with the numbers: $3500+3500\cdot 0.3\cdot 0.1+3500\cdot 0.3\cdot 0.1\cdot 0.3\cdot 0.1+\cdots$.
Answer: Let $G$=gross income and $T$=tithe.
Your after-tax income, for purposes of computing the tithe is $$.7G+.3T,$$ and the tithe is $10$ percent of this:
$$T=.07G+.03T\implies .97T=.07G\implies\\
\boxed{T=\frac{7}{97}G\approx .0722G}$$
This gives $T=\$3608.25\text{ when } G=\$50000.$
Comment: Very clever way to see through the issue, and you were very quick to answer too. Deserve more upvotes!

Calculate Tithe from Income


I need to prove that $\mathbb{C}/\mathbb{R}\cong \mathbb{R}$

Question: I need to prove that $\mathbb{C}/\mathbb{R}\cong \mathbb{R}$, by the this theorem:
$G/\ker(\varphi)\cong Im(\varphi)$.
I tried to find $\varphi$ that will give me this but I didn't succeed.
Maybe it's a mistake at my H.W.
But if not, I'll be glad if you will help me...
Thank you!
Comment: $(\mathbb C,+)$ you mean?
Comment: Find a surjective homomorphism $\mathbb C\to\mathbb R$ with kernel $\mathbb R$. These are $\mathbb R$-vector spaces that we are dealing with, there are canonical bases...
Comment: @B.S. I this yes - $\mathbb{C}$ with + action... ($0\in \mathbb{C}$)
Answer: Hint: Assuming you mean $\langle\mathbb{C},+\rangle$ and $\langle\mathbb{R},+\rangle$: consider $\varphi:\mathbb{C}\to\mathbb{R}$ by $\varphi(z)=\operatorname{im}(z)$, i.e. $\varphi(x+iy)=y$.
Comment: Wow, great!!! Thank you!!!
Answer: I think the map $(a+ib)\mapsto a$ would be helpful.
Comment: Yes. $\text{ker}(f)=\{a+ib\mid a=0\}\cong\mathbb R$ where $f$ is my map.
Comment: the kernel is isomorphic to $\mathbb{R}$
Comment: $\ker=\mathbb{R}$??
Comment: $\ddot\smile +1$


Expose a filter to turn a different filter on or off

Question: I have a view of items that have a due date, and I want to be able to expose a boolean filter "Is overdue by more than 30 days"
I can create a filter on this due date as a relative date filter "<= today -30 days"; however this filter is always active on the view.
The best I've been able to come up with is to add a new boolean field on my content type "date_filter" that is always null, and in the view create a new exposed filter "is not null" (i.e, when active, will always be false).
Then add this filter to a new OR filter group with the above relative date filter. This works, as when the filter is "off" it returns true and overrides the relative date filter. When on, only the rows that fit the date filter are returned.
However, is there a way to do this without adding dummy fields? Ideally a module I can use to do this. I'd prefer not to have to write a hook just for this filter.
Answer: There is a module for that; you can use Views Dependent Filters which allows the presence of exposed filters on a view to being controlled by values in another exposed filter. Dependent filters are hidden when not relevant, and their values are not considered when the exposed form is submitted.
Comment: Turns out I already have this module installed. However, looking over it, I can't see how to make it work to do what I want above. It appears to be using one field to drive exposing dependent filters based on the value of the first, e.g., product type vs product specific filters.
The case above is that I only have *one* filter/field I want to switch on and off, but not expose directly


json_normalize delivers ValueError, need of distinguishing prefix

Question: I'd like to normalize JSON data in python using pandas and json_normalize.
Line 33 in the below code works fine. In line 36 I changed the last element to 'number' and get the following error message:
Traceback (most recent call last):
  File "/Users/Home/Downloads/JSONtoCSV/testflattening.py", line 32, in <module>
    print json_normalize(data, 'items', [['address','city'], ['address','company_name'], 'number'])
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/io/json/normalize.py", line 262, in json_normalize
    'need distinguishing prefix ' % k)
ValueError: Conflicting metadata name number, need distinguishing prefix

I think this is because the item 'number' is in conflict with internal variables of pandas. So I need to rename all 'number' items to something else.
I tried that in a first approach using the code in line 28 below - but I get the error message:
ValueError: 'number' is not in list

Sorry, but I am totally new to python - what am I doing wrong?
Thank you!
import pandas

from pandas.io.json import json_normalize

data = [{'address': {
                  'city': 'city A',
                  'company_name': 'company A'},
        'amount': 998,
        'items': [{'description': 'desc A1','number': 'number A1'}],
        'number': 'number of A',
        'service_date': {
                      'type': 'DEFAULT',
                      'date': '2015-11-18'},
        'vat_option': 123},
        {'address': {
                  'city': 'city B',
                  'company_name': 'company B'},
       'amount': 222,
       'items': [{'description': 'desc B1','number': 'number B1'},
                 {'description': 'desc B2','number': 'number B2'}],
       'number': 'number of B',
       'service_date': {
                     'type': 'DEFAULT',
                     'date': '2015-11-18'},
       'vat_option': 456}
       ]

data[data.index("number")] = "numbr"

print data

# working
#print json_normalize(data, 'items', [['address','city'],     ['address','company_name'], 'amount'])

# not working
#print json_normalize(data, 'items', [['address','city'], ['address','company_name'], 'numbr'])

Answer: Got it - "number" seems so be not allowed with pandas. Changing all keys to e.g. "numbr" solves this issue:
eval(repr(data).replace("number", "numbr"))

Thanks to stackoverflow 46734293


Some intuition about the second dual of $l^1$

Question: In Functional Analysis we treated the Hahn-Banach theorem, and if I understood correctly, the dual space of $l^1$ (space of all absolutely summable sequences) is isomorphic to the space of all bounded sequences, $l^\infty$.
However, we also saw that the dual of $l^\infty$ is NOT isomorphic to $l^1$, but is bigger.
In fact, we proved the existence of a nonzero functional $f:l^\infty \to \mathbb{R}$, which satisfies $f(e_n) = 0$ for all $n \in \mathbb{N}$, where $e_n$ is the sequence $(e_n)_k = \delta_{nk}$.
My question is, how is this possible? Every bounded sequence is a linear combination of $e_n$'s, so how can $f$ be nonzero?
Thanks in advance.
Comment: Let $u_N = \sum_{n =1}^N (u)_n e_n$.  In  $l^\infty$ it is weird because If you only know that $f$ is continuous $l^\infty \to \mathbb{R}$,  you can't write $f(u) = \lim_{N \to \infty} f(u_N)$ since  $\|u - u_N\|$ doesn't always $\to 0$ as $N \to \infty$, whereas it does in $l^p$ for every $p  \in [1, \infty[$ (in $l^p$ we can write that $f(u+\epsilon v) \to f(u)$ as $\epsilon \to 0$ for any $u,v \in l^p$, hence $f(u_N) = f(u + (u_N-u))  \to f(u)$ as $N \to \infty$). Now I admit that I don't know how to define the general form of $f \in (l^\infty)^*$, did you ? (we'll probably need  measures)
Comment: So in [$l^\infty$ there are $c$ and $c_0$](https://en.wikipedia.org/wiki/Sequence_space#c_and_c0) the (closed, Banach)  subspaces of convergent and converging to $0$ sequences. In class you proved that there is $f \in (l^\infty)^*$ such that $f(u) = 0$ for any $u \in c_0$, but $f(v) \ne 0$ for some $v$ ? Did you say that $f(u) = \lim_{N \to \infty} \frac{1}{N} \sum_{n=1}^N (u)_n$ for every $u \in c$ is such an example, and use Hahn-Banach for extending it to any $u \in l^\infty$ ?
Comment: We used the result that if $S$ is a linear subspace of $X$ which is not dense in $X$, then there exists a nonzero functional $f$ such that $S\subset ker f$. In this case we chose $S=\{(x)_n \in l^\infty | (x)_n \neq 0 \text{ for finitely many } n\}$
Comment: Your subspace $S$ is not dense in $\ell^{\infty}$ because every element of $S$ is at least 1 unit away from the constant sequence $\{ 1,1,1,1,\cdots \}\in \ell^{\infty}$
Comment: @TrialAndError : if I didn't write too many mistakes, do you see any way for visualizing how $f(u) = \lim_{N \to \infty}\frac{1}{N}\sum_{n=1}^N (u)_n$ for $u \in c$ can be extended to $l^\infty$ ?
Comment: Take a look at this question: http://math.stackexchange.com/questions/47395/the-duals-of-l-infty-and-l-infty
Comment: @TrialAndError : I saw that, but probably as the OP, I understand nothing [of $\beta \mathbb{N}$](https://en.wikipedia.org/wiki/Stone%E2%80%93%C4%8Cech_compactification#An_application%3a_the_dual_space_of_the_space_of_bounded_sequences_of_reals)
Comment: @user1952009 : The accepted answer to that question does not use the Stone-Czech compactification.
Comment: @TrialAndError : the [link in the 1st comment](https://docs.google.com/file/d/0ByszALzBG-7kUlRDUlpwUERyeUE/edit) is useful, but it doesn't say how we define such measures $\lambda$ in general, and how $\lambda(E)$ probably isn't always definable for any weird subset $E \subset \mathbb{N}$.
Comment: @user1952009 : If you started with $\Phi \in (\ell^{\infty})^{*}$, how do you think you might define a finitely-additive set function $\mu E$ for any $E\subseteq\mathbb{N}$?
Comment: @TrialAndError : $\mu(E) = \Phi(I_E)$ (with $I_E$ the sequence of $0,1$ indicating $E$), but what I ask is how defining those for some weird sets $E$, I think that in general it stays [undefinable](https://en.wikipedia.org/wiki/Definable_set), and we can just say "the function extended to the whole $l^\infty$ exists by Hahn-Banach"  but not define it.
Comment: @user1952009 : That function you stated would be defined for all subsets $E$ of $\mathbb{N}$. It would be finitely-additive. Not a problem. And you can see that the variation of $\mu$ would be finite.
Comment: @TrialAndError : when you say it would be defined, do you need the axiom of choice, or can you really define a function $\Phi : l^\infty \to \mathbb{R}$ such that  for [any definable subset $E \subset  \mathbb{N}$](https://en.wikipedia.org/wiki/Definable_set) you can define the value of $\Phi(I_E)$ ? (and say for which $\Phi(u) = \lim_{n \to \infty} u_n$ for any $u \in c$)
Comment: @user1952009 : At this point, I'm not sure what you're asking.
Answer: we can take $Y$ to be the linear span of all $e_{n}$ and $x=\{ 1,1,1,....\}$. Since $x$ is not in $\bar{Y}$, by Hahn-Banach theorem there is a bounded functional $f$ on $l^{\infty }$ such that vanish on $Y$ and $f(x)=1$.


Changing my Clock

Question: I was given a problem in class. Let's say I bought a clock with no numbers on it (has only the hands). Because of the recent time change, I had to change my clock one hour back. In order to do this, I can rotate the clock.
Is it possible to rotate it exactly one hour?
Comment: I don't think so.
Comment: At $2$ AM the angle between the hands is $60^{\circ}.$  At $3$ AM the angle is $90^{\circ}$ at $1$ AM the angle is $30^{\circ}.$  Since rotation of the clock preserves the angle between the hands, the time can't be adjusted by rotating the clock.
Answer: If every specific time on a clock has a certain distance between the two hands, it cannot be that two subsequent hours have the same distance between the hands.
let $\alpha$ be the angle of the short hand with respect to $12$ o 'clock and $\beta$ the angle of the long hand. Then we know that for clocks the rate of change (the speed at which the hands move is different) of $\beta$ is greater than that of $\alpha$, so consider $\alpha '$ and $\beta'$ to be the angles an hour later, we know that $$ \beta - \alpha \neq \beta' - \alpha'$$
Since the angles between the hands are different there is no way to solve this by rotating the clock, as this preserves the angle between hands, and we need the angle to change.
As a concrete example, suppose it is 12 o 'clock. The two hands must be aligned, an hour later we have that the two hands are no longer aligned, we can not fix this by rotating.
Answer: No. If you let the clock run for exactly an hour, the angle between the hands changes (by $30°$ for an ordinary clock).
Answer: why is this hard to solve?
just keep rolling the minutes handle backwards until it reaches the same position

edit for super specific people :
put your finger on the tip of the minutes hand, change the minutes hand counter clock wise until it reaches the tip of your finger again
Comment: why was my solution downvoted without a reason?

Changing my Clock


Let $h :\Bbb Z_{5}\rightarrow S_{z_{5}}$ be the left-regular representation of $\Bbb Z_5$? For each $n$ in $\Bbb Z_5$, compute $h(1)(n)$and $h(3)(n)$.

Question: Let $h :\Bbb Z_{5}\rightarrow S_{z_{5}}$ be the left-regular representation of $\Bbb Z_5$? For each $n$ in $\Bbb Z_5$, compute $h(1)(n)$and $h(3)(n)$.
With this question I am confused with so many terms Like left-regular representation, I have use this term while proofing cayley's theorem but I can't relate this question.
Also when question ask find $h(1)(n)$, so does $(n)$ represents $1$-cycle (identity mapping) or it's something else. If so then how we find $h(1)$.
I know about symmetric groups and isomorphism but not able to proceed with this question.
Comment: $h(m)$ is the bijection which sends $n$ to $m+n$ (everything modulo $5$).
Comment: Left regular representation is just Cayley's embedding of a group in its symmetric group.
Answer: By left regular representation is meant Cayley's embedding of a group into its symmetric group, namely the embedding by left multiplication used in the proof of Cayley's theorem: $h\colon G\to \operatorname{Sym}(G)$, $a\mapsto(g\mapsto ag)$.
In your particular case (the additive group of the integers modulo $5$), we get: $h(1)(n)=1+n, \forall n\in \Bbb Z_5$, and hence:
\begin{alignat}{1}
h(1)(0)=1 \\
h(1)(1)=2 \\
h(1)(2)=3 \\
h(1)(3)=4 \\
h(1)(4)=0 \\
\end{alignat}
and likewise for $h(3)(n)$.

Extra. $\Bbb Z_5$ has $5$ elements and hence any bijection $f\colon \{1,2,3,4,5\}\to \Bbb Z_5$ induces an isomorphism $\varphi_f\colon S_{\Bbb Z_5}\to S_5$, defined by $\varphi_f(\alpha):=f^{-1}\alpha f$. You can prove that under the bijection $\tilde f\colon i\mapsto i-1$, we get: $\varphi_{\tilde f}(h(1))=(12345)$ and $\varphi_{\tilde f}(h(3))=(14253)$.


Find orientation of manifold

Question:
In $\mathbb{R}^3$ consider the the 2-dim manifold
  $$
M:=\left\{(x,y,z)\in\mathbb{R}^3:z=xy\right\}.
$$
  Let the orientation of $M$ be in such a manner that in the Point $(0,0,0)$ the vector $e_3=(0,0,1)$ is the positive orientated normal vector. How is the orientation of M given?

Hello, i do not know if I understand it right.
Do I have to find an orientated Atlas of $M$ that gives an orientation $\sigma$ to which the normal field is positive orientated?
Or something else?
Comment: Hint: One chart suffices!
Answer: If $z=xy$ then the natural choice for parameters is just $(x,y)$ and $R(x,y) = (x,y,xy)$ parametrizes the surfaces. The normal vector field is given by $N(x,y) = R_x \times R_y$,
$$ R_x \times R_y = (1,0,y) \times (0,1,x) = \langle -y, -x, 1 \rangle $$
hence clearly $N(0,0)= \langle 0,0,1 \rangle$ which shows the standard parametrization does in fact have the desired orientation for $z=xy$. No need for atlas here, as you can easily see the normal vector field is well-behaved on the $xy$-plane so the current choice of coordinates will work well for whatever problem we face.

Notice that if we calculate the determinant in your viewpoint we obtain:
$$ det \left[ \begin{array}{ccc} -y & 1 & 0 \\ -x & 0 & 1 \\ 1 & y & x  \end{array} \right] =y^2+x^2+1 \neq 0$$
for all $(x,y) \in \mathbb{R}^2$. Of course, for $z=xy$ there should be a symmetry for exchange of $x,y$ in equations, this allowed my brother to immediately deduce that my original normal vector was calculated wrong. Now our view-points agree, the normal vector field $N(x,y)$ is defined on the whole surface $z=xy$ and the determinant maintains its positive sign throughout. Incidentally, we should normalize $N(x,y)$ if we want it to be a unit vector field, I didn't bother since that is not needed for our interest here.
Comment: @math12 the error is found and I updated the answer so now our views are not in any logical tension.
Comment: @math12 yes, the normal vector field defines an orientation of the surface and it is naturally induced from $R$. From a higher-dimensional perspective, it is a happy accident of three dimensions that this normal vector field defines an orientation, it is the Hodge duality that connects the more natural two-form surface area form. Generally, for $p$-dimensional manifold you'll want a non-vanishing $p$-form to orient the space. But, I must cease talking here now since the website begins to grumble.
Comment: I understand your map and the normal vector calculation. But why does this show that the normal field is positive orientated related  the orientation that is given by the global map?
Comment: To my knowledge the normal field is positive orientated related to the orientation that is given by an orientated atlas (and here your map is indeed an orientated atlas) if $det(\nu(a),\frac{\partial \phi(c)}{\partial t_1},\frac{\partial\phi(c)}{\partial t_2})>0$ where $\nu$ is the normal field, $a\in M, c\in\mathbb{R}^2, \phi(c)=a$. And now the question here is if this is fullfilled for $a=(0,0,0)$, right? Or for all a?
Comment: Then I think in common it is $\mbox{det}\left(\begin{pmatrix}-y & 1 & 0\\x & 0 & 1\\1 & y & x\end{pmatrix}\right)=-x^2+y^2+1$ and so in the special case that $a=(0,0,0)$ then the determinant is to my opinion  1>0. So this shows the positive orientation of the normal field at least in the zero point?
Comment: @math12 given three vectors $v_1,v_2,v_3$ if $det(v_1|v_2|v_3)>0$ then this means that $v_3$ is on the same side of the plane spanned by $v_1,v_2$ as $v_1 \times v_2$. So, I think we agree at the origin. My approach was purely geometric, I just observed that $N(0,0)=\langle 0,0,1 \rangle$. For points on $z=xy$ where $1=x^2-y^2$ your calculation troubles me for it seems the deteminant is zero, yet $N(x,y) = \langle -y,x,1 \rangle$ is still above the plane spanned by $R_x$ and $R_y$. I am missing something here.
Comment: But does the determinant has to be larger than zero for points that are not the zeros point? The task only says that the normal vektor of the zero points is positive orientated related to the orientation. To my opinion that means that for the other points it is not necessary.
Comment: @math12 right, for your question, what we found suffices, it just is bothering me immensely that I cannot cipher the meaning of your determinant being zero! Of course the determinant can be negative or zero, but that signals a linear dependence at the zero point and then a change in handedness for where it is negative. So, I don't see why that determinant is zero since the coordinates $(x,y)$ look good for all values, in other words, the coordinate chart seems regular from the normal vector, but seems otherwise from your determinant. Curses.
Comment: Can I ask you another question here concerning this manifold and this global map? Or should I open a new thread for that? It's about calculating an integral of a 2-form.
Comment: @math12 yes ask a new question. That's how we do it here. I'm working on some things so I'll leave your question to someone else, don't worry, it'll get answered...
Comment: Okay, thanks a lot. So the unit normal field is positive orientated  related to the orientation $\sigma$ that is given by the global map $\phi$ (you called it $R$).

Find orientation of manifold


SQL compact 4 exception

Question: I have a windows form application written in C# and running on a Windows XP machine with SQL compact 4 database. The operating system language is simplified chinese.
I'm facing a strange exception.
"The specified locale is not installed on this machine. Make sure you install the appropriate language pack. LCID 1053"
Why?
The application does work ok on all other configurations/languages.
Answer: That is the locale for Sweden. You can change the locale by modifying the connection string:
http://msdn.microsoft.com/en-us/library/ms174034.aspx
so it would be something like
conString = "....;Locale Identifier=XXXX;..."
where the XXXX can be found on this table: http://msdn.microsoft.com/en-us/goglobal/bb964664
Comment: Where is the error thrown? Can you show the source code of that section? (and if it is a connection string, don't post the pwd, of course)
Answer: I had the same problem SDF created in win8 with version 4.0 and it was not working in XP.
Then I repaired the DB with the following C# code, now its working in both OSs.
<code>SqlCeEngine se = new SqlCeEngine(@"Data Source=|DataDirectory|\mydatabase1.sdf;Persist Security Info=False;");
se.Repair(@"Data Source=|DataDirectory|\mydatabase1.sdf;Persist Security Info=False;", RepairOption.RecoverAllOrFail);
</code>

SQL compact 4 exception