Recording an electric guitar and electric bass

Question: I've been searching around this stackexchange subcategory and I haven't reached a solid consensus.
What I want to do is in the title. I want to record an electric guitar and an electric bass in realtime into my DAW (FL Studio or Cubase).
In the DAW I can use Guitar Rig for effects and pretty much everything else.
I have tried recording like this:
Guitar -> Effects pedal (distort preset) -> Line in (onboard audio chip) -> DAW -> Guitar rig (only simulated speaker, no fx).
The result was quite disappointing, the guitar seems to have a certain 'fuzz' and is quite unintelligible in general. It just sounds like a lot of noise.
The bass was recorded like this:
Bass -> Line in (onboard audio chip again) -> DAW -> Guitar Rig (again, only simulated speakers, no fx).
The result was clearly better, but still it's not at all what I expected. Aside from the line noise (which I can cut out using a noise gate), the bass wasn't as precise as I thought it would be (it sounds far better on a cabinet that we use at our practice studio).
I have noted a few points that I need help with:

Will an audio interface be worth it? We've had no problems with input delay with a standard ASIO driver, so we were easily able to record while playing along with the rest of the tracks.
By being worth it I'm actually asking if the sound quality will improve, be it marginally or significantly. By searching around, I've only seen people discussing that audio interfaces offer far better latencies but nothing on the audio quality itself.
The effects pedal is nothing special. It's quite a low-budget pedal. Could this be the culprit? Would we be better off by recording clean guitars and then doing the effects (distort + amp + speaker) straight from Guitar Rig (or any other amp sim)? As added information, the clean effects sound very well. Any distortion effect sounds quite terrible.
Comment: Line inputs on computers are almost always terrible. Getting a good interface is the first step in computer recording.
Comment: Audio interface is definitely worth it. A decent and affordable audio interface is the Focusrite Scarlett. They come in several different sizes with varying amounts of inputs. Look into it. It's easy to use and should provide you with what you're looking for.
Answer: You have a few questions in there, which is not really the best way to structure questions on Stack Exchange. I'll cover off your main one, and you may wish to ask the others separately:
For any reasonable quality audio work, get a separate sound card / interface. It sounds like the main part of your problem is from incorrect levels - ie your pedal may not be feeding into your line in input at a level it can cope with, and proper interfaces are much better at handling odd impedances or voltages.
An ideal scenario is to hook the guitar up to the interface and to your DAW *clean** - and then run your effects on the effects loop (some interfaces will allow this - if they don't then you could try using the DAW's own effects) - this allows you the flexibility to tweak as often as you like, but even if you set up guitar to effects pedal to interface to DAW, you should be able to get a similar sound to when you play using a standalone amp.
(You have tested using guitar - pedal - amplifier works okay, right?)
You are unlikely to ever find a full sim solution that sounds as good as a standalone guitar amplifier. I am a big fan of digital simulation (I use a lot of Line 6 stuff on stage) but I would still suggest a proper valve amp if you want the best guitar sound.
Comment: I would go with a USB interface since they are just as good or better and easier to hold on to when you get a new computer.
Comment: First of all, thank you for your answer and edit. What you're saying makes sense about the input levels, basically I get the feeling it's clipping when it's actually not (in the DAW at least). And since the clean effects are far quieter, it would also explain why the clean effects sound ok.
So in the end, having an audio interface is clearly the better way. I will do as you said and will purchase an audio interface.
And yes, guitar - pedal - amplifier works very well. Could you also explain if a PCI-E sound card would be appropriate when compared to a USB audio interface?
Comment: I'd always go USB as well - then you typically have them powered separately if needed (which helps lower the noise floor)
Answer: "Line in" is an input for an audio source at 'line level', but an unamplified guitar signal is an 'instrument level' audio source. As others have suggested, you need an interface.
This article should help understand the difference between line level & instrument level etc:
https://www.sweetwater.com/sweetcare/articles/whats-the-difference-between-mic-instrument-line-and-speaker-level-signals/#:~:text=Instrument%20level%20signals%20fall%20between,signal%20up%20to%20line%20level.


How to have multiple colors in a listview row?

Question: I'm using C#/Winforms.
I want to have a listview with several "background" colored rows. Colors are defined by a ColorPicker. My code works but all rows are just in one color.
A brief explanation:
If the user chooses a color (below "Cor (Clique aqui para alterar)" and clicks on "Add highlight color" it is added to the list with the following line:
lstHighlightColors.Items.Add(lblColorPicker.BackColor.ToString());

but i can't seem to find a solution to have multiple colors. I want to fill the rectangles according to the color that was chosen in that row.
Here's my code:
            var highlightColorslst = lstHighlightColors.Items[e.ItemIndex];
            string text            = highlightColorslst.Text;
            text                   = text.Replace("Color", "");
            Brush myBrush          = new SolidBrush(lstHighlightColors.ForeColor);
            Pen rect               = new Pen(lblColorPicker.ForeColor);

            lstHighlightColors.Items[e.ItemIndex].BackColor = lblColorPicker.BackColor;
            Brush fillColor       = new SolidBrush(lstHighlightColors.Items[e.ItemIndex].BackColor);

            e.Graphics.DrawRectangle(rect, new Rectangle(e.Bounds.Left + 2, e.Bounds.Top + 2, 22, e.Bounds.Height - 4));
            e.Graphics.DrawString(text, new Font(FontFamily.GenericSansSerif, 8), myBrush, (e.Bounds.Left + 25), e.Bounds.Top + 2);
            e.Graphics.FillRectangle(fillColor, new Rectangle(e.Bounds.Left + 3, e.Bounds.Top + 3, 21, e.Bounds.Height - 5));

            e.DrawFocusRectangle();

Here's an image of the working code:
Answer: Assuming that, you have a single-column header ListView and the View property is set to View.Details.
The .ToString() method of the Color class does not return a color identifier (name, hex, int...), it returns - as what you have in your list shown above - the object's type and either something like "Color [Black]" for the named/known colors and "Color [A=255, R=25, G=207, B=183]" for the nameless ones.
You need to call the Color.Name property when you add one into the list. The property returns either the name of a known color (Black) or a hex representation (ffe43e19) of a nameless one.
lstHighlightColors.Items.Add(lblColorPicker.BackColor.Name);

In the drawing part and for each item you draw, get the color's name/hex and call the proper Color.From* method to create it.
Exanple
// +
// using System.Globalization;

private void listView1_DrawItem(object sender, DrawListViewItemEventArgs e)
{
    var color = GetColor(e.Item.Text);
    var colorRec = new Rectangle(e.Bounds.X + 2, e.Bounds.Y + 2, 22, e.Bounds.Height - 4);
    var textRec = new Rectangle(colorRec.Right + 2, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height);

    if (e.Item.Selected)
        e.Graphics.FillRectangle(SystemBrushes.Highlight, e.Bounds);
    else
        e.DrawBackground();

    using (var br = new SolidBrush(color))
    using (var pn = new Pen(e.Item.ForeColor))
    {
        e.Graphics.FillRectangle(br, colorRec);
        e.Graphics.DrawRectangle(pn, colorRec);
    }

    TextRenderer.DrawText(e.Graphics, e.Item.Text, e.Item.Font, textRec,
        e.Item.Selected ? SystemColors.HighlightText : e.Item.ForeColor,
        TextFormatFlags.VerticalCenter | TextFormatFlags.Left);
}

private Color GetColor(string name)
{
    Color color;

    if (int.TryParse(name, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out var hex))
        color = Color.FromArgb(hex);
    else
        color = Color.FromName(name);

    return color;
}

Side Note: If you just need what you get from this answer, then I recommend replacing the ListView with a ListBox. More suitable for this requirement.


não aparece nada na tela quando add o router

Question: quando eu tiro o Route, tudo funciona normalmente, ja tentei copiar o codigo do prof e da o mesmo erro, e preciso criar outro route pra agir como uma pag diferente, eu ja isntalei o npm do react-router-dom, e também quando tento importar o route sozinho ele importa do react-router
import React, { useState }  from "react";
import { v4 as uuidv4 } from "uuid";
import { BrowserRouter as Router, Route} from "react-router-dom";

import Tasks from "./components/tasks";
import AddTask from "./components/addTask";
import Header from "./components/header";

import './App.css'
const App = ()=>{

  const [tasks, setTasks] = useState([
    {
      id:1,
      title:"estudar programação",
      completed: false
    },
    {
      id:2,
      title:"ler livros",
      completed: true
    }

  ]);

  const handleTasksAddition = (taskTitle)=>{
      const newTask = [...tasks,{
        title:taskTitle,
        id: uuidv4(),
        completed:false
      }]

      setTasks(newTask);
  }

  const handleTaskDeletion = (taskId) =>{
    const newTasks = tasks.filter( task => task.id !== taskId)

    setTasks(newTasks)
  }

  const handleTaskClick = (taskId)=>{
    const newTask = tasks.map(task => {
      if(task.id === taskId)return{...task, completed: !task.completed}

      return task

    })

    setTasks(newTask)
  }
  return (
  <Router>

           <Route
                    path="/"
                    exact
                    render={() => (

                            <AddTask handleTasksAddition={handleTasksAddition} />
                            <Tasks
                                tasks={tasks}
                                handleTaskClick={handleTaskClick}
                                handleTaskDeletion={handleTaskDeletion}
                            />

                    )}
                />

  </Router>
  )

}

export default App;

esse é o codigo, e o problema aparentemente ta aqui no final.
Answer: Estou com um problema similar, mas pesquisando na internet descobri que a nova versão do router (v6) muda algumas coisas, como por exemplo:

O antigo switch recebeu algumas mudanças e agora se chama Router. E também todos os Routes precisam estar dentro dele.

A propriedade exact não é mais necessária (ou não exite?).

Então é necessário importar o Routes:
import { BrowserRouter as Router, Routes, Route} from "react-router-dom";
E coloca-lo entre o Router e o Route:
return (
    <Router>

            <Routes>
                <Route
                    path="/"
                    render={() => (

                            <AddTask handleTasksAddition={handleTasksAddition} />
                            <Tasks
                                tasks={tasks}
                                handleTaskClick={handleTaskClick}
                                handleTaskDeletion={handleTaskDeletion}
                            />

                    )}
                />
            </Routes>

    </Router>
)

Isso, claro, se estiver usando a versão 6. Espero ter ajudado.


Prove the existence of uniformly distributed sequence of reals in $[0,1]$

Question:
A sequence of reals $\{x_n\}$ in $[0,1]$ is uniformly distributed iff for every $a<b$ in [0,1], $$\lim_{n\to\infty}[\sum_{j=1}^n 1_{(a,b]}(x_j)]/n=b-a$$Prove that such a sequence exists. (Hint: Show that it suffices to show the above result holds for rational values $a$ and $b$.

Here is my approach:
Take $a<b, a,b\in [0,1]$. Let $\{x_j\}$ be a sequence of real numbers in $[0,1]$.
Define random variables $X_j=1_{(a,b]}(x_j)$, thus getting a sequence of random variables $\{X_j\}$. Then $P(X_j=1)=b-a, P(X_j=0)=1-(b-a)$ for every $j$, and they should be independent since $x_j\in (a,b]$ for any $j$ should be independent events. Then we get $E(X_j)=b-a$ for every $j$. Define, $S_n=\sum_{j=1}^n X_j$ and we get $\frac{S_n}{n}\to b-a$ almost surely by Strong Law of Large Numbers, which is the condition we want to show.
Now I have two questions:

Is my approach to this question correct? I'm a bit unsure that such random variables should exist in [0,1] though I feel that they should. Is this something I need to prove separately?
After I got through the question, I realized that I didn't use the hint at all, and I think the hint comes into play because the convergence in Strong Law of Large Numbers is almost surely. Therefore I need to take care of the null sets where the above result doesn't hold, but I'm a bit stumped on how to do that, and not sure how to show that it "suffices" to prove the above for rational $a,b$.

I would like some feedback on my proof and help on the remaining questions that I have! Thanks!
Comment: https://en.wikipedia.org/wiki/Equidistribution_theorem (not a proof you were asked for)
Comment: @EthanBolker I am unsure how that relates here :/
Comment: It is another way to think about equidistribution so I thought the  comment possibly useful.
Comment: @EthanBolker I'll give it a read, thanks!
Answer:
Lemma. $(x_j)$ is equidistributed if and only if, for each rationals $0 \leq a < b \leq 1$,
$$ \lim_{n\to\infty} \frac{1}{n} \sum_{j=1}^{n} \mathbf{1}_{(a, b]}(x_j) = b-a. \tag{*} $$

Proof. Assume that $\text{(*)}$ holds for all rationals $0 \leq a < b \leq 1$. We want to show that $\text{(*)}$ holds for any reals $0 \leq a < b \leq 1$. To this end, we adopt the usual squeezing argument.

Choose $a_k, b_k  \in \mathbb{Q} \cap [0, 1]$ such that $a_k \uparrow a$ and $b_k \downarrow b$ as $k \to \infty$. Then $\mathbf{1}_{(a, b]}(x) \leq \mathbf{1}_{(a_k, b_k]}(x)$ for all $x \in \mathbb{R}$, and so, for each fixed $k$,
$$ \limsup_{n\to\infty} \frac{1}{n} \sum_{j=1}^{n} \mathbf{1}_{(a, b]}(x_j)
\leq \lim_{n\to\infty} \frac{1}{n} \sum_{j=1}^{n} \mathbf{1}_{(a_k, b_k]}(x_j) = b_k - a_k. $$
Letting $k \to \infty$ shows that
$$ \limsup_{n\to\infty} \frac{1}{n} \sum_{j=1}^{n} \mathbf{1}_{(a, b]}(x_j)
\leq b - a. $$
In this time, we choose $a_k, b_k \in \mathbb{Q}\cap [0, 1]$ such that $a_k \downarrow a$ and $b_k \uparrow b$ as $k \to \infty$. Then, as before,
$$ \liminf_{n\to\infty} \frac{1}{n} \sum_{j=1}^{n} \mathbf{1}_{(a, b]}(x_j)
\geq \lim_{n\to\infty} \frac{1}{n} \sum_{j=1}^{n} \mathbf{1}_{(a_k, b_k]}(x_j) = b_k - a_k $$
and letting $k \to \infty$ gives
$$ \liminf_{n\to\infty} \frac{1}{n} \sum_{j=1}^{n} \mathbf{1}_{(a, b]}(x_j)
\geq b - a. $$

Combining two estimates shows that $\text{(*)}$ does hold as required. ////

Let $(U_j)$ be a sequence of i.i.d. random variables uniformly distributed on $[0, 1]$. Then for each rationals $0 \leq a < b \leq 1$, SLLN tells that
$$ \lim_{n\to\infty} \frac{1}{n} \sum_{j=1}^{n} \mathbf{1}_{(a, b]}(U_j) = b-a \quad \mathbb{P}\text{-a.s.}$$
So, if we consider the event
$$ \Omega_0 := \bigg\{ \omega : \lim_{n\to\infty} \frac{1}{n} \sum_{j=1}^{n} \mathbf{1}_{(a, b]}(U_j(\omega)) = b-a \text{ for all } a, b \in \mathbb{Q} \text{ with } 0 \leq a < b \leq 1 \bigg\}, $$
then $\Omega_0$ is the countable intersection of events having full probability, hence $\mathbb{P}[\Omega_0] = 1$. Moreover, by Lemma, for each $\omega \in \Omega_0$ the sequence $(U_j(\omega))_{j=1}^{\infty}$ is equidistributed. So by setting $x_j = U_j(\omega)$ for any choice of $\omega \in \Omega_0$, we obtain an equidistributed sequence.

As a totally different approach, one may give a concrete example. Indeed, choose $\alpha \in \mathbb{R} \setminus \mathbb{Q}$ and set $x_n = \alpha n \text{ mod } 1$. Weyl's criterion immediately tells that $(x_j)$ is equidistributed over $[0, 1]$.
Comment: I understand now! We were concerned with possibly having an uncountable union of null sets (which may not be null together) if we work with reals only right? But by limiting the argument to the rationals, we get that $\Omega_0$ is a countable intersection, which means that ${\Omega_0}^c$ is a countable union, thus null itself as well?
Comment: Thank you for your answer! For the second approach, I'm new to probability and don't know about Weyl's criterion :/. With that said, I have a couple questions: 1). Does my choice of random variables work as well? I was under the impression that the mean of our random variables should be $b-a$, but if $U_j$ are uniform on $[0,1]$, their mean is 0.5 isn't it? 2.) Could you elaborate why it suffices to show this for rationals, and how to prove that it suffices to show for rationals? Thank you.
Comment: @Sank, Notice that $$ \mathbf{1}_{(a, b]}(U_j) = \begin{cases} 1, & U_j \in (a, b] \\ 0, & \text{otherwise} \end{cases} $$ is a Bernoulli random variable with the parameter $b-a$.
Comment: Ah, I see that. How can I extend $U_j$'s to a sequence of reals $\{x_n\}$, is that just by evaluating $U_j$'s at given points? Also, I'm still bit unsure why it suffices to show that the above is true for rational $a,b$. I believe your proof after "So we have" shows that it suffices (correct me if I'm wrong), but I'm not sure why that is true, or why we need that :/
Comment: @Sank, I expanded my answer. :)


What would happen if a team made a pitstop in less than 2 seconds?

Question: I think I read a thread saying that this season (2022), F1 pitstops must be at least 2 seconds and cannot go lower. I think that this gives a disadvantage to Red Bull since their pitstop timing is superb.
I just want to know, what would happen if a team made a pitstop in less than 2 seconds?
Comment: Not that it really matters, there's no strict "2 second rule", but instead [rules which govern the sequencing of the events in the pit stop](https://www.espn.in/f1/story/_/id/31706484/fia-attempt-slow-pit-stops-more-dangerous); _practically_ these mean that you can't do a pit stop in less than 2 seconds.
Answer: I don't know where you read this, but it's not quite accurate.
What was happening before - and what the FIA have outlawed for 2022 - is that teams were using automated systems to predict when each stage of their pit-stop was going to happen, allowing them to react to it faster than would otherwise be possible - for example, releasing the front jack at the exact instant the last wheel went on. Reacting to events before they've happened naturally carries risks - namely, that the event actually hasn't happened, and you're now releasing the car in an unsafe condition.
The FIA outlawing these systems, and reintroducing human reaction times, means that pitstops are slightly slower and more deliberate, such that making a pitstop in less than 2 seconds is now much harder than before. However, doing so is neither illegal nor impossible: at the 2023 Qatar Grand Prix, McLaren broke the world record for fastest pitstop by changing Lando Norris' tyres in just 1.80 seconds. They faced no punishment and were awarded the DHL Fastest Pit Stop award for that race.
Comment: "they would most likely come under investigation by the FIA." <- this is sort of the crux of the question to me - is there any information available on what sort of penalties would be applied if teams were found to be breaking this rule?
Comment: Just a nitpick point - I think these rules were first introduced in the 2021 Belgian GP (pushed back from the Styrian GP) via a technical directive, which also introduced a minimum time of 0.15s to complete certain tasks.


Put blocks, views, etc in git for other developers

Question: Keep in mind that I'm fairly inexperienced with drupal!
I use a docker based setup for my development environment for docker 7. I'm building a site that involves a front page that will be changed infrequently but I still want the key users to change what's necessary.
I'm firing up the drupal docker with my_theme mapped to /var/www/sites/all/themes/my_theme and the following is executed in the docker container:
# Install zen theme (needed for the sub-theme)
/usr/local/bin/drush -r /var/www en zen -y
# Install base modules
/usr/local/bin/drush -r /var/www en views, entity, pathauto, devel_node_access, backup_migrate, imce, link_css, jquery_update, ckeditor, farmmix -y
# Set our theme as default
/usr/local/bin/drush -r /var/www vset theme_default farmmix
# Disable old theme
/usr/local/bin/drush -r /var/www dis bartik -y
# Enable/Install permissions
/usr/local/bin/drush -r /var/www en views_ui, entity_token, views_content, admin_devel, color, contextual, dashboard, field_ui, file, image, list, locale, number, options, overlay, search, shortcut, taxonomy -y

This installs and enables the modules I need for development. What this does NOT do is create content types, blocks, views, etc that might be necessary for this site.
It would be ridiculous to recreate these essentials for the site each time a new instance is spun up (e.g: another developer starts to work on it). How can I put content types, blocks, views etc in git so if another developer checks it out, he can continue where I just left off?
Only backup and migrate helps?
Answer: You have several modules that allow to export configuration changes (like views, blocks, content types etc) into code. One is features and the other is configuration Features is much more heavily used and configuration isn't supported by the security team, so I tend to use Features. There are a number of good tutorials on using Features, like this one. Once you create a feature, it will exported into a code-based collection of files under custom modules, which you can then share with git.
The one caveat is that using Features (or any config changes module for that matter) in a collaborative environment can become tricky: team members have to be mindful of the branches and feature versions they are working with. For example, switching from a branch where feature was installed to a branch that does not have that feature can throw fatal errors because GIT will remove the feature files according to the branch but the database will still look for the feature. In such a case you can disable the feature before switching branches or install the feature in all the branches you are working in.


Sending webform submissions to email with csv export of submissions

Question: I need help, because I dont know how to create csv file from submissions and send it as attachment in submission mail.
I have form with some field and after sending webform I need to create custom csv in specific format with values from webform and all this send it like attachment of normal submission mail.
Is there some modul for creating csv from webform, or I need to cook my own custom module to create it?
Thanks a lot
Comment: webform already can create a CSV downloadable file. So it has the code to make the csv output -- you just need to find the right function to call to get the raw output. And then stuff it in an email. You probably need a relatively simple custom module.
Answer: As tenken wrote, Webform module has a function for that, namely webform_results_export
Do you really want a single line of CSV e-mailed when a form is submitted, rather than periodic downloads?  You could modify your e-mail template to print each value, comma, value, but it wouldn't be an attachment.  If you absolutely need an attachment some custom code and/or Rules is the way to go.


should both scores of 2 time points be of same scale in mixed ANOVA

Question: I am running mixed ANOVA as repeated measurement analysis for cognitive score at 2 time points for 2 groups (blood pressure low vs. High). The the score at time 1 was normally distributed and at time 2 was not normally distributed so I QURT transformed.
Can I still use mixed ANOVA? or both scores should be of same scale/ units? if both should be same, what should i do, transform time 1 or use the original time 2?
Answer: You cannot transfom one variable but not the other. This simply doesn't make any sense, they need to be on the same scale (otherwise you trivially get a main effect of time).
Usually, people are overcutious with the normality assumption disregarding several important aspects:

Normality testing is potentially "essentially useless". So shouldn't be used for your different time points.
The assumption of normality does not concern the raw data, but the residuals, see here or here.

I would probably go with the raw values but plot those and the residuals and only consider alternatives if the deviations are dramatic.


How to proceed after update.php fails due to memory limit?

Question: Sometimes i have a "Fatal error: Allowed memory size exhausted" on certain drupal installations with low php memory limit during module or core updates. After such an error i regularly increase this value with the help of my webhoster to avoid this for future updates...
But on the drupal side i'm lost a bit. The system report shows no indication that the update has to be done again and doing it manually shows that there's nothing to update. But this process failed before...
How do i find out if something went wrong during the update.php process?
Comment: This post handles everything you can do in order to deal with blank pages/memory issues: https://www.drupal.org/node/158043 The first thing I would check is the PHP error log on my server. Not sure where your php error log is located: Try phpinfo() and check for "error_log"
Answer: Short Answer
You can't. Though comment F0ns's comment is a good start, depending on your PHP skills you may find this frustrating to impossible.
Long Answer
I am not sure that the easiest resolution is to deal with the (possible) problem after the event.
I would not normally suggest this as an answer except that you begin your question with 'Sometimes', implying that this a is a workflow consideration rather than a specific bugfix.
You should consider your upgrade process in general. Ideally you would put the site into maintenance mode if you absolutely must perform the upgrades on a live site, so there would be no changes to the site during the process. You should always take a database backup before performing core or contrib updates, and this is made easy using backup_migrate module. If you are updating core backup the files as well (if it is contrib simpler to just download previous version)
As long as you know which updates you are applying (I do not recommend applying many at the same time), and what version of core/module you are upgrading from, then you can now easily return to your pre-upgrade state by overwriting the db and files, rather than trying to pick apart potential problems caused by a failed upgrade.
Depending on the usage of your site, it might be preferable preferable to limit administrative access to the site temporarily (or put it into maintenance mode), perform updates on a local clone of the site, and overwrite the live version with the tested, working local version, restoring administrative access.
Comment: Thanks for your thoughts on this. In the end it's probably less time consuming to backup everything and update a local clone first... I'll consider your suggestions for my future workflows.


On a formula of the norm of an element of a finite extension of a field

Question: Theorem
Let $F$ be a field.
Let $K$ be a finite extension of $F$.
Let $[K : F]_i$ be the inseparable degree of $K/F$.
Let $\bar{K}$ be an algebraic closure of $K$.
Let $S$ be the set of $F$-embeddings of $K$ into $\bar{K}$.
Let $\alpha \in K$.
Then $N_{K/F}(\alpha) = (\prod_{\sigma \in S}\sigma(\alpha))^{[K : F]_i}$
This is proved in Theorem 60 in page 39 of the lecture note written by Pete L. Clark.
I don't understand the proof.
Would any one please enlighten me?
EDIT
Why down votes??
Asking for help to understand a proof should be frowned upon?
EDIT
I understand the prerequisites for the proof, i.e. the content of section 6 and Corollary 58.
EDIT
Related question 1,
Related question 2
EDIT
Let $f(X)$ be the characteristic polynomial of $\alpha$.
Let $g(X)$ be the minimal polynomial of $\alpha$.
By Corollary 58, $f(X)$ = $g(X)^{[K:F(\alpha)]}$.
The set {$\sigma(\alpha); \sigma ∈ S$} is the set of the roots of g(X).
However, it is not clear to me that the equation $N_{K/F}(\alpha) = (\prod_{\sigma \in S}\sigma(\alpha))^{[K : F]_i}$ follows immediately.
Would anyone please explain why the equation follows other than just saying it is straightforward?
EDIT
It's amazing that some people regard questioning a proof as an attack to the author's credibilty. Everybody makes a mistake. Even Grothendieck made a non-trivial mistake(see Misconceptions About $K_{X}$ by Kleiman).
I think this attitude is harmful to healthy development of mathematics.
I'm not claiming that the proof is wrong, though.
EDIT
To anyone who thinks the proof is straightforward, please explain to me in detail.
I am not as smart as you.
EDIT
It's surprising that no one explained the proof so far.
I believe every step of any proof can be reduced to (really) trivial statements.
If you think it's straightforward, please reduce it to more trivial statements that anybody who has basic knowledge of abstract algebra can understand.
Comment: For my part, I'm sorry that you read my notes (which are, by the way, signalled on my webpage as being a first, rough draft) and found something not to your liking.  But "it's obvious that the proof is too terse" is not constructive feedback: it doesn't give me any indication what to change.  If someone else has a suggestion for how to improve this part of the exposition, please do say so.
Comment: If I may venture a piece of advice: when you are reading a text and come to a point that seems obscure to you, usually the fastest and best remedy is just to consult a different text. In this case any reasonably serious field theory text should do: for instance, see Section 8 of Patrick Morandi's *Field and Galois Theory*, Section 6.5 of Lang's *Algebra*, and so forth.
Comment: @Arturo I thought it's obvious that the proof is too terse even assuming Corollary 58 etc.. Now I know some people do think otherwise. Perhaps it's straightforward for smart people, but alas I'm not that smart.
Comment: @Pete L. Clark I edited my question. I believe my question is clear enough now.
Answer: I don't think the downvotes are helping the situation.  In case anyone is downvoting the OP's question out of some sense of solidarity with / loyalty to me: thanks, but please don't.
On the other hand, exactly what the OP wants to ask is not clear, even to me.  "I don't understand the proof.  Would any one please enlighten me?" isn't specific enough to be helpful.  In fact, more than a couple of days ago now, this started with a comment the OP left to me elsewhere on this site:
"@Pete I think the proof of Theorem 60 is incorrect (I'm not talking about some obvious typos there). Please forgive me if this is my mistake."
Let me start by saying that I most certainly do want errors in my mathematical writings to be brought to my attention.  At this point though I have about 2000 pages of such things available on the internet, so it is a nontrivial matter as to how to best deal with adding / editing / correcting these things.  Generally at any point in time I am more mentally present and interested in making these changes on some documents than others (if anyone cares, at the moment it is honors calculus / undergraduate analysis, geometry of numbers and quadratic forms which have most of my attention).
What I'm trying to say is: at the moment I don't really have a well thought out system to deal with modifications to the product I've already made available.  People write me to suggest changes and corrections fairly frequently (a few times a month, on average), and I'm sorry to say that I address some but not all of these suggestions in a timely fashion.  For now, if you want to maximize the chances that a correction gets made sooner rather than later, then it helps to give me as much information as possible and give me as concrete a task as possible.  For instance:
1) Please include specific information about which notes you are looking at: a link to a particular file on my webpage is ideal.
2) If you think that I've made a mistake, please say exactly what you think the mistake is.  If you think you know the correction, of course please tell me.
3) If you just didn't understand something in my notes, or have a natural followup question, or are seeking references on something I alluded to too casually (N.B.: I have gotten much better in recent years at including precise, formal references even in lecture notes for my undergraduate classes), then you might want to try asking someone else first, or asking on this site.  When it comes to teaching, I will naturally put my own students, and students at my own university, first.  Anyway, when it comes to questions about my expository notes, I promise you that I am not uniquely or best qualified to answer them.  On the contrary, for almost anything that I have written about, there are people here who are more qualified to address your questions than I am.
If you do ask a question here that comes from my own writings, please ping me.  I will be interested to read it, even if I am not one of the ones to answer it.
Comment: @Will I want you to answer me here. If you think this is personal, don't write personal matters here in the first place.
Comment: Pete, see the 20 comments at http://math.stackexchange.com/questions/136456/ideal-theoretic-proof-of-the-second-inequality-of-global-class-field-theory along with those at http://mathoverflow.net/questions/95225/ideal-theoretic-proof-of-the-second-inequality-of-global-class-field-theory and perhaps my email to Franz if your curiosity extends that far. I did not downvote either, but there is a pattern.
Comment: @Will Somehow you seem to have developed ill feelings toward me. Would you mind to tell me what made you so if that is the case? And if you want to say something to me, say it straight to me.
Comment: @Will "but there is a pattern" So what is the pattern? And what's wrong with that?
Comment: @MakotoKato, please email me. Click on my profile. If you do not see an email address for me, search at http://www.ams.org/cml/ and use the gmail address if possible. I really do not know enough about you at this stage.
Comment: @Pete *"In case anyone is downvoting the OP's question out of some sense of solidarity with / loyalty to me: thanks, but please don't."* Well said and fair enough. I respect you on this one.
Comment: @Pete L. Clark I edited my question. I believe my question is clear enough now.
Answer: What exactly you don't understand in that proof? It is heavily based on former results in the same notes, and if you know already that the conjugates of certain element are the images of this element under the different embeddings $\,K\to \overline{K}\,$, each being repeated precisely $\,[K:F]_i\,$ , then...well, then we're done!
Comment: He certainly defines norm as a determinant in page 38, immediately before prop. 57, but then in page 39 prop. 60 he proves it is just the product of all the embeddings of the field in an alg. closure, each factor appearing an ammount of times equal to the inseparable degree of the extension...*this* is the theorem you need to understand in depth.
Comment: Perhaps Mr. Clarke's defintion of $N_{K/F}(\alpha)$ and yours are different. Let $\alpha_{L}$ be the $F$-linear map K → K definded by x → $\alpha.x$. Then $N_{K/F}(\alpha)$ is the determinant of $\alpha_{L}$.
Comment: That's exactly the theorem 60 in page 39 whose proof I don't understand. And that's why I'm asking.
Comment: I know that, but you haven't yet answered Arturo's question: do you understand Cor. 58 and section 6? This is what's needed to understand th. 60!
Comment: I understand Cor.58 and section 6.
Comment: I edited my question. I believe my question is clear enough now.
Answer: Well the theorem is a bit too hastily stated, for example if you happen to pick $\alpha \in F$, then $f(t) = (t-\alpha)^n$ and has only one distinct root.
The correct statement is :
Let $K/F$ be a field extension of degree $n < \infty$ and separable degree $m$. Let $\overline{K}$ be an algebraic closure of $K$. Let $\alpha \in K$ and let $f(t)$ be the characteristic polynomial of $\alpha \bullet \in End_F(K)$. Let $\sigma_1 \ldots \sigma_m$ be the distinct $F$-algebra embeddings of $K$ into $\overline{K}$. Then the factorisation of $f(t)$ on $\overline{K}$ is $f(t) = \prod_{i=1}^m (t- \sigma_i(\alpha))^{n/m}$.
First, let $K_0 = F(\alpha)$, $n_0 = [K_0 : F]$, $m_0$ be the separable degree of $[K_0 : F]$, $\tau_1 \ldots \tau_{m_0}$ be the embeddings of $K_0$ into $\overline{K}$, and $f_0(t)$ be the minimal polynomial of $\alpha$ over $F$.
Then, by corollary 58, $f(t) = f_0(t)^{[K : K_0]} = f_0(t)^{n/n_0}$.
According to the proof of theorem 38, each $\tau_i$ is the restriction to $K_0$ of $m/m_0$ many embeddings $\sigma_j$, therefore
$\prod_{i=1}^m (t- \sigma_i(\alpha))^{n/m} = \prod_{i=1}^{m_0} (t- \tau_i(\alpha))^{n/m_0} $, so we only need to prove that $f_0(t) = \prod_{i=1}^{m_0} (t- \tau_i(\alpha))^{n_0/m_0}$.
From now, suppose we are in the case $K = K(\alpha)$. Let $K_s$ be the separable closure of $F$ in $K$, so by Proposition 50, $K/K_s$ is purely inseparable and $K_s/F$ is separable. By corollary 47, there is an integer $a\ge 0$ such that $K_s = K(\alpha^{p^a})$.
Let $g(t)$ be the minimal polynomial of $\alpha^{p^a}$ over $F$.
Then $f(t) = g(t^{p^a})$, because $g(\alpha^{p^a}) = 0$ and they have the same degree $n = p^a m$.
Meanwhile, $(t - \sigma_i(\alpha))^{p^a} = (t^{p^a} - \sigma_i(\alpha^{p^a}))$ so we only need to prove that $g(t) = \prod_{i=1}^m (t - \sigma_i(\alpha^{p^a}))$.
So we only need to prove the theorem when $\alpha$ is separable.
But then this is clear : the $\sigma_i(\alpha)$ are roots of $f(t)$ because $\sigma_i$ are embeddings of $F$-algebras, and every factor in the product is distinct, so the product has to divide $f(t)$, and both polynomials have the same degree, so they must be equal.
Comment: Thank you, Mercio. Your proof is basically the same as I had in my mind. By the way, if $\alpha \in F$, since $\sigma(\alpha) = \alpha$, $N_{K/F}(\alpha) = (\prod_{\sigma \in S}\sigma(\alpha))^{[K : F]_i}$ still holds.


PHP AJAX button click counter

Question: i want to make a button click counter. When you click the button the text from it changes, when the button is clicked i want to write to the database but i can't manage this.
<button type="button" class="btn btn-info" style="width:90%;" id="textChanger" onclick="counter;">
   XXXX XXX XXX
Show Number

</button>

document.getElementById("textChanger").onclick= function(){
        document.getElementById("textChanger").innerHTML="
   <?php echo $nrTelefonAnunt ?>
";
         }

this is the code that i manage the text change, now what can i do to write to the database, i tried some methods but none worked
Comment: Assuming the DB is not on your local machine, you'll need to make a remote call so you can do some server side scripting.
Answer: Thanks everybody for the answers i manged by adding this:
$('#textChanger').click(function(){
    $.ajax({
        url : 'rate.php?idanunt="<?php echo $idAnunt ?>"',
        type : 'post',
        success : function(data){
        }
    });
});

Answer: Try this

<button type="button" class="btn btn-info" style="width:90%;" id="textChanger" onclick="counter;">1</button>

Answer: Try this

 <button type="button" class="btn btn-info" style="width:90%;" id="textChanger" onclick="counter;">
   XXXXX
Show Number

</button>

PHP AJAX button click counter


Transformations' order

Question: I get why you can move the curve for (a*(x-b))^2 where ever you want horizontally and then stretch as you want and it stays in the same place.
Why does (ax-b)^2 behave any differently(and rather weirdly)?
I get how the parentheses force the order in the first one. I want to know the reasoning behind why the second one functions (pun intended) the way it does.
Please explain in as detail and verbosely as you wish.
Thanks.
Comment: How does $(a(x-b))^2$ behave strangely relative to $(ax-b)^2$ when $(ax-b)^2=(ax-ab/a)^2=(a(x-b/a))^2$, which is $(a(x-b))^2$ shifted elsewhere?
Comment: Once you change the value of b for the second one and then try to change the value of 'a' it moves horizontally. (I made graphs with variables on desmos)
Comment: Yes. The second expression moves horizontally *and* stretches itself as you vary $a$, and this horizontal movement and stretching is described exactly by the answer below.
Answer: The second function could also be written as
$$\left(a\left(x-\frac{b}{a}\right)\right)^2$$
if you want to put it into a form that is similar to the first one.
Comment: Doesn't really explain why it behaves like that. Thanks anyways
Comment: @user134505 The "why" is a very subjective thing. If you ask me, my form shows clearly that the function behaves like the standard square function, shifted by $\frac{b}{a}$ and then streched by a factor of $a$. *Why* does it do that? Well, because it **is** a standard square function, shifted by $\frac{b}{a}$ and then streched by a factor of $a$. So, how else would it behave?
Comment: Woah, so that's why it jumps around since just b is not(but b/a) involved in shifting .
Comment: @user134505 Exactly. Or, you could look at it this way: In the first case, you shift first, and then stretch. Therefore, the stretch also affects the shift. In the second case, you stretch only x, and then you shift. But now, when you apply the shift, $x$ is $a$-times bigger, so it "sees" any shift as being $a$-times smaller, i.e. it "sees" only a shift by $\frac{b}{a}$ instead of a shift by $b$. (If you suddenly became twice as big, everything around you would appear half the size)

Transformations' order


Finding posterior density of discrete distribution

Question: Consider a process in which someone is asked to do a task and iff they succeed, they are allowed to repeat the task. Let $X$ be the number of times the task is successfully completed and suppose that different attempts at the task are iid and the probability of success on any one attempt is $0 \le \theta \le 1$.
$$
\displaystyle P(X=x) =
\begin{cases}
1-\theta & \text{if } x = 0 \\
\theta(1-\theta) & \text{if } x = 1 \\
\theta^2 & \text{if } x = 2 \\
\end{cases}
$$
Suppose in addition that we observe $X=1$ and that the prior density for $\theta$ is $\text{Unif}[0,1]$. The first task is to find the posterior density for $\theta$.
\begin{align*}
\displaystyle f(\theta;{\bf x}) &= \frac{f({\bf x}; \theta)f(\theta)}{C}
\end{align*}
where $c$ is a constant independent of $\theta$. How does one proceed from here? I think we can drop $f(\theta)$ from the numerator since it is constant $1$. Is $f({\bf x}; \theta) = P(X=x)?$, so in this case, since we have observed $X=1$, is $f({\bf x}; \theta) =\theta(1-\theta)$? Working as outlined above I find $C=6$. Let me know if this outline has an flaws.
What seems harder to me is the following: what is the posterior probability that the next time this person goes through the process the $\#$ of observed successes will be $2$? How does one translate this last question into probability? That is, are we looking for $f(\theta; X=2)$? I don't think so. So what exactly do we want to calculate here?
Any comments or suggestions are, as always, deeply appreciated.
Answer: The posterior distribution is indeed the Beta(2,2) distribution when $X=1$. Which is associated with $C=1/6$, rather than $C=6$. Regarding your second question, you are looking at a future value for which the Bayesian answer is the posterior predictive, that is the distribution of $X'$ conditional on $X$, which writes as
$$\mathbb{P}(X'=x|X=1) = \int_0^1 \mathbb{P}_\theta(X'=x) f(\theta|X=1)\text{d}\theta$$
So, for instance,$$\mathbb{P}(X'=2|X=1) = \int_0^1 \theta^2 f(\theta|X=1)\text{d}\theta=\int_0^1 \theta^2 6\theta(1-\theta)\text{d}\theta=\frac{6}{20}$$


How to return Service Worker with custom HTTP header from custom module

Question: I have a custom module providing a HTML5 Service Worker file under /modules/custom/my_blocks/assets/js/service-worker.js. Since the Service Worker is not located in the root of the Drupal server, I need to return the file with an additional Service-Worker-Allowed HTTP header.
How to do that within my module?
Comment: This isn't a Drupal issue. The file is a static file, it is not processed through Drupal, so HTTP headers need to be added through the server.
Comment: But I could provide the static file dynamically via Drupal, right? Hence it should also interceptable.
Comment: Ahh I get it, Remi provided the answer for how to serve it through Drupal. That said, I would look at how to do this with `.htaccess` or whatever, so that Drupal doesn't have to be bootstrapped to serve the file.
Comment: `.htaccess` wouldn't work. I need to create the service worker an/or related cache files dynamically, as they need to be updated as the contents of my Drupal site change.
Answer: To provide a dynamic file, you need to make a Controller with a method like:
 public function serve(Request $request) {
    $file_str = $file_system->realpath($module_handler->getModule('my_module')->getPath()) . '/assets/js/service-worker.js';

    if (file_exists($file_str)) {

      $response = new BinaryFileResponse($file_str, 200);
      $response->headers->set('Content-Type', 'application/javascript');
      // Allow same origin service worker.
      $response->headers->set('Service-Worker-Allowed', '/');

      return $response;
    }

    throw new NotFoundHttpException();
  }

And then define a route for it, where the path is not existing as a static file, like:
example.serviceworker:
  path: '/serviceworker'
  defaults:
    _controller: '\Drupal\my_module\Controller\ExampleController::serve'
  requirements:
    _permission: 'access content'

see - https://www.drupal.org/docs/drupal-apis/routing-system/introductory-drupal-8-routes-and-controllers-example.
Comment: Fixed some small issue: Drupal doesn't intercept the "serviceworker.js" route, so I had to remove the extension. The "/serviceworker" route on the other hand works as expected.
Comment: np ;) and thank you for the code fixes ;)
Could you then also mark the answer as accepted pls ?
Comment: Excellent clear and clean solution. That's what i was looking for. Lotta thx!


focusedSceneValue fixed by searchable

Question: I'm getting this odd issue where focusedSceneValue doesn't work on macOS Monterey Beta 6, but adding searchable to one of the views fixes it.
Here's how to reproduce:
First paste this code into ContentView:
struct ContentView: View {
    @State var search = ""

    var body: some View {
        NavigationView {
            Text("First")
                .focusedSceneValue(\.customAction) {
                    print("Pressed!")
                }
            Text("Second")
                .searchable(text: $search) // Comment this line and focusedSceneValue breaks
        }
    }
}

struct ActionKey: FocusedValueKey {
    typealias Value = () -> Void
}
extension FocusedValues {
    var customAction: (() -> Void)? {
        get { self[ActionKey.self] }
        set { self[ActionKey.self] = newValue }
    }
}

And then paste this into your app file:
struct CustomCommands: Commands {
    @FocusedValue(\.customAction) var action

    var body: some Commands {
        CommandGroup(before: .newItem) {
            Button(action: {
                action?()
            }) {
                Text("Press me")
            }
            .disabled(action == nil)
        }
    }
}

And add this into the body of your Scene:
.commands {
    CustomCommands()
}

This just adds a menu item to File, and the menu item is enabled only if a variable named action is not nil.
action is supposed to be assigned in the focusedSceneValue line in ContentView. This should always happen, as long as the ContentView is visible.
This code only works if I add the searchable modifier to one of the views however. If I don't add it, then the menu item is permanently disabled.
Is anybody else able to reproduce this?
Answer: There seems to be a bug with implementing focusedSceneValue (SwiftUI and focusedSceneValue on macOS, what am I doing wrong?).
From what you have shared, it seems that the .searchable modifier provides a focus for a view in the scene so that the focusedSceneValue is updated when the focus changes.
In the focusedSceneValue documentation, it recommends using this method "for values that must be visible regardless of where focus is located in the active scene." Implicitly, it could be that focusedSceneValue only works when an active scene has focus somewhere within.
Answer: This appears to be fixed in Monterey 12.1 (21C52), so the .searchable workaround should no longer be needed.

focusedSceneValue fixed by searchable


How do I alter a way node is rendered so I can add custom links/buttons?

Question: Sometimes I want to add custom links/buttons specific to a content type to a node when the page for that node is rendered, how would you achieve this when you write a module? An example code to achieve this by adding hello world link somewhere in the page when a node is rendered would be appreciated as the lack of documentation I can find for this is discouraging.
Answer: The easiest way to do this would be to use Content Templates!
Using this module you can have some fine-grained control over how templates and individual fields are displayed without actually creating a new .tpl.php file for that node (which is another pretty good much more laborious solution)


validating dynamic text box content in PHP

Question: I have this and works fine. But can someone tell me is there a SMARTER way to validate this?
In the validation here, you may find that the echo "<form....... is replicated thrice to make sure that the form content is also visible along side the validation message when the form is submitted. Im sure there is a more refined method of validating text box content without form being replicated multiple times.
Also appreciate if some one can suggest me a method to retain the text box value after the form is being submitted. Usually when the form is submitted the value you enter disappears.
Thanks
<?php
include ("../connection/index.php");
?>
<form method='post' action=''>
<input type="submit" name="sendone" id="sendone" value="OneClick">
</form>
<?php

if(isset($_POST['sendone']))
{
echo "Hello";
echo "<form method='post' action=''><input type='text' name='txt1' id='txt1'><input type='submit' name='sendtwo' id='sendtwo' value='TwoClick'></form>";

}
if(isset($_POST['sendtwo']))
{if($_POST['txt1']=='')
{
echo "Hello";
echo "<form method='post' action=''><input type='text' name='txt1' id='txt1'><input type='submit' name='sendtwo' id='sendtwo' value='TwoClick'></form>";
echo "Empty";}
else
{
echo "Hello";
echo "<form method='post' action=''><input type='text' name='txt1' id='txt1'><input type='submit' name='sendtwo' id='sendtwo' value='TwoClick'></form>";
echo "Hit success!";
}}

?>

EDIT
Concept
  <hard coded submit1 button>
     <dynamically create a text box with a submit2 button>
         <when submit2 is activated is should validate the text box content>

When the validation happens both the vaidated message and the text box should be visible
Comment: At the top, you could make sure of the following: **1**: All (or at least one of) of your *expected* $_POST variables exist, and **2**: No *unexpected* one's exist. Do that at the top of your script, then you won't need multiple `isset()` calls further down.
Comment: You could create a session and set each submission values as session values ie. $_SESSION['somevalue']=$_POST['somevalue'];  and if it is set, you can echo it out as value  or something like that
Comment: Always good to validate on client side with script and then validate php for security purposes.
Answer: did you mean something like this?
<?php
if(isset($_POST['sendtwo']))
{
    echo "Hello";
}
?>
    <form method='post' action=''>
        <?php
        if (!isset($_POST['sendone'])) {
            ?>
            <input type="submit" name="sendone" id="sendone" value="OneClick">
        <?
        } else {
            ?>
            <input type="hidden" name="sendone" id="sendone" value="OneClick">
            <input type='text' name='txt1' id='txt1'<?=isset($_POST['txt1']) && trim($_POST['txt1']) !== '' ? ' value="'.trim($_POST['txt1']).'"' : ''?>>
            <input type='submit' name='sendtwo' id='sendtwo' value='TwoClick'>
        <?
        }
        ?>
    </form>
<?php
if (isset($_POST['sendtwo'])) {
    if (trim($_POST['txt1']) == '') {
        echo 'Empty';
    } else {
        echo 'Hit success!';
    }
}

Comment: pls have a look at the edit.. certain part of the build is hard coded and the balance which needs to be validated in dynamically populated


On the MLE of p in Bernoulli and Binomial distributions

Question: Suppose we have a random variable $X = [x_1, x_2, ..., x_m]$, that is distributed $Binomial(n,p)$, with known $n$ and unknown $p$.
Now, assume we want to estimate $p$. Usually, textbooks and articles online give that the MLE of $p$ is $\frac{\sum_{i=1}^{m}x_i}{n}$. However, isn't it correct only when $m=1$, or in other words, when we end up having merely a $Bernoulli$ distribution?
If so, wouldn't it be more precise to say that the MLE of $p$ is actually $\frac{\sum_{i=1}^{m}x_i}{mn}$?
Answer: You are right, while even the credible sources sometimes claim differently,
the correct formula is
$$ \hat p = \frac{1}{mn} \sum_{i=1}^m x_i = \overbrace{\frac{1}{m} \sum_{i=1}^m}^\text{we have m trials} \overbrace{\frac{x_i}{n}}^{\substack{\text{proportion of successes} \\ \text{in single Bernoulli trial}}} $$
since if you calculated ordinary arithmetic mean of $X$, you'd get average number of successes in $n$ trials, i.e. $E(X) = n \hat p$.
Comment: That's exactly how I thought, however I saw so many books and sources giving the $Bernoulli$ formula when talking about $Binomial$ that I got to the point of questioning myself. Thanks!


update a VIRTUAL GENERATED column

Question: UPDATE reservation SET NB_RESTE=1 WHERE IDRESERVATION='28'

i want to update the NB_RESTE value but it wont work , even when i try to update another column it works properly Knowing that NB_RESTE is VIRTUAL GENERATED
error message :

#3105 - The value specified for generated column 'NB_RESTE' in table 'reservation' is not allowed.
Comment: Why do you want to updated a generated column directly? Update the field(s) it is generated from.
Comment: If you want to update the generated column to a value that no longer complies with its definition (e.g. you calculate the total amount from price and quantity and now you want to apply a 10+ item discount) then a generated column is not the right tool—not at least without some changes.
Answer: As mysql manual on update statement says:

If a generated column is updated explicitly, the only permitted value is DEFAULT.

Which is completely logical, since the value of the field is generated by an expression. In case of a virtual volumn, there is not even a value stored in the table. If you want to change the value of a generated column, then update the field(s) it is generated from.
Answer: Virtual generated columns cannot be altered to stored generated columns, or vice versa. To work around this, drop the column, then add it with the new definition.
CREATE TABLE t1 (c1 INT, c2 INT GENERATED ALWAYS AS (c1 + 1) VIRTUAL);
ALTER TABLE t1 DROP COLUMN c2;
ALTER TABLE t1 ADD COLUMN c2 INT GENERATED ALWAYS AS (c1 + 1) STORED;

Source: https://docs.oracle.com/cd/E17952_01/mysql-8.0-en/alter-table-generated-columns.html

update a VIRTUAL GENERATED column


Get data out of Parse.com and display on android

Question: Please could you give me some ideas and maybe parts of code, I am trying to get data out of a Parse.com table and display it on my android phone in either a TextView or a TableView.
I can manage to get one value out however, there are three in the table that should be shown.
I just can't seem to work out where I am going wrong! Any help would be greatly appreciated...
 private void forLoadingView(String c_id) throws ParseException
             {
            ParseQuery<ParseObject> query = ParseQuery.getQuery("Review");
            query.whereEqualTo("c_id", c_id);
        query.orderByDescending("rating");
                query.findInBackground(new FindCallback<ParseObject>() {
                    public void done(List<ParseObject> reviewList, ParseException e) {
                    if (e==null && reviewList!= null)
                    {

                        for(ParseObject object : reviewList) {
     String score = object.getString("rating");
                        String review = object.getString("review");
                        String name = object.getString("name");
reviews.setText(review + " " + name + " " + score);

                }
                }
                else
                {
                    Log.d("score", "Error: " + e.getMessage());
                }

                }
            });

EDIT:
Now my code looks a little more like this:
final List<String> infoList = new ArrayList<String>();
List<String> result = new ArrayList<String>();
    ParseQuery<ParseObject> query =
            new ParseQuery<ParseObject>("Review");
   query.whereEqualTo("c_id", c_id);
        query.orderByDescending("rating");
    query.findInBackground(new FindCallback<ParseObject>() {

        @Override
        public void done(List<ParseObject> objects, ParseException e) {
            if (e == null) {
            //fill your list or adapter by using objects
            for(ParseObject obj : objects) {
                infoList.add(object.getString("score"));
                    infoList.add(object.getString("review"));
                    infoList.add(object.getString("name"));
               }
            }
        }
    });

reviews.setText(infoList.toString());

But it still does not print out... instead there is a null pointer exception as (I guess) the information isn't being sent to the infoList. Have you got any ideas?
Thank you!
Comment: What does this mean?  query.whereEqualTo("c_id", c_id);   Aren't you querying for a specific id here? Do all three objects share the same c_id ?
Comment: Yes, all objects share the same C_id
Answer: Try this , it worked for me, let me know if worked for you as well:
    List<String> result = new ArrayList<String>();
    ParseQuery<ParseObject> query =
            new ParseQuery<ParseObject>(yourQuery);
    query.whereEqualTo(querykey, queryvalue);
    query.addAscendingOrder(orderKey);
    query.findInBackground(new FindCallback<ParseObject>() {

        @Override
        public void done(List<ParseObject> objects, ParseException e) {
            if (e == null) {
            //fill your list or adapter by using objects
            for(ParseObject obj : objects) {
               result.add(obj.getString(someKey));
               }
            }
        }
    });

Comment: Thank you for your help! So I changed my code to yours and then
  `if (e == null) {
                for(ParseObject object : messages) {
               //fill your adapter by using messages
                String score = object.getString("rating");
                      String review = object.getString("review");
                      String name = object.getString("name");
                reviews.setText(review + " " + name + " " + score); etc`
This still only printed one thing but when I sysout'd the review it showed all values in terminal, do you know to get this to show on screen?
Comment: If I mistake not ,You are happy with the result of your query but have problems with extracting data from the ParseObject?
Comment: yes, I am happy with the query. Inside the variable review are the three items that it is meant to hold. However, when I ask it to set the textView it only displays the last item. Do you know how to get it to display all three?
Comment: I recommend you to get a log from the returned object (or the string you created from) to make sure that is different from the output result of the textview, then make sure that your textview initialized properly.
Comment: So the log does show the correct results. The only problem with the TextView is that in order for it to access the variables rating, review and name it needs to be in the query box. How else would I initialise it?
Comment: I meant this by initialization : TextView tv = (TextView)findViewById(id);
Comment: where do you use setText() method ? if you're using in the done method like your code block above, it will only show the last ParseObject data, did you consider this !?
Comment: I had a feeling that might be the case... where should I do it instead? how to do you then access the variables in the done statement?
Comment: That's simple , just create a string array or a list of strings in your activity scope, then assign the returned values by done() method to the array using a loop.got it !?
Comment: that seems to make sense! I just don't know how to do it? Would you be able to help me code it? Thank you so much for all your help
Comment: I edited my answer in order to save results to an array for the case you want just access the result, If you need to show the result in a ListView you can use an [ArrayAdapter](http://developer.android.com/reference/android/widget/ArrayAdapter.html)
Comment: So I have followed what you have said and then called  `reviews.setText(result.toString());` but this has called a null pointer exception as nothing is being written to reviews... do you know why this might be the case?
Answer: Replace ParseQuery<ParseObject> query = ParseQuery.getQuery("Review"); with ParseQuery query = new ParseQuery("Review");
According to Parse Documentation (refer here), ParseQuery.getQuery(class_name) method retrieves all objects in the class.

public static  ParseQuery getQuery(String
  className) Creates a new query for the given class name. A default
  query with no further parameters will retrieve all ParseObjects of the
  provided class name. Parameters: className - The name of the class to
  retrieve ParseObjects for. Returns: A new ParseQuery.

Whereas ParseQuery object can be queried if one instantiates it by calling ParseQuery() constructor.
Comment: sadly that does not do anything. The query is getting the correct values, they are just not showing correctly in the TextView
Comment: Make sure that TextView reviews is global to forLoadingView method

and

try setting text like this
reviews.setText(object.getString("review") + " " +object.getString("name") + " " +  object.getString("rating"));
Answer: Use this code
StringBuilder str_infoList = new StringBuilder();
    for (String s : infoList)
    {
        str_infoList.append(s);
        str_infoList.append(" ");
    }

reviews.setText(str_infoList);


menu css3 style in css and IE

Question: I have a question ,  i need something like this
<code>background: -webkit-gradient(linear, left bottom, left top, from(#1e3c84), to(#2a5bd0)) #1CA6D6;
    border-radius: 3px;
    border-bottom: 3px solid #021748;
    -moz-border-radius: 3px;
    -webkit-border-radius: 3px;
    -o-border-radius: 3px;
    -khtml-border-radius: 3px;
    -ms-border-radius: 3px;
margin-right: 5px;
</code>
But in CSS2 ? to show in IE correctly and other browsers
How i can do that? what is the  properties or  i can do with image? how? or something similar
very thanks!!
Answer: All modern browsers support rounded corners and gradient. The older versions of ie can support these features using scripts like css3pie.
Comment: thanks sotiris , but doesn't work look http://goo.gl/Qa5zh , I add the   behavior: url(PIE.htc);
Comment: @FelipeIgnacioVictorianoVict keep in mind that the path to pie.htc must be relative to the HTML file being viewed, not the CSS file it is called from.
Comment: thanks @sotiris, I use behavior: url(/wp-content/themes/sw/images/PIE.php); but doesn't  work too :( , Can i can do wrong?
Comment: @FelipeIgnacioVictorianoVict I don't know much of wordpress. Read http://www.position-relative.com/2011/01/using-css3-pie-in-wordpress-custom-themes/ may help you
Answer: Border radius doesn't work in older browsers... you will have to draw the corners yourself, slice them and then build the div or button yourself :)
http://caniuse.com/#search=border-radius
http://www.search-this.com/2007/02/12/css-liquid-round-corners/
Update
Or use @Sotiris link :)

menu css3 style in css and IE


Cannot update subitems ListBox

Question: I have two ListBoxes.  One ListBox displays some items.  Each item has a list of subitems.  The second ListBox displays the subitems of the current item in the first ListBox.  A typical item/subitem scenario.  When I add a value to the subitem list, I cannot get the second ListBox to update.  How can I force the second ListBox to update my subitems?
My simplified XAML and view model are below.  Note that my view model inherits from Prism's BindableBase.  In my view model I have a method to add a value to the subitems list and update the Items property with RaisePropertyChanged.
<ListBox Name="Items" ItemsSource="{Binding Items}" >
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <VirtualizingStackPanel />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>

    <ListBox.ItemTemplate>
        <DataTemplate>

        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

<ListBox Name="SubItems" ItemsSource="{Binding Items.CurrentItem.SubItems}" >
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <VirtualizingStackPanel />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>

    <ListBox.ItemTemplate>
        <DataTemplate>

        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

class Item
{
    public int ItemValue { get; set; }
    public List<int> SubItems { get; set; }
}

class MyViewModel : BindableBase
{
    private ObservableCollection<Item> _items = new ObservableCollection<Item>();

    public MyViewModel()
    {
        List<Item> myItems = new List<Item>() {  /* a bunch of items */ };

        _items = new ObservableCollection<Item>(myItems);
        Items = new ListCollectionView(_items);
    }

    public ICollectionView Items { get; private set; }

    private void AddNewSubItem(object obj)
    {
        Item currentItem = Items.CurrentItem as Item;

        currentItem.SubItems.Add(123);

        RaisePropertyChanged("Items");
    }
}

Comment: ``
Comment: This did not work.  Values are added to SubItems just fine, just not updating ListBox.  I tried Items.InvalidateVisual and Items.UpdateLayout - did not work either.
Comment: Is Item.SubItems an ObservableCollection?
Answer: class Item
{
    public int ItemValue { get; set; }
    public ObservableCollection<int> SubItems { get;}
      = new ObservableCollection<int>();
}

class MyViewModel : BindableBase
{
    publc ObservableCollection<Item> Items {get;}
        = new ObservableCollection<Item>();

    public MyViewModel()
    {
        List<Item> myItems = new List<Item>() {  /* a bunch of items */ };

        myItems.ForEach(item => Items.Add(item));
    }

    private Item _currentItem;
    private Item CurrentItem
    {
       get => _currentItem;
       set
       {
          if(Equals(_currentItem, value))
            return;

          _currentItem = value;
          RaisePropertyChanged(nameof(CurrentItem));
       }
    }

    private void AddNewSubItem(object obj)
    {
        CurrentItem.SubItems.Add(123);
    }
}

<ListBox ItemsSource="{Binding Items}"
         SelectedItem="{Binding CurrentItem}">
  ********
  ********
</ListBox>

<ListBox ItemsSource="{Binding CurrentItem.SubItems}" >
  ********
  ********
</ListBox>

Answer: The issue is that your Item type contains a List<int>, which does not notify on collection changes, because it does not implement the INotifyCollectionChanged interface. Consequently, bindings do not get notified to update their values in the user interface when the collection is modified. Using a collection that implements this interface, e.g. an ObservableCollection<int> will solve the issue.
By the way, the same applies to ItemValue and SubItems properties as well with INotifyPropertyChanged. Both properties have setters, which means they can be reassigned, but the bindings will not get notified then either. Since you use BindableBase, you can use the SetProperty method with backing fields to automatically raise the PropertyChanged event when a property is set.
public class Item : BindableBase
{
   private int _itemValue;
   private ObservableCollection<int> _subItems;

   public int ItemValue
   {
      get => _itemValue;
      set => SetProperty(ref _itemValue, value);
   }

   public ObservableCollection<int> SubItems
   {
      get => _subItems;
      set => SetProperty(ref _subItems, value);
   }
}

A remark about your project. What you try to do is a master-detail view for hierarchical data. Since you already expose an ICollectionView, you do not have to use the CurrentItem explicitly.

When the source is a collection view, the current item can be specified with a slash (/). For example, the clause Path=/ sets the binding to the current item in the view. When the source is a collection, this syntax specifies the current item of the default collection view.

There is a special binding syntax, where you can use a / to indicate the current item, e.g.:
<ListBox Grid.Row="1" Name="SubItems" ItemsSource="{Binding Items/SubItems}">

Additionally a few remarks about your view model code.

The _items field initializer is useless, as you reassign the field in the constructor anyway.
If you only use the collection view and not _items, you can use a local variable in the constructor.
The private setter of Items is not used, you can remove it.
Cast the Items.CurrentItem directly to Item to get an invalid cast exception that is more specific that the null reference exception that you would get later when accessing the value from using as and getting null. If you expect that the value could be something else than an Item, you could check for null after as or use pattern matching to handle both cases, success and error (CurrentItem is not of type Item) appropriately.
Comment: Many thanks!  A very complete answer.  I also greatly appreciate the comments regarding other parts of the code.

Cannot update subitems ListBox


SyncFusion DataManager not recognizing changes to entity instance within Blazor WASM App

Question: I have an app that has an entity entitled, "Invoice". Within the Invoice entity, I have a reference to a collection for another entity entitled, "InvoiceLine".
I am using SyncFusion's DataGrid along with DataManager to perform CRUD operations. When I click on an invoice in the datagrid, it displays a component containing the relevant information. The invoice contains an invoice line component. When I make a change to an invoice line, the UI reflects the changes. I have also verified that the invoice line within the invoice line collection within the invoice reflects the changes.
The issues is when I click save, the changes are not carried through to the controller on the server-side.
<code>// relevant line within the invoice entity class
// Navigation property
        public List<InvoiceLine>? InvoiceLines
        {
            get => GetPropertyValue<List<InvoiceLine>?>();
            set => SetPropertyValue(value);
        }
</code>
<code>// invoice data manager class
namespace AccountsReceivable.Client.DataAdaptor
{
    public class InvoicesDataManager : SfDataManager
    {
        private IServerApiService _serverApiService = default!;

        [Inject]
        private IServerApiService ServerApiService
        {
            get => _serverApiService;
            set
            {
                if (_serverApiService != value)
                {
                    _serverApiService = value;
                    OnServerApiServiceChanged();
                }
            }
        }

        public InvoicesDataManager()
        {
            Adaptor = Syncfusion.Blazor.Adaptors.ODataV4Adaptor;
            this.EnableCaching = true;
        }
        // Set data manager url values
        private void OnServerApiServiceChanged()
        {
            // main url
            const string apiUrl = "api/Invoices";
            // Instantiate http instance
            HttpClientInstance = ServerApiService.HttpClientInstance;
            // Set base url
            Url = ServerApiService.GetApiUrl(apiUrl);
            // Set saving url
            UpdateUrl = ServerApiService.GetApiUrl($"{apiUrl}/save");
            // Set deletion url
            RemoveUrl = ServerApiService.GetApiUrl($"{apiUrl}/delete");
        }

        protected override void OnInitialized()
        {
            OnServerApiServiceChanged();
            base.OnInitialized();
        }
    }
}
</code>
<code>// Controller code...the values argument contains the changes that have been made.
// PATCH: api/invoices/save
        [HttpPatch("save({invoiceId})")]
        [AuthorizeScope(AuthorizationScope.UpdateInvoice)]
        public async Task<ActionResult> Patch([FromRoute] int invoiceId, [FromBody] IDictionary<string, JsonDocument>? values, CancellationToken ct)
        {
            try
            {
                Invoice? invoice = await _invoiceDataProvider.GetItemAsync(invoiceId);
                if (invoice != null)
                {
                    values?.Patch(invoice);

                    await _invoiceDataProvider.SaveAsync(invoice);
                }

                return Ok(ApiResponse.OkResponse(invoice));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Invoice Error");
                return BadRequest(new ApiResponse(ApiStatusCodes.UnhandledError, ex.Message));
            }
        }
</code>
Answer: You are facing difficulties due to the updated values sent to server as Patch request. By default ODataV4 accepts Patch method to update the records in database. PATCH request is similar to PUT method where only difference is that in PATCH request the only the modified properties [(i.e.) only updated properties] will be sent to API server. All other default properties will ignored in PATCH request.  So, I suspect that you are facing issue while updating your Navigation property.
Consider the below example of Order class.
<code>
public class Order

   {

       [Key]

       public int? OrderID { get; set; }

       public string CustomerID { get; set; }

       public DateTime? OrderDate { get; set; }

       public double? Freight { get; set; }

   }

</code>
List is bound to Grid using ODataV4 adaptor and DataManager, in that CustomerID column alone edited in the first record. While saving the changes PUT request will be sent to the API server with the entire object consisting { OrderID, CustomerID, OrderData, Freight } all these properties.
But in PATCH request, only the modified property (CustomerID) alone will be considered and sent to the API server for PATCH operation. This is the difference between PUT and PATCH requests.
Please refer to the below online reference between PUT and PATCH requests.
Use of PUT vs PATCH methods in REST API real life scenarios
https://rapidapi.com/blog/put-vs-patch/
Comment: Thank you for your post. I am aware of the differences between PUT and PATCH. My issue is that I make changes to a navigational property and those are not being recognized and sent to the server-side controller. I am not sure why my changes to a navigational property are not being "caught"?


xml parsing failed using python: xml.etree.cElementTree

Question: I download a xml file using
wget -O example.xml http://gdata.youtube.com/feeds/api/videos?q=samsung+mobile&orderby=relevance&start-index=1&max-results=5&v=2

I want to get video id, for example, "x_HFR3Hmv44" from  x_HFR3Hmv44
and published time from 2010-10-25T20:42:22.000Z
however, I failed using the following codes
import xml.etree.cElementTree as et

sxml = open('example.xml', 'r').read()
tree=et.fromstring(sxml)
for el in tree.findall('published'):
    print el.getchildren()[1].text

but I failed,
the output is nothing
can anyone tell me where I'm wrong? thanks!
is it because the xml file can't be processed by xml.etree.cElementTree?
there are tags like , while the yt is not defined in the file
Comment: Failed how? Did you get an error or traceback (please include if so)? What output are you expecting from this code?
Comment: Is this even really your actual code?  It has a typo "exmaple.xml" (incidentally I have an amusing mental image of a trans-species former tree)
Comment: This can't be your code. Your code should output *nothing* since `el.getchildren()` is empty.
Comment: I made a mistake, it is nothing, in my original code, I have an additional print tree
Comment: anyway, how to achieve my goal? how to modify the code? thanks!
Comment: Given that you didn't quote the URL, that can't be your real `wget` line either. If you want us to figure out what's wrong with your code, show us your code—or, better, a stripped down version that can be run and demonstrates exactly the same thing—not something vaguely similar.
Answer: It's hard to say exactly, but I think you have two problems:

Element.findall() only finds elements that are direct children of that element, per the docs.
You need to specify the namespace that this tag belongs to.  For example:
list(tree.iter('{http://www.w3.org/2005/Atom}published'))
Comment: thanks very much. how to find the namespace? I notice there are namespaces like http://www.w3.org/2005/Atom}published, or   http://search.yahoo.com/mrss/, but I can't find them in the xml file
Answer: You are just confused about the XML structure. Add prettyprint=true to your query string to get indented xml which will be easier for you to read. Also consult YouTube's element reference links to understand what to expect.
This will get you started:
from urllib import urlopen
import xml.etree.cElementTree as ET

url = 'http://gdata.youtube.com/feeds/api/videos?q=samsung+mobile&orderby=relevance&start-index=1&max-results=5&v=2'

root = ET.parse(urlopen(url))

def qname(prefix, name, map={'atom':'http://www.w3.org/2005/Atom'}):
    """Helper function for namespaced element names"""
    return '{{{}}}{}'.format(map[prefix], name)

for e in root.findall(qname('atom','entry')):
    print e.findtext(qname('atom','id')), e.findtext(qname('atom','published'))


How to allow FTP on Google Compute Engine Windows VM?

Question: All of the Google Cloud Platform instructions seem to be about setting up FTP in other OS like debian, etc.  Connection just times out.
On the Windows 2012 Server, I have setup FTP in IIS properly, but the firewall will not let me connect from the outside with FileZilla.
These Google Cloud Network firewall rules are already in place.
Name    Source tag / IP range   Allowed protocols / ports   Target tags
allow-ftp    0.0.0.0/0   tcp:21  ftp-server
allow-passive-ftp    0.0.0.0/0   tcp:5000-6000   Apply to all targets
allow-passive2-ftp   0.0.0.0/0   udp:5000-6000   Apply to all targets
I also made an inbound rule for ftp on port 21 in Windows Firewall.
Still cannot connect.  What am I missing?
Thanks
Comment: How exactly is FTP failing?  Could you provide logs from your FTP client showing the commands/responses, and the error message?
Comment: If anyone is experiencing this issue, I'd like to say that this issue was discussed in [this thread](https://groups.google.com/forum/#!topic/gce-discussion/dnNQwdfMBUw) and resolved.
Answer: I was facing exact same issue. Here's how I resolved this:
Inside the Windows VM, go to Control Panel > Windows Firewall > Inbound Rules
Create New Rule to allow TCP port 21 connections.
There is already a default rule to allow FTP Traffic In on Port 21 but it has some attached restrictions related to NAT.
After adding a manual rule as above, FTP access from FileZilla starting working instantly.
Answer: Using a Windows instance in GCP you should allow the FTP traffic in your internal firewall ( the firewall from the instance ) and the firewall of you GCP project.
Also it could be caused by the passive mode. View this article : Failed to retrieve directory listing filezilla connecting to IIS FTP behind NAT »  Grant Curell
Answer: In my case, other answers do not work, but when I change the range of the firewall rules everything starts to works fine. I have created only tcp rule:
allow-passive-ftp 0.0.0.0/0 tcp:49152-65535 Apply to all targets.
My FTP site has the following firewall options:
IIS FTP Firewall Support configuration


Combinatorics permutation with letters and numbers

Question: Suppose a valid name is of length 3 or more up until 100 (including 100)
A valid name also has to satisfy:

It has at least one lower-case letter (a-z)
At least one upper-case letter (A-Z)
At least one digit (0-9)

But, there is a rule. The rule is that names with the exact same letters and digits are considered the same. So for example, the name "AaZ41" is the same as "a1Z4A" and "1aB" is the same as "1111BBBaaaa"
So in short, the order does not matter, and so is the number of repeated character ("1qZ" = "q1ZZ" but not equal to "1zqZ" as lower-cased z isn't there)

How many different names are there?

My approach:
The reasonable thing to notice is that because we can have names that are more than 62 characters long ( because uppercase + lowercase + digits = 26+26+10 = 62)
Then by the pigeonhole principal, after we pass the 62'nd character we will use something that has already been used and thus not changing the actual name.
So we need each iteration take $i$ upper-cased letters, $j$ lower-cased letter and $k$ digits such that:
$$ i + j + k = 62$$
And thus I think it is:
$$ \sum_{i+j+k=3}^{i+j+k =62} \overbrace{\binom{26}{i}}^{\text{upper}} \overbrace{\cdot \binom{26}{j} }^{ \text{lower}}\cdot \overbrace{\binom{10}{k}}^{\text{digits}}$$
But how do I evaluate this (Answer should be a number, not a sum..)? and I am not sure if that is even close to the way of solving it..
I would appreciate your kind help! Thanks!
Comment: You can include (or not) each of `a-zA-Z0-9` in $2^{62}$ ways. Now you should exclude cases when no lower letters ($2^{36}$ ways), no digits ($2^{52}$ ways) and so on
Comment: @AlexeyBurdin so is it  $2^{62} - 2^{36} - 2^{36} - 2^{52}$ ?
Comment: @AlexeyBurdin if I remove all the passwords that does not contain: upper / lower / digit  and add (upper $\cap$ lower + upper $\cap$ digit + lower $\cap$ digit$ ) minus ( digit $\cap$ upper $\cap$ lower)  so then is the cardinality of digit $\cap$ lower $\cap$ upper ? is it 1 or 0 (I mean, what is the cardinality of the intersection of the groups of passwords which does not contain a digit / uppercase / lowercase) it should be the emptyset no?
Comment: So the cardinality is $1$ -- when we take nothing, and yes, you use the [PIE](https://en.wikipedia.org/wiki/Inclusion%E2%80%93exclusion_principle), but I'm not quite sure how to use it correctly, if I was, it was an answer, not a comment. )
Comment: And your sum, [computed in python](https://tio.run/##RY7LDsIgEEX3fAVLBqgRGq0LWfUzjIuqrU4rj1C68OuxGKObczI3mZkbXunhXX0IMWe0wcdEMfUxef@cyTewXXqQ1hRtrt5eSOdmMy@WtUzvJQL/eCxWWzkBHXykKEc5UXT/c5sQ/W25JsbZKXbu3jMldQNnrsVvVgrOABQHWh8NilFMR7PXQEJEl9j6V17QFYMsJUzFhKo052pbqBuxcqcL66Yk6y7k/AY) is $-1+2^{10}+2^{27}-2^{52}-2^{37}+2^{62}$.
Comment: @AlexeyBurdin well, as you checked in with python you did use the PIE - let $A$ be the set of names without an upper - $B$ without lower $C$ without a digit. so $|A| + |B| + |C| - |A \cap B| - |A \cap C| - |B \cap C| + |A \cap B \cap C|$.   we get: $|A \cap B| = 2^{10}$ is the set of names with digits, $|A \cap C| = 2^{26}$ is only with lower - etc.. we get $2^{62} - 2^{37} - 2^{52} + 2^{27} +  2^{10} - 1$ - the only thing I don't get is why it is $-1$ when the intersection of the three should yield a positive number.
Comment: This $1$ corresponds to the case when you take no lower letters, no upper letters and no digits into the password -- you can do it exactly $1$ ways -- it's the empty password.
Answer: Your sum is not that scary. First, it's not $\displaystyle\sum\limits_{i+j+k=3}^{i+j+k=62}$, but $\displaystyle{\sum\limits_{i=1}^{26}\sum\limits_{j=1}^{26}\sum\limits_{k=1}^{10}}$ and can be rearranged as
$$
\begin{align*}
\sum\limits_{i=1}^{26}\sum\limits_{j=1}^{26}\sum\limits_{k=1}^{10} {26\choose i}{26\choose j}{10\choose k}&=
\left(\sum\limits_{i=1}^{26}{26\choose i}\right)\cdot
\left(\sum\limits_{j=1}^{26}{26\choose j}\right)\cdot
\left(\sum\limits_{k=1}^{10}{10\choose k}\right)\\
&=\left(2^{26}-1\right)\cdot
\left(2^{26}-1\right)\cdot
\left(2^{10}-1\right),
\end{align*}$$
and actually you get the same result using the Inclusion-exclusion principle.


Asymptotic Behavior of an Entire Function

Question: Let $b\in\mathbb{N}\geq2$
 , $a\in\left\{ 1,2,...,b-1\right\}$
 , and let:
$$f\left(x\right)=\frac{e^{2\pi ix}-1}{\pi ix\alpha}\frac{1}{\alpha-1}+\frac{e^{2\pi ix}-1}{\pi ix\alpha}\sum_{n=0}^{\infty}\frac{x^{2}\alpha^{n}}{x^{2}-n^{2}}$$
where $\alpha=e^{2\pi i\frac{a}{b}}$.
As defined, it can be shown that $f\left(z\right)$ is an entire function; moreover, $f\left(z\right)$ has no zeroes on the real line. My concern at present is the limiting behavior of this function on the real line. Empirical evidence strongly suggests that:
$$\lim_{x\rightarrow+\infty}\frac{f\left(x\right)}{\alpha^{x-1}}=1$$
and that:
$$\lim_{x\rightarrow+\infty}\left|f\left(x\right)-\alpha^{x-1}\right|=0$$
This has been bugging me in my research, so, I was wondering if anyone had an idea as to how one might go about justifying either or both of these assertions rigorously.
Thanks in advance!
Comment: If it only it was so simple as plugging in x = ∞. The $\frac{e^{2\pi ix}-1}{\pi ix\alpha^{x}}$ term dies a very slow death to 0 as x —> ∞; on the other hand, the summand tends to the non-convergent series $\sum_{n=0}^{\infty}\alpha^{n}$ as x —> ∞. I don't believe it is possible (or legal) to evaluate the x limit on the series term by term.
Comment: Have you tried just plugging $\infty $ in for x?  It shouldn't be that hard to algebraically find out if these limits you propose are correct or not.  The first limit you propose seems to be valid, in my opinion.  Also, is f not also a function of a and b?  You might want to amend this to be $f(x,a,b) = ... $
Comment: Why do you think it is true, and where does your function come from ?
Comment: This function comes from a (hopefully) novel method I have developed for tackling the issue of fractional differentiation. As for why I think it is true:

1) The heuristics I've been using strongly suggest that it is true (it makes intuitive sense;

2) The graphs of the quotients and differences of the two functions converge with extreme rapidity to the desired value.

3) The fourier transforms of the functions are markedly similar
Comment: @MCS sry what I really  meant is that it is not true, because of the poles at $x = \pm n$, but maybe you meant $\lim_{n \to \infty} f(n+1/2)$ or something like that
Comment: There ARE NO POLES. The x = +/- n poles are cancelled out by the zeroes of $1-e^{2\pi ix}$ at those points.
Answer: Note : I didn't solve the question, if someone does I'll delete this

in the same way that $\pi \cot(\pi z) = \frac{1}{z}+2z\sum_{n=1}^\infty \frac{1}{z^2-n^2}= \lim_{N \to \infty} \sum_{n=-N}^N \frac{1}{z-n}$
(show that $\pi \cot(\pi z)-(\lim_{N \to \infty} \sum_{n=-N}^N \frac{1}{z-n})$ is a bounded entire function, and using Liouville's theorem)
you have for $0 \le a/b \le 1$ :
 $$\frac{e^{2i \pi a z / b}}{e^{2i \pi z}-1} = C+\lim_{n \to \infty}\sum_{n=-N}^N \frac{e^{2i \pi a n / b}}{z-n}$$
for some $C$.
And your function $f(z),z \in \mathbb{C}$ isn't entire, but meromorphic.
Comment: And I didn't solve the question, since what I wrote works for $\sum_{n \ge 1 }\frac{\cos(2 \pi a n/b)}{z^2-n^2}$ but not for $\sum_{n \ge 1 }\frac{e^{2 i\pi a n/b}}{z^2-n^2}$ as the OP wants. This last series needs the gamma function, something like $e^{2i \pi az/b} \frac{\Gamma'(z)}{\Gamma(z)}$
Comment: Yes, I've already found representations for the function in terms of the logarithmic derivative of the gamma function (the so-called "digamma" function, $\psi$):  $f\left(x\right)=\frac{1-e^{2\pi ix}}{2\pi ib\alpha}\sum_{n=1}^{b-1}\alpha^{n}\psi\left(\frac{x+n}{b}\right)$ Are there any useful asymptotics for $\psi$ that could resolve the issue?
Comment: Oh! I just found an asymptotic: $\psi\left(x+1\right)\sim\ln x+\frac{1}{2x}+\mathcal{O}\left(x^{-2}\right)$. Let's see if this might resolve the issue...
Comment: @MCS as $x \to + \infty$ (or $Re(z)\to + \infty$), not as $x \to - \infty$ where $\psi(x)$ has many poles
Comment: Whoops. Typed up the wrong formula for f in terms of psi. It's close enough though—what with the symmetry and all.

And yes, it's the limit as x goes to positive infinity.


Prevent TagBuilder.MergeAttribute from encoding attribute text

Question: I've created a Html helper that encodes email addresses in order to prevent SPAM. This is the same technique used by the MarkdownSharp library when auto-generating email links.
The problem is that TagBuilder.MergeAttribute encodes the attribute text which breaks the link. Is it possible to override this behaviour or at least specify the attribute another way. I know I can fall back to just using string concatenation or a StringBuilder but TabBuilder does offer a number of benefits such as easily merging other HTML attributes.
    ///
    /// Creates an encoded email link in the hopes of foiling most SPAM bots
    ///
    public static IHtmlString EmailLink(this HtmlHelper html, string email, string text = null, object htmlAttributes = null)
    {
        Ensure.Argument.NotNullOrEmpty(email, "email");

        var encodedEmail = EncodeEmailAddress(email);

        var tb = new TagBuilder("a");
        tb.MergeAttribute("href", "mailto:" + encodedEmail);

        tb.InnerHtml = text ?? encodedEmail;

        if (htmlAttributes != null)
        {
            tb.MergeAttributes(new RouteValueDictionary(htmlAttributes));
        }

        return new HtmlString(tb.ToString());
    }

    ///
    /// encodes email address randomly
    /// roughly 10% raw, 45% hex, 45% dec
    /// note that @ is always encoded and : never is
    ///
    private static string EncodeEmailAddress(string addr)
    {
        var sb = new StringBuilder(addr.Length * 5);
        var rand = new Random();
        int r;
        foreach (char c in addr)
        {
            r = rand.Next(1, 100);
            if ((r > 90 || c == ':') && c != '@')
                sb.Append(c);                         // m
            else if (r < 45)
                sb.AppendFormat("&#x{0:x};", (int)c); // &#x6D
            else
                sb.AppendFormat("&#{0};", (int)c);    // &#109
        }
        return sb.ToString();
    }

Answer: I do not believe your helper will do anything meaningful to help reduce spam.  When crawlers use HTML parsers, they're seeing the decoded strings, not the encoded ones.  It is the same logic as in the browser itself.  So all they need to do is strip the mailto: prefix, and they now have the original email address.
If you still wish to pursue this, you must use string concatenation.  TagBuilder isn't designed to work with input that is already encoded.  Make sure that you encode the &, ', and " characters if you go this route.
Comment: When I view the source of the link in my browser I get the encoded string *not* the decoded one so I'm assuming this would be the same if the crawler was not using a parser?


At what frequencies do you usually high/low pass male vocal doubles?

Question: I'm speaking in general but if it depends on the vocal how can I find out by ear?
Comment: I generally don't. I generally mulitband comp entire sections if we're talking large block BVs. Why do you think you'd need to?
Comment: I did one of my usual long, waffling opinionated answers on some tips & tricks for doubling & blocking vocals. Doesn't answer your question but you might find it interesting - https://music.stackexchange.com/a/109701/12556
Comment: Haha - it was an answer to one of your own questions ;)))
Answer: For all high pass and low pass filters for any instrument or voice:
Start with the filter turned on but at the end of its range (as low as possible for high pass, as high as possible for low pass). Listen to the track either soloed or with the music, depending on why you are filtering it. Slowly raise (lower) the filter until it makes the track sound bad and overly filtered. Then lower (raise) it slightly until it just stops sounding bad or wrong. Done.
How do you know when it sounds bad/wrong/too much? Vision and experience. It's a combination of having a vision or plan for how you want the track to sound and the experience to know what that plan sounds like in each element of it.
If you feel like you don't have enough of a plan or enough experience, then just give it your best shot and you can always go back and change it later as you mix. Doing it even when you aren't sure exactly what you're doing is how you get the experience.
Comment: I do agree, & by 'error' I just mean there are more ways to get this wrong than right.. It's just that a feel this is too far beyond 'mixing 101' & more of a 5th year experience gainer ;) I remember my first 10 years of mixing I spent more time taking cassettes out to the car to try figure where i went wrong than anything else ;)
Comment: @Tetsujin I wonder if you and I would agree on what "error" means in this case. If it sounds good, it is good. My take on where the asker is in their journey of mixing is they still have yet to learn how to learn how to mix. So my answer isn't about how to mix, it's about how to learn how to mix.
Comment: I'm conflicted by this answer. There isn't any part of it I disagree with, but I have the uncomfortable feeling that in its execution there is greater chance of error than in not doing it at all...


How to solve this PHP fatal error after installing module?

Question:
PHP Fatal error:  Cannot redeclare _field_info_field_cache()
  (previously declared in
  C:\xxxx\wwwroot\xxxxx\modules\field\field.info.inc:16) in
  C:\xxxxx\wwwroot\xxxxxxx\sites\all\modules\easy_booking-7.x-2.4\modules\field\field.info.inc
  on line 32

So I got this error notification after turning on Error debug in my IIS Server because previously it only showed a 500 page error.
It seems it's calling two times the same function? Anyone can help?
Edit: I guess it's better I just delete the module but then I get a require_once error:

PHP Fatal error:  require_once(): Failed opening required '
Comment: The module is using a function that is part of core, which causes that bug. You may be able to use the module if you remove that function from the module, but I'd suspect you'll run into other problems if you do that. The best thing to do is open a ticket in the issue queue for that module, which can be found on the module download page.
Comment: Don't "simply" delete a module. Disable and uninstall it first. Otherwise Drupal will miss it.
Comment: @leymannx Sorry didnt see your post.  I couldnt disable it first because I couldnt access my admin page due to the require once fatal error.
Comment: What module did you install then? Custom? Contrib?
Comment: @leymannx It was "easy booking".
Answer: Put the module back. Check its code. Delete the problematic function named in the corresponding error message from it. Go to admin page. Uninstall the module.
Try to reinstall the module in a proper location. Don't name the folder easy_booking-7.x-2.4. Simply name it easy_booking. If the error still occurs, file a bug at https://www.drupal.org/project/issues/easy_booking?status=All&categories=All
Comment: Thanks. So I delete the whole function? The first problematic function in the error message is sites\all\modules\views\includes\plugins.inc:15)
Comment: No! From `easy_booking` module!
Comment: Your solution works. Although I can see my admin panel now, the module panel has disappeared which doesn't allow me to clean uninstall that problematic module.
Comment: @Vasmir - Any chance you can do it with Drush or Drupal Console? Finally you can try to edit the module's status database entry.
Comment: Drush, unfortunately -not on this machine. Where do I access the Drupal Console and what command line should I use?
Comment: Console is d8 only
Comment: Update: Admin Menu finally showed up BUT clicking on modules for ex. gives me new fatal PHP error: C:\xxxx\xxxxx\xxxxxxx/sites/all/modules/easy_booking-7.x-2.4/modules/system/system.admin.inc' (include_path='.;C:\php\pear') in C:\xxxxx\xxxxxxx\includes\menu.inc on line 525
Answer: Okay, I found the solution.

I run update.php as in typing www.yourwebsite.com/update.php in
the browser
I upgraded my php version on my IIS Server from PHP 5.3 to PHP 5.5 (For Windows users, install PHP upgrade manager for IIS and follow instructions)

While doing this it still gave me a fatal PHP error about my elfinder module but I deleted a function in the given line code and after runing update.php, my admin page worked again.


How to start resque daemons with rails server?

Question: I wonder if there is a way to start my resque daemons when the rails server starts in my production environment. I tried creating an initializer file but it didn't work.
Every single time my rails server starts, I want to run this two commands:
<code>bundle exec rake resque:work BACKGROUND=yes RAILS_ENV=production PIDFILE=/shared/pids/resque_work.pid

bundle exec rake resque:scheduler BACKGROUND=yes RAILS_ENV=production PIDFILE=/shared/pids/resque_scheduler.pid
</code>
I really appreciate your help.
Answer: Check out Foreman.  You can describe what processes you need to run, and it will take care of it.
http://blog.daviddollar.org/2011/05/06/introducing-foreman.html