Lilypond: define macros / templates to avoid code repetition

Question: Please excuse the vague question title. I don't know how what I need is called in Lilypond - the two words (macros/templates) are what I'd call it in programming context.
I have a Lilypond document like this:
title = "title1"
music = { \relative { c c c c } \addlyrics { this is some text } }
% song on one page
\bookpart { \header { title = \title } \score { \music \layout { } } }
% midi file creation
\book { \bookOutputName \title \score { \unfoldRepeats \music \midi { } } }

title = "title2"
music = { \relative { d d d d } \addlyrics { here o -- ther text } }
% song on one page
\bookpart { \header { title = \title } \score { \music \layout { } } }
% midi file creation
\book { \bookOutputName \title \score { \unfoldRepeats \music \midi { } } }

title = "title3"
music = { \relative { e e e e } \addlyrics { what -- e -- ver text } }
% song on one page
\bookpart { \header { title = \title } \score { \music \layout { } } }
% midi file creation
\book { \bookOutputName \title \score { \unfoldRepeats \music \midi { } } }

There's a lot of code repetition: For each title and musicAndLyrics I have the same code. I want to put that code into a macro/template and reuse that for each pair of title and musicAndLyrics. Like this:
% define macro. NOTE THAT I DO NOT KNOW THE SYNTAX. THIS IS PSEUDOCODE!
macro(foo, bar) =
{
    % song on one page
    \bookpart { \header { title = \foo } \score { \bar \layout { } } }
    % midi file creation
    \book { \bookOutputName \foo \score { \unfoldRepeats \bar \midi { } } }
}

title = "title1"
music = { \relative { c c c c } \addlyrics { this is some text } }
% call macro with above variables as content
macro(title, music)

title = "title2"
music = { \relative { d d d d } \addlyrics { here o -- ther text } }
% call macro with above variables as content
macro(title, music)

title = "title3"
music = { \relative { e e e e } \addlyrics { what -- e -- ver text } }
% call macro with above variables as content
macro(title, music)

Is there a way to achieve this? If yes, how? How is that concept called in Lilypond? I searched Lilypond snippets that contained "template", "macro", "variable" and "function" in their content or comments, but could find no example where something like \bookpart, \header etc. were used in the way I intend.

Bonus question:
Can we write a macro based on arrays in order to remove the last bit of code repetition? Like this:
% define macro. NOTE THAT I DO NOT KNOW THE SYNTAX.
%    THIS IS (C#/JAVA-based) PSEUDOCODE!
% assumption: the two arrays have the same length.
macro(foo[], bar[]) =
{
  for (int i = 0; i < foo.length; i++)
  {
    % song on one page
    \bookpart { \header { title = \foo[i] } \score { \bar[i] \layout { } } }
    % midi file creation
    \book { \bookOutputName \foo[i] \score { \unfoldRepeats \bar[i] \midi { } } }
  }
}

title[1] = "title1"
music[1] = { \relative { c c c c } \addlyrics { this is some text } }

title[2] = "title2"
music[2] = { \relative { d d d d } \addlyrics { here o -- ther text } }

title[3] = "title3"
music[3] = { \relative { e e e e } \addlyrics { what -- e -- ver text } }

% call macro with above variables as content
macro(title, music)

Side question: Would you put that question somewhere else, like StackOverflow or Tex Stackexchange? Where do you think the chance for a good answer is highest?
Answer: Lilypond allows you to create Scheme functions that can process and output Lilypond variables.
Lilypond variables
You can define Lilypond variables to insert a block of code somewhere else. They don't really make this clear in the documentation, but each variable must have one of several allowed types. They can't just be arbitrary text like a macro.
So you can do like this:
title = \markup "Title"
music = { c'4 d'4 c'4 }
lyrics = \lyricmode { Ex -- am -- ple }

\book {
   \header { title = \title }
   \score { { \music } \addlyrics { \lyrics } }
}

Scheme expressions and functions
In pure Scheme, you define expressions that return the body.
(define title "Title")
$> (title) => "Title"

You can define expressions that take arguments and insert them into the body.
(define hello
   (lambda (name)
      (string-append "hello, " name)))
$> (hello "world") => "hello, world"

Scheme functions in Lilypond
Lilypond provides you with the awkward solution of using a highly modified version of Scheme within Lilypond and mixing the two languages' syntax.
In Lilypond's version of Scheme, all Scheme expressions are preceded by #. Instead of simple define you "get" to use define-scheme-function. Instead of (define fn (lambda (arg1 arg2) body)) now you write this:
fn = #(define-scheme-function
        (arg1 arg2)
        (type-of-arg1? type-of-arg2?)
        body)

Most of the time for the body you will want to write Lilypond code, not its even crazier Scheme translation, so you can put it in a code block #{ ... #}. Then when you want to insert the arguments, you put a dollar sign in front of them ($arg1).
So here is a way to do more or less what you are asking. Note that you have to be specific about what kind of variables you are giving the function.
\version "2.23"

% Function 'makebook': Make a \book.
%   INPUT:  title (Lilypond \markup expression),
%           music (Lilypond music expression inside curly braces {})
%           words (Lilypond \lyricmode expression)
%   RETURNS: A \book expression with the given contents.
makebook =
#(define-scheme-function
   (title music words)
   (markup? ly:music? ly:music?)
      #{
\book {
    \header { title = $title }
    \score {
        \new Staff
          <<
            \new Voice { $music }
            \new Lyrics { $words }
          >>
        }
    }
#})

% Lilypond-centered approach
title = \markup "title1"
music = { c'4 c'4 c'4 c'4 }
words = \lyricmode { this is some text }

% Call the Scheme function with the Lilypond variables defined above
#(makebook title music words)

Is there a better way?
I learned Scheme so that I could use Lilypond at a more advanced level. I fell in love with Scheme and with functional programming in general. But using Scheme in Lilypond is extremely unpleasant. You aren't really using normal Scheme, you're using their own dialect of it. Scheme itself uses dynamic typing so you can be flexible about arguments. Compared to that, or even more, LaTeX, where you can put just about anything into a macro and do just about anything with it, in Lilypond-Scheme you have do be very fussy about variable types and only certain expressions are allowed. You end up with a messy mishmash. The alternative is a lot of boilerplate Lilypond code, and it's hard to reduce that even using Scheme.
Another approach is to use Scheme itself, or really any other language, to generate your Lilypond code. All you want to do is duplicate blocks of text in the input file. In fact you could use the m4 macro processor to do it:
File lytemplate.m4:
define(makebook,
\version "2.23"
\book {
    \header { title = $1 }
    \score {
        \new Staff
          <<
            \new Voice { $2 }
            \new Lyrics { $3 }
          >>
        }
    }
)
define(mytitle, \markup "title1")
define(mymusic, { c'4 c'4 c'4 c'4 })
define(mywords, \lyricmode { this is some text })
makebook(mytitle, mymusic, mywords)

Then you can run m4 lytemplate.m4 > lytemplate.ly && lilypond lytemplate.
Response to bonus question about iterating through a list of data
This is a good example of something it seems like you should be able to do with "Scheme-in-Lilypond". I found it easy to do in Scheme but I could not get it to work within Lilypond.
As a Scheme program, this just generates the strings for the Lilypond code. There are various ways you can make a list of your data (here I use an association list) and them map a string-making function over that list. You can run this with the Guile interpreter. (But you might as well use any other language you already know if you're going to go this route.)
(define make-book
  (lambda (title music words)
  "Return a string with the Lilypond code for a book, given title, music, and lyrics"
    (string-append
      "\\book { \\header { title = \\markup \"" title "\" }\n"
      "\\score { \\new Staff << \\new Voice { " music " }\n"
      "\\new Lyrics { \\lyricmode { " words " } >> } }\n")))

(define get-song
    (lambda (alist)
    "Call make-book with the song data from an association list"
    (let ((title (assq-ref alist 'title))
          (music (assq-ref alist 'music))
          (words (assq-ref alist 'words)))
      (make-book title music words))))

(define make-songs
  (lambda (ls)
  "Return a string with the Lilypond code for a given list of songs"
    (let ((song-strings (map get-song ls)))
      (string-concatenate song-strings))))

(define songs
  '(((title . "title1")
     (music . "c'4 c'4")
     (words . "word one"))
    ((title . "title2")
     (music . "d'4 d'4")
     (words . "word two"))
    ((title . "title3")
     (music . "e'4 e'4")
     (words . "word three"))))

(format #t (make-songs songs))

Comment: I just tried your example macro in section `Scheme functions in Lilypond`. I added `\layout { }` below the `\new Staff ...` command in order to get a pdf. It compiles, but creates no pdf. I changed `#(makebook title music words)` to `$(makebook title music words)`, but then I got error `Unbound variable: words`. How do I make a pdf from this example?
Comment: Thanks for this excellent explanation. Much better than the Lilypond Scheme Manual that others linked to, that I have read and explored without finding an answer. I wish I had found your explanation earlier! (In the manual, calling the arguments is done with a #, which doesn't work. Switching to a $ made it.) Thanks again.
Comment: Since you have a lot of experience with scheme and scheme in Lilypond, do you have an answer to my comment under Aaron's answer?
Comment: That example already makes a PDF, no changes needed. You have to have the # before any Scheme expression.
Comment: I think the real problem is errors in your Lilypond code. A book part is supposed to be inside a book. https://lilypond.org/doc/v2.22/Documentation/notation/file-structure
Answer: This is not quite the programming-heavy answer you might be looking for, but a workaround that is very easy in LilyPond is to use \include. (See the Learning manual at 3.4.5 Scores and parts and 4.7.3 Style sheets.) You can create a template file that uses your score information, and then reuse that as many times as you need. Just \include it after the code that it is calling:
% File called score.ily

 \bookpart {
   \header {
     title = \title
   }
   \score {
     \music
   }
   \layout {}
 }

% File called compile-this.ly

title = "title1"
music = \relative c' { do re mi }
\include "./score.ily"

title = "title2"
music = \relative c { fa sol la }
\include "./score.ily"

Answer: LilyPond can be extended using Scheme. So you can create a scheme function of appropriate variables to output the sort of code you want.
The LilyPond Scheme Manual is the place to begin.
Comment: Gather them in a list, and replace # with the list splicing operator #@ . Some examples here: https://extending-lilypond.readthedocs.io/en/latest/intro.html#inserting-scheme-inside-lilypond
Comment: I was able to create a function in scheme that returns the `bookpart` (song on one page) and another function that returns the `book` (midi file creation). But I was not able to return both in one function. Is that even possible? A function by definition returns ONE value, but `\bookpart { ... } \book { ... }` are two things.
Comment: @Kjara I'm working on it myself, but haven't got it yet.


Chrome Extension - Remembering user input JavaScript

Question: I'm trying to make a Chrome Extension that allows a user to input a sequence of nucleotides and convert that sequence into the corresponding amino acid sequence. Ideally I could click on the extension icon in the browser, then a text box would pop up that I could paste the sequence into. After hitting "Translate" the amino acid sequence would appear below the input text box. I'm hoping to add more functionality to this later but this is the basis for the extension.
I'm still new to HTML and I'm very new to CSS and JavaScript, and I've also never created a Chrome Extension before so I'm having a little trouble turning my ideas into working code.
Here's the HTML I have so far:

<!doctype html>

<form action="/popup.js">

        Nucleotide Sequence:

        <textarea id="nucleotide_seq" name="nucleotide_seq" rows="6" cols="35"></textarea>

    <input type="submit" value="Translate">
</form>

The biggest question I have right now is how to make it so that when you hit "Translate", the user input is sent to the JavaScript file and saved as a variable that the code would then iterate over, and convert to a string of amino acids, which it would print out as a string underneath the original input text box.
Any help is appreciated!
Comment: I wish I had an easier answer. Read up on [messaging here](https://developer.chrome.com/extensions/messaging) and study [examples here](https://chromium.googlesource.com/chromium/src/+/master/chrome/common/extensions/docs/examples). Also see [this question](http://stackoverflow.com/questions/13546778/how-to-communicate-between-popup-js-and-background-js-in-chrome-extension) Good luck!
Answer: Please check this
https://jsfiddle.net/fNPvf/39583/
function translateInput(){
var nucle=document.getElementById("nucleotide_seq").value;
//translate nucle
document.getElementById("nucleotide_seq").value = "amino acid";
}

You can use local storage also,if you want. Please check below link
https://jsfiddle.net/fNPvf/39584/
function translateInput(){
localStorage.nucle = document.getElementById("nucleotide_seq").value;
//translate nucle
document.getElementById("nucleotide_seq").value ="converted "+localStorage.nucle;
}

Updated fiddle. Please check this
https://jsfiddle.net/fNPvf/39630/
function translateInput(){
localStorage.nucle = document.getElementById("nucleotide_seq").value;
//translate nucle
document.getElementById("nucleotide_seq").value =localStorage.nucle;
document.getElementById("amino_acid_seq").value ="converted "+localStorage.nucle;
}

Comment: Thank you so much! This seems very close to what I'm looking for.

Do you know how I could get the returned amino acid sequence to appear below the textbox instead of within it? Ideally the nucleotide sequence would stay within the textbox so the user could see both their original input sequence and the output sequence at the same time.
Comment: Happy to here that was useful to you. I have edited the fiddle to show translated data to another text box.
Answer: I know this is an old post, but there is a much better way of doing this than the current answer using the chrome storage. Here's a link. Usage is fairly easy, you just have to add the permission storage in the manifest.json file.
Should the link expire, here's an example (note, this will not work in a browser. It wil only work in a chrome extension):

// Saves options to chrome.storage
function save_options() {
  var color = document.getElementById('color').value;
  var likesColor = document.getElementById('like').checked;
  chrome.storage.sync.set({
    favoriteColor: color,
    likesColor: likesColor
  }, function() {
    // Update status to let user know options were saved.
    var status = document.getElementById('status');
    status.textContent = 'Options saved.';
    setTimeout(function() {
      status.textContent = '';
    }, 750);
  });
}

// Restores select box and checkbox state using the preferences
// stored in chrome.storage.
function restore_options() {
  // Use default value color = 'red' and likesColor = true.
  chrome.storage.sync.get({
    favoriteColor: 'red',
    likesColor: true
  }, function(items) {
    document.getElementById('color').value = items.favoriteColor;
    document.getElementById('like').checked = items.likesColor;
  });
}
document.addEventListener('DOMContentLoaded', restore_options);
document.getElementById('save').addEventListener('click',
  save_options);

<!DOCTYPE html>

  <title>My Test Extension Options</title>

  Favorite color:
  <select id="color">
    <option value="red">red</option>
    <option value="green">green</option>
    <option value="blue">blue</option>
    <option value="yellow">yellow</option>
  </select>

  <input type="checkbox" id="like">
  I like colors.

  <button id="save">Save</button>

Comment: Maybe you could have included an example of the code if it is that simple? Links can die, code included in the answer is visible forever.
Comment: @Steve added. This should now be the accepted answer imo.


Commutativity of the fundamental groups.

Question: Let $X$ be a topological space and $x_0 \in X.$ Given $[g], [h] \in \pi_1 (X, x_0)$ define a map $H : I \times I \longrightarrow X$ by
$$H (t,s) = \begin{cases} h \left (\frac {3t} {1 - s} \right ) & \text {if}\ 0 \leq t \leq \frac {1 - s} {3} \\ g \left ( \frac {3t + s -1} {1 + 2 s} \right ) & \text {if}\ \frac {1 - s} {3} \leq t \leq \frac {2 + s} {3} \\ \overline h \left (\frac {3t - s - 2} {1 - s} \right ) & \text {if}\ \frac {2 + s} {3} \leq t \leq 1 \end{cases}$$
Doesn't it mean that $h \ast g \ast \overline h$ is based homotopic to $g$ in $X\ $? But if it's the case then this is true for any two loops $g$ and $h$ in $X$ based at $x_0.$ But this in turn implies that $\pi_1 (X, x_0)$ is abelian, which is not necessarily true. Where did I go wrong?
Any help would be highly appreciated. Thanks for your time.
EDIT $:$ The homotopy diagram I mentioned is the following $:$

Remark $:$ Another point is that although $h \ast g \ast \overline h$ is not homotopic to $g$ as based loops in $X$ they are indeed homotopic as non-based loops in $X.$ The following gives one such homotopy. Consider $K : I \times I \longrightarrow X$ defined by
$$K (t,s) = \begin{cases}  \overline h (s -3t) & \text {if}\ 0 \leq t \leq \frac {s} {3} \\ g \left ( \frac {3t - s} {3 - 2 s} \right ) & \text {if}\ \frac {s} {3} \leq t \leq \frac {3 - s} {3} \\ \overline h (3t + s - 3) & \text {if}\ \frac {3 - s} {3} \leq t \leq 1 \end{cases}$$
Comment: The map $H$ is not defined at points where $s = 1$. I'm guessing you want to say that $H(t, 1) = g(t)$, but then you have no guarantee that $H$ is continuous.
Comment: [This](https://math.stackexchange.com/questions/269467/fundamental-group-is-abelian-iff-the-fundamental-group-isomorphisms-a-hat-coin) seems related.
Comment: yeah I think that is the problem @MichaelAlbanese. The map $H$ goes through $h$ and $\overline{h}$ faster and faster and would move through them "infinitely fast" for $s=1$, which then would be "equal" to $g$.
Comment: @MichaelAlbanese$:$ Good remark! That's the reason they fail to be homotopic. I drew a homotopy diagram and this is what I get when rephrasing the diagram in terms of equations. So why does the homotopy diagram fail here? Any idea? I am asking this because many people prefers to describe homotopy by diagrams instead of writing down explicit formulas for the homotopy. But in my case the homotopy diagram does give a wrong intuition about the homotopy. That's why I want to know why the intuition fails to work here.
Comment: I'm not sure what you mean by a homotopy diagram. Do you mean something like [this](https://math.stackexchange.com/q/2629096/39599)? Maybe you could add the diagram to the question so that someone can answer the questions you ask in your comment.
Comment: @MichaelAlbanese$:$ Added the diagram as mentioned.
Comment: @MichaelAlbanese$:$ Added one more remark in the edit.
Comment: It turns out that the basepoints of the intermediate loops in the non-based homotopy (I defined) traces out the loop $\overline h.$
Comment: $K$ is not well-defined. Take $t = \frac s 3$ in the first and second line of the definition. And what is your question?
Comment: @PaulFrost$:$ There is a typo and there is an obvious fix to it. Edited it accordingly. The question is clearly mentioned.
Comment: If your question is "Where did I go wrong", then it was answered in a comment by Michael Albanese: $H$ is undefined for $s=1$. Or does it concern $K$?
Comment: @PaulFrost$:$ If you glossed over the above comments then you can get to see that I was confused about the existence of homotopy diagram without the existence of non-based homotopy. Michael Albanese suggested me to upload the diagram and I have uploaded it which clearly indicates how the homotopy should be done. But now I realized at $s = 1$ the parametric interval of $h$ and $\overline h$ just becomes a point. So $h$ and $\overline h$ cannot be defined at $s = 1$ unless $h$ is a constant loop (and consequently so is $\overline h$). For any other $0 \leq s \lt 1$ we are fine because... contd
Comment: ...in that case the parametric intervals of $h$ and $\overline h$ are both non-degenerate closed and bounded intervals and any such interval is homeomorphic to $[0,1].$ For degenerate case we no longer have that homeomorphism. So the definition of $h$ and $\overline h$ miserably fails at $s = 1.$
Comment: Then I suggest you answer your own question and accept it. Just to remove it from the unanswered queue.
Comment: @PaulFrost$:$ I am now busy with some other job. My exams are knocking at the door and I am preparing for the same. Is it possible to remove it?
Comment: You can delete the question. Or I can write a community wiki containing what you wrote as an explanation. Would  perhaps help other users who have the same question.
Comment: @PaulFrost$:$ Yes then please do it that way without deleting this question. I will surely accept the answer.
Comment: Done. Note that community wikis can be accepted and upvoted, but do not confer any  reputation for authors. See https://math.stackexchange.com/help/privileges/community-wiki. Questions can be deleted only by their authors and by the moderators. See https://math.stackexchange.com/help/deleted-questions. Other users can vote for deletion or closure.
Comment: @PaulFrost$:$ Thanks a lot for your efforts. Accepted and upvoted the answer.
Answer: The question was answered in the comments. This community wiki summarizes the relevant insights.
Formally the homotopy $H$ is not well-defined because it involves a division by $0$ for $s=1$. It is impossible to repair the definition of $H$ as we shall explain now.
The "homotopy diagram" explains what the homotopy from $h *g * \overline h$ to $h$ should do.
The problem is that at $s=1$ the parametric interval of $h$ and $\overline h$ just becomes a point. So $h$ and $\overline h$ do not fit into this degenerate interval at $s=1$ unless $h$ is a constant loop (and consequently so is $\overline h$). For any other $0≤s<1$ we are fine because in that case the parametric intervals of $h$ and $\overline h$ are both non-degenerate closed and bounded intervals and any such interval is homeomorphic to $[0,1]$. For the degenerate case we no longer have that homeomorphism. So the insertion of $h$ and $\overline h$ into the shrinked intervals miserably fails at $s=1$.


Exchange 2016 and Sever 2016 DCs: Unknown KDC Encryption type

Question: Team,
Exchange environment is all 2016, no mix. Parent and child domains exist, but the functional level of each domain and forest is 2012R2. All domain controllers have been 2012R2 until recently. The AD team (different from me) have introduced Server 2016 domain controllers and I think it has caused a problem. Here are the symptoms:
Mail gets stuck on servers in a parent domain with the destination to the child domain. Error on the queue is "454 4.7.0 Temporary Authentication error" and the correlating events in the event log are Event ID 2017, Source: MSExchangeTransport, the message is:
"Outbound authentication failed with error KdcUnknownEncryptionType for Send connector Intra-Organization SMTP Send Connector. The authentication mechanism is ExchangeAuth. The target is SMTPSVC/server fqdn."
Mail will flow from child domain to parent domain with no problem. Like I said earlier, I think the most significant change that has happened is simply introducting Server 2016 DCs. To fix it temporarily, I can reboot the server that the messages are stuck on and it will work for a while. This really seems like a Kerberos issue.
EDIT: We also have an ASA set up, but the supported encryption types between all my exchange servers, DCs, and this ASA are all "28".
Google searches suggest time sync issues, but I've checked both the Exchange servers and the domain controllers and things seem to be exactly on sync. I've also checked replication health and there doesn't appear to be any issues with that. I've also checked for duplicate or malformed SPNs and didn't find anything. Is there more that I can look into about the SPNs though? Like what kind of encryption they are requesting/using or something? I don't know much about Kerberos.
EDIT: As another note, using a GPO, I did remove the RC4-HMAC from the destination server. As a result, the klist tickets command did show the correct "AES...", but then my powershell was broken... "Possible causes" were:

"Username or password invalid"
"Kerberos used when no authentication method and no user name are specified"
"Kerberos accepts domain usernames, but not local user names."
"SPN for remote computer name and port doesn't exist"
"client and remote computers are in different domains and there is no trust."

Then it suggests to try adding destination computer in the WinRM TrustedHosts list.
Answer: I think you may first check the SPN, you could run "SetSPN -L <ExchangeServerName>" command to check the SPN configuration. It should contain:
SMTP/<ExchangeServerName>

SMTP/<ExchangeServerName>.example.com

SMTPSVC/<ExchangeServerName>

SMTPSVC/<ExchangeServerName>.example.com

If some missed, you could run "setspn -a <data>" to add.
And then, on the client side, run "klist tickets" in CMD to check the ticket type. Usually it should be "AES-256-CTS-xxx".
Here is a related blog about ticket types:
https://blogs.msdn.microsoft.com/openspecification/2011/05/30/windows-configurations-for-kerberos-supported-encryption-type/
In addition, according my research, beginning with Windows Server 2016, KDCs can support the PKInit freshness extension. Maybe you could also check this point.
Comment: Well, the `klist tickets` command is showing me something new. I have run the other setspn commands suggested and nothing is amiss there. The first ticket (which is the krbtgt) on the source server (parent domain) is the "AES..." you mentioned, but on the destination server (child domain), it is "RSADSI RC4-HMAC". My guess is that this has something to do with it?
Comment: Also, to the link you provided, The GPO settings for this are the same on both domains and it shows up the same on both servers when I look in SECPOL.msc
Comment: Don't just look in secpol, use gpresult.exe to output the resultant set of policy for the computer. You should have your AD team verify this on the 2016 DCs also.
Comment: Gpresult shows the same configurations as well.
Answer: It sounds like RC4 was an allowed Kerberos encryption type on the 2012 DCs, and your AD team introduced 2016 DCs with RC4 disabled. I say this with some confidence, because it is the recommended security setting on Server 2016. The goal is to remove RC4 from the environment, but not without first updating your mission critical applications to support AES. My suggestion would be to ensure the allowed Kerberos encryption types are configured the same on all DCs and then enable Kerberos service ticket success auditing on all Domain Controllers to see which applications are still trying to use RC4. It will show up in EventId 4769 with an encryption type of 0x17. If you see this, then RC4 is being used. You need to make sure all involved user accounts, computer accounts, and the Kerberos policy on each server (including the DCs) is configured properly for AES to work.
Comment: Glad to hear you got it squared away!
Comment: There are no 4769 events on the DCs. Sorry it took me a while to respond. We still have all our 2012R2 DCs as well, so it seems like it shouldn't stop mail flow.
Comment: We do have an event ID of 16 logged multiple times, that reads something like this: "While processing TGS request for HTTP/, the account  did not have a suitable key for generating a Kerberos ticket (the missing key has an ID of 8). The requested etypes were 18 17. The accounts available etypes were 18 17 23 -133 -128 24 -135. Changing or resetting the password for  will generate a proper key." I don't see why it is requesting a key with an ID of 8. According to the link above about Kerberos types, that is "AES-128..." That's supposed to be supported.
Comment: You need to enable Kerberos service ticket success/failure auditing on your Domain Controllers to see these events. This is the event you're looking for: https://docs.microsoft.com/en-us/windows/security/threat-protection/auditing/event-4769
Comment: Enabling Kerberos auditing today, will let you know the results.
Comment: Yeah, audit of event 4769 shows my Exchange servers on the child domain requesting RC4 encryption type for the tickets. Now I just need to figure out how to get it not to do that?
Comment: Your issue isn't that they are using RC4 (that's another issue for later). The issue is your AD team introduced new Domain Controllers into the environment that are rejecting RC4 without first verifying if any applications would be affected. There's probably more than just Exchange. They should leave RC4 enabled on all DCs until the applications support AES. You will need to verify the supported encryption types attribute on all Exchange computer/service accounts is set to support AES. I'm very annoyed that this isn't on by default for all accounts.
Comment: Yeah, I checked the DCs on the child domain (where mail would not flow to) and it was indeed not there. It was there on all the 2016 DCs on the parent domain, just not the child domain. You da man. Thanks.


Irreducibility of $2x^3-3x^2+6$ in $\mathbb Q[x]$

Question: The following statement is given, i need to check whether its true\false.
There exists a subfield $F$ of $\mathbb{C}$ such that $F\not\subseteq\mathbb R$ and $$F \cong \mathbb Q[X]/(2X^3 − 3X^2 + 6).$$
My attempt:
I thought since its cubic polynomial it will have a real solution, how do I show its not in $\mathbb Q$, and then the fact that $F\not\subseteq\mathbb R$?
Ans - Eisenstein and Rational root test, settle the first part. How to show that $F\not\subseteq\mathbb R$.
I know for a fact that this is a true statement.
Comment: sorry for the inconvenienvce
Answer: Hint 1. A rational root $p/q$  of $f(x):=2x^3-3x^2+6$ with $\gcd(p,q)=1$ is such that $p$ divides $6$ and $q$ divides $2$ (See the Rational Root Theorem).
Hint 2. Note that $f'(x)=6x(x-1)$,  $x=0$ is a local maximum and $x=1$ is a local minimum with $f(1)=5>0$. Show that from this it follows that the roots are not all real.
Comment: @rhombicosicodecahedron Note that $(2x^3-3x^2+6)'=6x(x-1)=0$,  $x=0$ is a local maximum and $x=1$ is a local minimum.
Comment: how do I show the second part?
Answer: Hint: Rational root theorem. $\hphantom{imaginary space}$
Comment: @rhombicosicodecahedron, do you mean $F\not\subseteq\mathbb R$? Well, $F$ is the smallest subfield of $\mathbb C$ that contains $\mathbb Q$ and the roots of your polynomial. So, if all roots were real, it would follow that $F\subseteq\mathbb R$. Thus, you need to show that...?
Comment: how do i show the second part?
Comment: ahh right, thank you very much.
Answer: This follows from Eisensteins's criterion, with $p=3$.
Comment: Oh right. I got $2x^3$ and that had roots in Z3, so ignored it. stupid on my part. Thanks. How do I show the second part?


Como fazer um select com base em dados de outra tabela

Question: Tenho que fazer a seguinte adaptação em uma query:
Tabela app_usuários: id, nome, sobrenome, hash, sexo, interesse, latitude e longitude.
Tabela app_likes: id, user_a_id, user_b_id
Resumidamente, tenho um query que pega os usuários com base no sexo e interesse em um raio de 25 quilômetros.
O que eu preciso fazer: Tenho que fazer a query não pegar usuários que eu já dei like acessando a tabela app_likes, sei que tenho de fazer isso com inner join, mas como? Considerem que user_a_id seria o id de quem deu like.
Minha query:
$teste  = $app->database->query("SELECT user_id, user_firstname, latitude, longitude,
(6371 * acos(
 cos( radians(".$app->session->user_data[0]['latitude'].") )
 * cos( radians( latitude ) )
 * cos( radians( longitude ) - radians(".$app->session->user_data[0]['longitude'].") )
 + sin( radians(".$app->session->user_data[0]['latitude'].") )
 * sin( radians( latitude ) )
 )
) AS distancia
FROM app_users ".$query."
HAVING distancia < 25
ORDER BY distancia ASC
LIMIT 4;", $array);

De onde vem as variáveis $query e $array:
if($app->session->user_data[0]['user_interest'] == "m" || $app->session->user_data[0]['user_interest'] == "f"){
  $query = "WHERE user_gender = :ug AND (user_interest = :uin OR user_interest = :reserved) not in (".$app->session->user_data[0]['user_id'].")";
  $array = array("ug"=>$app->session->user_data[0]['user_interest'], "uin"=>$app->session->user_data[0]['user_gender'],"reserved"=>"fm");
} else if($app->session->user_data[0]['user_interest'] == "fm"){
  $query = "WHERE user_interest = :uin OR user_interest = :reserved not in (".$app->session->user_data[0]['user_id'].")";
  $array = array("uin"=>$app->session->user_data[0]['user_gender'],"reserved"=>"fm");
}

Answer: Para não apanhar os utilizadores que já deram like teria que fazer um LEFT JOIN com a tabela app_likes:
$teste  = $app->database->query("   SELECT      user_id
                                            ,   user_firstname
                                            ,   latitude
                                            ,   longitude
                                            ,   (6371 * acos(       cos(radians(".$app->session->user_data[0]['latitude']."))
                                                                *   cos(radians(latitude))
                                                                *   cos(radians(longitude) - radians(".$app->session->user_data[0]['longitude']."))
                                                                +   sin(radians(".$app->session->user_data[0]['latitude']."))
                                                                *   sin(radians(latitude))
                                                            )
                                                ) AS distancia
                                    FROM        app_users au
                                    LEFT JOIN   app_likes al ON al.user_b_id = au.id
                                                            AND al.user_a_id = ".$app->session->user_data[0]['user_id']."
                                    WHERE       al.id IS NULL
                                            AND ".$query."
                                    HAVING      distancia < 25
                                    ORDER BY    distancia ASC
                                    LIMIT 4;", $array);

Terá que remover o WHERE da sua variável $query e colocar uns parêntesis onde utiliza o OR, caso contrário vai misturar os resultados.
Nota: não coloquei plicas na condição AND al.user_a_id = ".$app->session->user_data[0]['user_id']." porque não sei de que tipo de dados é, mas se for string ou um tipo UNIQUEIDENTIFIER deverá colocar.
Comment: Atualizei a pergunta e coloquei de onde vem as variaveis $query e $array
Comment: Resposta editada para considerar o conteúdo da variável `$query`.
Comment: Referiu que o campo `user_a_id` era o campo que deveria ligar à tabela `app_likes`, e se assim for, ligando as duas tabelas com o `LEFT JOIN` e dizendo que não queremos os registos dos utilizadores que já deram _like_ (têm um registo na tabela `app_likes`), então penso ser o que estava a pedir, certo?
Comment: Ok, está difícil. O que é que está a ser retornado na _query_ inicial?
Comment: Acho que já percebi o cenário! Editei a resposta para no `JOIN` apanhar os resultados em que o utilizador representado pelo `user_b_id` tenha _likes_ e ao mesmo tempo que esses _likes_ venham do utilizador que está logado, depois na cláusula `WHERE` dizemos que todos esses resultados devem ser removidos da consulta.
Comment: João, obrigado por ajuda. Mas não acho que você não entendeu direito. Seria assim, se user_b_id for igual ao id do registro que veio da consulta, o mesmo não seria incluído no resultado.
Comment: Vamos lá. Vou tentar explicar utilizando algorítimo. [Selecione 4 usuários em um raio de 25 quilômetros, verifique também se foi retornado algum usuário em que eu já dei like utilizando a tabela app_likes, considerando que user_a_id é o meu id e user_b_id é o id dos outros usuários, caso seja encontrado não retorne esses resultados]
Comment: Simplesmente quero que a query me retorne usuários com os requisitos definidos no WHERE e que a query exclua usuários que eu já dei like, utilizando a tabela app_like. Considerando que user_a_id é o meu id e user_b_id é o id do usuário em quem eu dei like.
Comment: A variavel $query manda as preferências do usuário para a consulta.
Comment: Se o usuário for bissexual, manda selecionar homens e mulheres que estejam interessado no gênero dele. Se o usuário for hétero, seleciona o sexo oposto que esteja interessado no gênero dele. Assim funciona a variável $query. Já a variável $array contem os dados dessas preferências.
Comment: Considere que $app->session->user_data[0] contém os dados do usuário que está logado
Comment: Cara, você é incrível! Funcionou perfeitamente.


Function $f$ on plane satisfying $f(I)=f(A)f(B)f(C)$ for any triangle $ABC$ with incenter $I$

Question:
Let $f$ be a function from the set of all points on the plane to the nonzero real numbers. Suppose that for any triangle $ABC$ with incenter $I$, we have that $f(I)=f(A)f(B)f(C)$. What are the possibilities for $f$?

Clearly, $f=1$ and $f=-1$ work. Are there other ones?
Comment: Here's the corresponding problem for tetrahedra: http://math.stackexchange.com/questions/857273/find-all-such-functions-defined-on-the-space/857309#857309
Comment: is $f$ continuous?
Comment: is $f$ locally bounded?
Answer: Let $D$ be the incenter of the triangle $ABI$
Let's draw the picture:

Thus $f(D)=f(I)f(A)f(B)=f(A)^2f(B)^2f(C)$
Now, consider pictures symmetric pictures with respect to the line $IC$.

We get points $A',B',D'$ for which we have
1) $f(A')f(B')=f(A)f(B)=f(I)/f(C)$
2) $f(D')=f(A')^2f(B')^2f(C)=f(A)^2f(B)^2f(C)=f(D)$
Thus, we have so proved that $f(D)=f(D')$
Now, given two points $X,Y$ in the plane, let $L$ be their axis of simmetry. That is to say, $L$ is the line of points equidistant from $X,Y$.
Up to scaling and rotating we can suppose that $X=D$, $Y=D'$ and $L$ is the line $CI$.
In other words, given any two $X,Y$ in the plane, we can construct a triangle $A,B,C$ so that $X,Y$ play the role of $D,D'$ above. Thus $f(X)=f(Y)$ for any $X,Y$.
This proves that $f$ is constant. Given that $f$ is constant it must bu a square root of $1$ hence $\pm1$
Comment: Note that this proof make no use of continuity nor local boundedness of $f$.


How to customize entity print pdf

Question: I've installed Entity Print in order to create PDF files. I've read the documentation to enable a twig template to customize the pdf output, but I don't know how to do simple things, in the twig file, like add a page header and footer, add a front page, etc. Are there any docs about how to customize it?
Answer: It depends on which print engine you're using. I am using the following entity-print.html.twig with the dompdf engine.

    <meta charset="utf-8">
    <title>{{ title }}</title>
    {{ entity_print_css }}

{# The footer is repeated on all pages and must be printed first. #}

    {{  footer  }}

{%  if cover_page  %}

    {{ cover_page }}

{%  endif  %}
{# The header is repeated after the cover page for all pages. #}

    {{  header  }}

    {{ content }}

The header and footer must be styled with position: fixed, after which they are displayed on every page.
I haven't found any great combined reference for the entity print module, but searching for what you want to accomplish along with your print engine's name should be helpful.
Comment: Thank you for your answer. I installed WkHtmlToPdf, but only because It was the first option in the documentation. After read your answer I have installed dompdf and I will use this engine. I don't care the engine if I can do what I need. Thanks.

How to customize entity print pdf


How can I retrieve the value of a field in a flagging?

Question: I have a global flag, spam, that has a textfield, reason, attached to it.
According to the Flag API documentation, I know I can check whether a user is flagged like this:
$spam && $spam->is_flagged($account->uid)

However, in this case, I want to retrieve the flagging, and then check the value of a field in that flagging.  I didn't see any directions for doing so in the documentation, so I'm at a loss about how best to proceed.
Comment: What type of var is `$spam`? Hopefully it's `flag_entity` but maybe it's `flag_flag`?
Answer: According to the Flag API
flagging_load

Loads a flagging entity. Parameters
$flagging_id: The 'flagging_id' database serial column.
$reset: Whether to reset the DrupalDefaultEntityController cache.
  Return value
The entity object, or FALSE if it can't be found

Therefore something like this might work:
$flaggings = flag_get_user_flags('node', $node->nid);
if (isset($flaggings['spam'])) {
    $flagging = flagging_load($flaggings['spam']->flagging_id);
}

You will then find your field in:
$flagging->field_reason


Find the total number of ways to select a non-empty subset of these people, such that no two adjacent people are selected.

Question: There are N people are sitting around a circular table. Let's call them P1, P2, . . . , PN ,
in order. P1 is sitting between P2 and PN . P2 is sitting between P1 and P3. P3 is
sitting between P2 and P4, and so on.
You need to select a non-empty subset of these people, such that no two adjacent
people are selected. Find the total number of ways in which you can do so.
For example, suppose N = 3, then we have P1, P2 and P3. If we select P1, then
neither P2 nor P3 can be selected. So, the only valid selections are {P1}, {P2}, {P3}.
So there are three possible ways, and hence the answer would be 3.
Suppose N = 4, then we have P1, P2, P3 and P4. The possible subsets are
{P1}, {P2}, {P3}, {P4}, {P1, P3}, {P2, P4}. So the answer would be 6.
Find the answer for the following values of N:
(a) N = 11
(b) N = 13
(c) N = 15
source:- Q.3 https://www.iarcs.org.in/inoi/2019/zio2019/zio2019-question-paper.pdf
ANS:- (a)198
(b) 520
(c) 1363
This question was from pen & paper test
My failed attempt:-
(a) For N = 11,
the possible subsets are {P1},{P2},....{P11} = 11 +
since P11,P2 are adjacent to P1, the next possible subsets are:- {P1,P3},{P1,P4},...,{P1,P10}
= 8 +
Similarly, P1,P3 are adjacent to P2, the next subsets are:-
{P2,P4},{P2,P5}.....,{P2,11} = 8 +
DOING SAME FOR P3,P4,P5,P6,P7,P8,P9,P10,P10, (each of the individual has 7 subsets)
total subsets of them are :- 7 x 9 + 8 + 8 + 11 = 90.
MY ANS:-90

Answer: Two comments:
First, your count for subsets of $2$ is off. When you choose $P_4$, you have already counted pairing that up with $P_1$ and $P_2$, and so you only have $6$ more options, rather than $7$. So, you get $8+8+7+6+5+4+3+2+1=44$ options.
However, an easier way to count this is to say that for *each * person we can pick $8$ others, giving $11\cdot 8 = 88$ options.  Of course, now you need to rule out double-counting: first picking $P_1$ and then picking $P_6$ gives you the same subset as first picking $P_6$ and then picking $P_1$. So, you need to divide by $2$. In other words, there are $\frac{88}{2}=44$ possible subsets of size $2$
Second: what about subsets of size $3$?  For example, you can pick $P_1$, $P_4$, and $P_8$.  You didn't count that subset, or any subset of size $3$. And you also didn't consider subsets of size $4$ or $5$. Now, any subset of size $6$ or larger will be impossible (do you see why?), but you will have to count the subsets of size $3$, $4$, and $5$.
OK, how many subsets of size $3$ are there?

 You can again start with $P_1$, pick $P_3$ as a second person, and then have a choice of $6$ ($P_5$ through $P_{10}$) as a third. So, that's $6$ options. Then, still staying with $P_1$, you can pick $P_4$ as your second person, but now you have only $5$ persons left ($P_6$ through $P_{10}$) for the third one. So, that's another $5$ options.  Choosing $P_5$ as the second gives $4$ options ... and continuing this, you get $6+5+4+3+2+1=21$ options with $P_1$ as the first person.  This, of course, repeats for all $11$ people, so you get $11\cdot 21=231$ options. But again, you are over-counting, because for any subset of $3$, you could have picked any of those $4$ as your 'first' person. As such, every triple got counted $3$ times, and so you have $\frac{231}{3}=77$ possible subsets of size $3$

For subsets of $4$:

 Again, start with $P_1$, add $P_3$, then $P_5$, and now you have $4$ options left ($P_7$ though $P_{10}$). Now we can make the third person $P_6$, and that gives you $3+2+1=6$ options. Likewise, you get $2+1=3$ and $1$ one more while having $P_1$ as the second person. So, there are $10+6+3+1=20$ subsets with $P_1$ as the first person. Again, multiply by $11$ ... and divide by $4$, since each subset gets counted $4$ times, since we could have started going around with each of the $4$ people in each subset. So: $\frac{11 \cdot 20}{4}=55$

Subsets of $5$:

 With $P_1$, $P_3$, $P_5$, and $P_7$ you have $2$ options left. You can also make $P_8$ the fourth person, and now there is $1$ option left. You can make the third $P_6$, and that also leads to $1$ options, and finally you can pick $P_4$ as the second, for a final option. Total: $5$ subsets with $P_1$. Again, multiply by $11$, and divide by size of subsets: $\frac{11 \cdot 5}{5}=11$ possibilities.

Total:

 $11+44+77+55+11=198$ subsets
Comment: for p3,...p10 it will be 7 because let say p3 then **{p3,p1},{p3,5},{p3,p6},{p3,p7},{p3,p8},{p3,p9},{p3,p10},{p3,p11}**, but you see here **(p3,p1}** is already counted before  for p1.
Comment: what are the efficient way to count for susbset of size **3** , **4** , etc
Comment: @AyushRaj Yes, that is another way of counting that will avoid over-counting. But then for $P_4$ you only have $6$ options, because you already have $\{ P_1, P_2 \}$ and $\{ P_4, P_2 \}$.  Also, I think my method of counting once, multiplying by $11$, and then dividing by the number of ways every subset ended up being counted is a lot more efficient.
Comment: Thanks a lot :)
Answer: Let $C_n$ be the number of ways to choose a group of people from a circle of $n$ people such that no two adjacent people are chosen, and let $L_n$ be the number of ways to choose a group of people from a line of $n$ people such that no two adjacent people are chosen.  For now, we will include the possibility that no one in the group is chosen -- remind me to rule that out at the end, okay?
Step 1: $C_n=L_{n-1}+L_{n-3}$
Proof: Let $n$ people numbered $p_1$ through $p_n$ be in a circle.  Either $p_n$ is in the group or not.  If $p_n$ is not in the group, then the remaining people could be selected for a group in $L_{n-1}$ ways.  If $p_n$ is in the group, then we know for certain that $p_{n-1}$ and $p_1$ cannot be in the group, so the remaining members of the group can be chosen in $L_{n-3}$ ways.
Step 2: $L_n=F_{n+2}$, where $F_n$ is the n'th Fibonacci number (i.e. $L_1=2$,$L_2=3$)
Proof: By inspection, $L_1=2$ and $L_2=3$, since we are still counting the possibility that no one is chosen. Let $n>2$ be given, and let $p_1$ through $p_n$ be our $n$ people in a line.  Again, either $p_n$ is in the group or not.  If not, then the remaining members of the group can be chosen in $L_{n-1}$ ways.  If so, then $p_{n-1}$ must not be in the group and the remaining members can be chosen in $L_{n-2}$ ways.  Therefore, $L_n=L_{n-1}+L_{n-2}$ and the sequence is a tail of the Fibonacci sequence starting at $2$.
Hmmm?  Oh, right, thank you.  Since there is 1 way to have nobody in the group and we're not supposed to count that, our final answer is $C_n-1=F_{n+1}+F_{n-1}-1$.
Comment: I didn't understand why **Ln = Ln−1 + Ln−2**, since **Ln**  is the number of ways to choose a group of people.
so, that means **no. of ways to choose people (no 2 adjacent) = no. of ways to choose [(n-1) people + (n-2) people]**


PDOException: SQLSTATE[42S22] When adding quiz content

Question: I am trying to implement the quiz module on a new website and it's throwing the following error when attempting to add content > quiz. I believe the code I have was part of a feature I was trying to migrate over from a different website so I could retain the functionality involved with it, but it's proven to be less than compatible. (Going from Drupal Commons 7.50 to Plain Drupal with a demo theme built in 7.54).
Can someone interpret this error and point me in the right direction as to what the missing piece of the puzzle is here?

PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'base.allow_change_blank' in 'field list': SELECT base.qnp_id
  AS qnp_id,  base.vid
      AS vid, base.nid AS nid, base.uid AS uid, base.number_of_random_questions AS
      number_of_random_questions, base.max_score_for_random AS max_score_for_random,
      base.pass_rate AS pass_rate, base.summary_pass AS summary_pass,
      base.summary_pass_format AS summary_pass_format, base.summary_default AS
      summary_default, base.summary_default_format AS summary_default_format,
      base.randomization AS randomization, base.backwards_navigation AS
      backwards_navigation, base.keep_results AS keep_results, base.repeat_until_correct
      AS repeat_until_correct, base.quiz_open AS quiz_open, base.quiz_close AS
      quiz_close, base.takes AS takes, base.show_attempt_stats AS show_attempt_stats,
      base.time_limit AS time_limit, base.quiz_always AS quiz_always, base.time_left AS
      time_left, base.max_score AS max_score, base.allow_skipping AS allow_skipping,
      base.allow_resume AS allow_resume, base.allow_jumping AS allow_jumping,
      base.allow_change AS allow_change, base.allow_change_blank AS allow_change_blank,
      base.build_on_last AS build_on_last, base.show_passed AS show_passed,
      base.mark_doubtful AS mark_doubtful, base.review_options AS review_options,
      base.result_type AS result_type FROM {quiz_node_properties} base WHERE (base.vid
      IN (:db_condition_placeholder_0)) ; Array ( [:db_condition_placeholder_0] => 351 )
      in EntityAPIController->query() (line 187 of
      /Applications/AMPPS/www/example/docroot/profiles/cms/modules/contrib/entity/inc
      ludes/entity.controller.inc).

Here is how the process went:

I implemented an online training feature from our current website for the new one
It included syllabus and quiz content types, neither of which worked until I installed the Title module
Once Title was installed, I received a new error only when trying to create content type quiz:

EntityFieldQueryException: Unknown field: title_field in
  EntityFieldQuery->fieldOrderBy() (line 954 of
  /var/www/html/example/docroot/includes/entity.inc).

I updated the quiz from 7.x-5.0-alpha4+77-dev to 7.x-5.1 and all seemed well
I removed a quiz field field_syllabus_ref and recreated it a different way, to reference the title of the syllabus page in the quiz.
Now I get the error below unless the module is uninstalled. When it is uninstalled, I am still able to add quiz content but I get a different error instead after saving it.
Answer: The error was somehow related to the UUID module, which couldn't be disabled without derailing the entire website. Here's how I fixed it.

uninstalled the feature that held the affected quiz module
drush pm-disable <my_feature>
drush pm-uninstall <my_feature>
uninstalled the quiz module and all the modules dependent on it:
drush pm-disable quiz
drush pm-uninstall quiz
moved the quiz module files to my temp backup outside the drupal root:

mv sites/all/modules/contrib/quiz ../<temp_backups>/quiz

downloaded the quiz module fresh and reenabled it and all the dependent modules and reenabled the feature that contained it:

drush dl quiz
drush en quiz
That took care of this particular error.
Please note: I did not yet have any quiz data or content set up; this guideline is only safe for a dev environment. I have not tested it with any actual content or user data.


Devo criar uma tabela por categoria, ou uma única tabela?

Question: Quero montar um site de classificados e tenho uma dúvida: como eu posso fazer a criação das categorias no BD? Crio uma tabela de anúncios pra cada categoria? Ou crio uma tabela Categorias com elas dentro? Qual a melhor forma?
Comment: **NÃO crie uma tabela para cada categoria**.
Comment: Ampla? Não vejo nada de ampla..só queria saber como posso fazer (a melhor forma é fazendo X ou fazendo Y) isso é amplo?
Comment: Faça uma tabela para categorias, com chave estrangeira.
Comment: Acho que modelagem e normalização não é um assunto amplo, não é atoa que existem tags para isso.
Comment: Se a única coisa que varia de uma categoria pra outra é o nome e o identificador único (ID), não crie mais tabelas.
Comment: Essa pergunta está um pouco ampla, não?
Answer: Se categoria é um conceito bem fechado, o ideal é não criar uma tabela para cada categoria.
Um bom exercício de sanidade: imagine que você já tem mil notícias no site, e agora toda notícia ou categoria precisa ter uma coluna a mais. Você prefere fazer alterações - e ainda correr o risco de errar - em apenas uma tabela ou em vinte?
Existem duas formas de se lidar com categorias, no seu caso:

Uma tabela de categorias, e a tabela de notícias tem chave estrangeira pra ela. Isso traz duas vantagens: ao mudar o nome da categoria você atualiza todas as notícias dela automaticamente, e para adicionar uma categoria nova basta adicionar um registro em uma tabela.
Categoria como uma coluna de tipo textual na tabela de notícias. Isso pode ser visto por muita gente como desnormalização. Isso simplifica o schema do banco e, dependendo de como for feito, pode tornar as buscas mais rápida. Mas para atualizar uma categoria, você precisa atualizar todos os registros de notícia daquela categoria.

Se a categoria for ter mais informações além do nome, sugiro preferir a primeira forma.


An error which appears in Autocomplete taxonomy fields

Question: Did someone ever note this annoying D7 taxonomy error? It jumps out when I seem to "pass" a certain amount of terms or characters. The error is as follows:

An AJAX HTTP request terminated abnormally. Debugging information
  follows. Path:
  http://pancherim.co.il/taxonomy/autocomplete/field_engines StatusText:
  ResponseText:  ReadyState: 4
Answer: In my case I get this exact error when using Views. It happens when I try to save changes in a given view and I click too quickly to start another action, while the ajax loader of the previous action hasn't gone away. Basically it's moaning that I should wait for one action to finish before starting another.
In your case, maybe the ajax request isn't fast enough to go and grab an existing match for the taxonomy term(s) you're adding in order to autocomplete it. Do you have enough memory allocated to Drupal in your machine/server?
If you're using the admin overlay, another trail to follow is comment #10 in this issue
Comment: Hi. interested to read more about this server-dedicated memory for Drupal. never heard of it.
Comment: My bad I should have said "drupal/apache instance". You can't allocate RAM directly to Drupal per se, but to the instance in which it runs (ex: dedicated server, VPS etc).
Comment: i am sorry. i don't understand. what should i do?
Answer: This problem started occurring after switching my site to https.
Setting $base_url appropriately in settings.php fixed it for me. (See also this comment on d.o.)


Coefficients of the stirling's series expansion for the factorial.

Question: Knowing the Stirling's approximation for the Gamma function (factorial) for integers:
$$\Gamma(n+1)=n!\approx \sqrt{2\pi n}n^ne^{-n}\bigg(1+\frac{a_1}{n}+\frac{a_2}{n^2}+\cdots\bigg)$$
Using the above approximation one can write:
$$(n+1)!=\sqrt{2\pi(n+1)}(n+1)^{n+1}e^{-(n+1)}\bigg(1+\frac{a_1}{n+1}+\frac{a_2}{(n+1)^2}+\cdots\bigg)$$
We know that following recursion holds:
$$(n+1)!=(n+1)n!$$
One can rewrite this:
$$(n+1)!=(n+1)\sqrt{2\pi n}n^ne^{-n}\bigg(1+\frac{a_1}{n}+\frac{a_2}{n^2}+\cdots\bigg)$$
All this comes from: https://www.csie.ntu.edu.tw/~b89089/link/gammaFunction.pdf (Page 8-9)
Then the author gives this expansion to calculate the $a_k$ coefficients when $n$ becomes large.
Comparing these two expressions for $(n+1)!$ gives
$$1+\frac{a_1}{n}+\frac{a_2}{n^2}+\cdots=\bigg(1+\frac{1}{n}\bigg)^{n+1/2}e^{-1}\bigg(1+\frac{a_1}{n+1}+\frac{a_2}{(n+1)^2}+\cdots\bigg)$$
Then he says, that after "classical series expansion" this equals:
$$1+\frac{a_1}{n}+\frac{a_2-a_1+\frac{1}{12}}{n^2}+\frac{\frac{13}{12}a_1-2a_2+a_3+\frac{1}{12}}{n^3}+\cdots$$
I don't understand how he got there. Only thing that came to my mind was, that as $n\to\infty$ $\big(1+\frac{1}{n}\big)^n$ goes to $e$ but then we are left with $\big(1+\frac{1}{n}\big)^{1/2}$. When i expand this into binomial series, i get:
$$\bigg(1+\frac{1}{2n}-\frac{1}{8n^2}+\frac{1}{16n^3}\cdots\bigg)\cdot\bigg(1+\frac{a_1}{n+1}+\frac{a_2}{(n+1)^2}+\cdots\bigg)$$
And I'm stuck here.
Or is there any other elementary way how to compute the coefficients $a_k$ of the stirling's series expansion for factorial/Gamma function?
Comment: That part is easy, just Maclaurin expansion of $\sqrt{1+x}$.
Comment: Have a look at https://dlmf.nist.gov/5.11.i (especially formulae 5.11.3--5.11.6).
Answer: You were close. Note that1
$$
e^{-1}\left(1+\frac{1}{n}\right)^{n+1/2}=1+\frac{1}{12n^2}-\frac{1}{12n^3}+\frac{113}{1440n^4}+\cdots\tag1
$$
Therefore, you have
$$
\bigg(1+\frac{1}{12n^2}-\frac{1}{12n^3}+\cdots\bigg)\cdot\bigg(1+\frac{a_1}{n+1}+\frac{a_2}{(n+1)^2}+\frac{a_3}{(n+1)^3}+\cdots\bigg)=\\
1+\frac{a_1}{n}+\frac{a_2-a_1+\frac{1}{12}}{n^2}+\frac{a_3-2a_2+\frac{13}{12}a_1+\frac{1}{12}}{n^3}+\cdots\tag2
$$
as per
$$
\frac{1}{n+1}=\frac{1}{n}-\frac{1}{n^2}+\cdots\\
\frac{1}{(n+1)^2}=\frac{1}{n^2}-\frac{2}{n^3}+\cdots\\
\frac{1}{(n+1)^3}=\frac{1}{n^3}-\frac{3}{n^4}+\cdots\\
\text{etc.}\tag3
$$

Easy (but slightly cumbersome) exercise:
\begin{equation}
\begin{aligned}
{}&\lim_{n\to\infty}e^{-1}\left(1+\frac{1}{n}\right)^{n+1/2}=1\\
{}&\lim_{n\to\infty}n^2\left[e^{-1}\left(1+\frac{1}{n}\right)^{n+1/2}-1\right]=\frac{1}{12}\\
{}&\lim_{n\to\infty}n^3\left[e^{-1}\left(1+\frac{1}{n}\right)^{n+1/2}-1-\frac{1}{12n^2}\right]=-\frac{1}{12}\\
{}&\text{etc.}
\end{aligned}\tag4
\end{equation}
These are basic limits that are left to the reader.
Comment: @MichalDvořák Oh, it's pretty simple: $\frac{1}{n+1}=\frac{1}{n}\frac{1}{1+n^{-1}}=\frac{1}{n}(1-n^{-1}+n^{-2}-n^{-3}+\cdots)$ (just a geometric series in $n^{-1}$).  Can you take it from here?
Comment: @MichalDvořák Instead of using the multinomial theorem, you can also use $\frac{1}{(n+1)^{a+1}}=\frac{(-1)^a}{a!}\left(\frac{\mathrm d}{\mathrm dn}\right)^a\frac{1}{n+1}$ and differentiate term-wise.
Comment: Hang on, how did you come up with the first line?
Comment: @MichalDvořák I edited in a hint. Let me know if you need some more details. Cheers!
Comment: I would be interested in deriving the (3) formulas, I'm unfamiliar with these, i got the (1) and the limits (4)
Comment: Hang on, but Geometric series are $1+r+r^2+r^3+...=\frac{1}{1-r}$, while you have '+' sign here. What am i missing?
Comment: Just take $r'=-r$, so that $1-r+r^2-r^3+\cdots=\frac{1}{1+r}$
Comment: Oh, didn't see that, one last thing, how about the powers? $\frac{1}{(n+1)^2}$... How do the coefficients 2,3 appear in here?
Comment: $$\frac{1}{(n+1)^2}=\left[\frac{1}{n+1}\right]^2=\left[\frac{1}{n}-\frac{1}{n^2}+\frac{1}{n^3}+\cdots\right]^2=\cdots$$
Comment: So just multinomial theorem? That came to my mind aswell, but found it pretty long. Ok I think this is it, thank you for your time!
Comment: @MichalDvořák That's it! No problem :-)
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/72439/discussion-between-michal-dvorak-and-accidentalfouriertransform).
Answer:
We expand the series up to terms of $\frac{1}{n^3}$. We obtain for $\left|\frac{1}{n}\right|<1$
  \begin{align*}
\color{blue}{\left(1+\frac{1}{n}\right)^{n+\frac{1}{2}}e^{-1}}
&=e^{-1}e^{\left(n+\frac{1}{2}\right)\ln\left(1+\frac{1}{n}\right)}\\
&=\exp(-1)\exp\left[\left(n+\frac{1}{2}\right)\left(\frac{1}{n}-\frac{1}{2n^2}+\frac{1}{3n^3}+\cdots\right)\right]\\
&=\exp(-1)\exp\left(1+\frac{1}{12n^2}-\frac{1}{12n^3}+\cdots\right)\\
&=\exp\left(\frac{1}{12n^2}-\frac{1}{12n^3}+\cdots\right)\\
&\color{blue}{=1+\frac{1}{12n^2}-\frac{1}{12n^3}+\cdots}\tag{1}
\end{align*}

and applying the binomial series expansion

we obtain
  \begin{align*}
&\color{blue}{1+\frac{a_1}{n+1}+\frac{a_2}{(n+1)^2}+\frac{a_3}{(n+1)^3}+\cdots}\\
&\qquad =1+\frac{a_1}{n\left(1+\frac{1}{n}\right)}+\frac{a_2}{n^2\left(1+\frac{1}{n}\right)^2}
+\frac{a_3}{n^3\left(1+\frac{1}{n}\right)^3}+\cdots\\
&\qquad =1+\frac{a_1}{n}\left(1-\frac{1}{n}+\frac{1}{n^2}\cdots\right)
+\frac{a_2}{n^2}\left(1+\binom{-2}{1}\frac{1}{n}+\cdots\right)
+\frac{a_3}{n^3}\left(1+\cdots\right)\\
&\qquad\color{blue}{=1+a_1\cdot\frac{1}{n}+\left(-a_1+a_2\right)\frac{1}{n^2}
 +\left(a_1-2a_2+a_3\right)\frac{1}{n^3}+\cdots}\tag{2}\\
\end{align*}

Putting (1) and (2) together

we obtain
  \begin{align*}
&\left(1+\frac{1}{12n^2}-\frac{1}{12n^3}+\cdots\right)
\left(1+a_1\cdot\frac{1}{n}+\left(-a_1+a_2\right)\frac{1}{n^2}
 +\left(a_1-2a_2+a_3\right)\frac{1}{n^3}+\cdots\right)\\
&\quad\color{blue}{ =1+a_1\cdot\frac{1}{n}+\left(\frac{1}{12}-a_1+a_2\right)\frac{1}{n^2}
  +\left(-\frac{1}{12}+\frac{13}{12}a_1-2a_2+a_3\right)\frac{1}{n^3}+\cdots}
\end{align*}
and the claim follows.
Comment: @MichalDvořák: We use the series expansion of $\exp(x)=1+x+\frac{x^2}{2}+\cdots$ here with $x=\frac{1}{12n^2}-\frac{1}{12n^3}$ and we only need to expand up to the linear term in $x$.
Comment: Seems fine, just the last line of (1). How did you change $\exp\bigg(\frac{1}{12n^2}-\frac{1}{12n^3}+\cdots\bigg)$ into $\bigg(1+\frac{1}{12n^2}-\frac{1}{12n^3}+\cdots\bigg)$
Comment: @MichalDvořák: Many thanks for granting the  bounty.


How to dampen an amp's volume for recording?

Question: Unfortunately I live in a block of flats and strangely enough not everyone appreciates loud guitar music..
However, I'm of the opinion that recording an amp with a mic will pretty much always sound better than a software amp (although I have to admit, Revalver is really good, so I have tried to get the best tone possible).
Does anyone have any tips or tricks to try and restrict the volume of the amp while still getting enough signal for the mics? Specifically, more the bleed into the other flats rather than the volume of the amp itself. The amp is a Bugera TriRec (with adjustable power output) set down to 1W, going through a Marshall 1960AV (however I'm only using the left side to try and keep some volume down so it's actually only coming out of 2 speakers).
I've tried the technique of covering the amp with a thick sheet and it's a good start, but I was wondering if anyone else knew anything I could try?
As a side note, I know it's not an ideal situation and I know the best tones are achieved by getting the speakers in the cab to actually start moving some air, but for demos in a flat, I'm having to make do for now!
Comment: @blueskiwi yeah that's what I meant by moving the air as well, the speakers breaking up when they're pushed is all part of the tone too. At the end of the day, there's no substitute for cranking a 4x12 up at max volume but I just want to find some acceptable alternatives!
Comment: I think that pushing just 1 watt through a pair of 12" speakers won't really give the best sound anyway. Sorry!
Comment: Recording that way isn't really a great idea IMHO.  Better to take the output of any & all preamps , and possibly adding an analog network to mimic the impedance of the speakers, and feeding that directly to an ADC . Collecting a clean signal from speakers to a mic is very difficult.  THere's a reason people spend money constructing anechoic sound studios.
Comment: @Tim "Tube amps of five watts or less have been at the heart of some of the most inspired recordings by rock's legendary guitarists—many of whom used stacks onstage, but favored small "practice" combos from Fender, Supro, Selmer, Valco, Vox, and others for tracking mammoth tones to tape." from http://www.guitarplayer.com/miscellaneous/1139/roundup-11-micro-tube-amps/22244
Comment: @ToddWilcox yes but those small low wattage amps had small low wattage speakers too...  I assume that's what Tim meant - you're not getting any compression from the speaker (as it's hardly having to 'work') which I guess is part of the sound of a cranked amp
Comment: This will sound like an advertisment, but try the Rivera RockCrusher recording. It is a power soak, combined with a line out. The EQ section on the unit makes the direct signal usable. Combine this with the attenuated from the speakers, and you can get quite good results. The attenuated tone is very good to my ears.
Answer: Given the situation you described I wouldn't go for a miked amp, because you can't really crank the amp, you might have interference from other flats or from the street, etc.
For recording a demo, a good amp simulation will very likely be good enough. But if you really don't want to use software simulation, there's yet another option: use a DI box with speaker simulation, like Hughes & Kettner's Redbox. Note that you will also need a power soak between your amp and the cab simulation / DI box, otherwise you might destroy the power amp if you run it without a load (speaker). This method will give you the amp's sound, except for the speaker, but these days most hardware cab sims are quite good.
Comment: I've used that method before, it's a great idea but I can't seem to get anything usable from it really although I may just be being a perfectionist here!
Comment: You can put the speaker simulator between the amp and the dummy load if you want. I think they are wired in parallel so it doesn't matter as long as you have a dummy load on there somewhere.
Answer: You need a lower efficiency speaker. It's the only way to significantly change the output of your amp. Speakers are rated with SPL, they average about 98SPL, loudest are the JBL f120s at about 103 SPL.
Every 3db of SPL will double or halve the apparent wattage of your amp. Low SPL speakers are also way cheaper than loud speakers. You can probably get a decent light magnet 90spl 25 watt speaker for about 30 bucks. Scavenge an old practice amp for a cab, close the back up, cover any unused speaker holes with wood and put some fiberglass insulation on the inside back, left and bottom only.
You can't have speakers just hanging out unused.  You will need to make a custom ghetto cab. 1x12 in a 2x12 cab will sound huge. Then build a couch "pillow fort" around the cab which should be close miced straight on the grill. Move the mic towards the edge for a brighter sound, towards the dustcap for a darker sound.
And have your parts rehearsed. People will complain about crappy loud music 1000x faster than something that sounds good.
re: Todd's expansion of my answer
I'm glad my pillow fort technique is gaining some traction, but I'm going to disagree on some details here.
First, you should not mismatch output and speaker impedance. It always sounds weak and there is a danger of  flyback voltages damaging the amp using a lower z transformer tap into a higher z speaker load.
Second, you must use a closed back cab, close miced. My conception of b the pillow fort is specifically designed to provide an acoustically dead environment to avoid small room ambiance, which simply isn't epic. The fiberglass treatment will break internal standing waves and make the cab sound bigger.
I'd avoid giving the neighbors warning or taking test runs, have your parts rehearsed and nail them. Then shut the operation down until you have more parts down cold.
Comment: I think Weber makes some good cheap low SPL speakers
Comment: That's true but that wasn't the question.
Comment: Got to say I didn't even think of speaker efficiency, that's a great idea! I've used a smaller 1x12 cab but the speaker itself is atrocious so I stopped using it. I'll also give the pillow fort thing a try, might at least dampen a little more of the sound without compromising it!
Comment: nice one, cheers man! i'll mark your answer as correct because it's a solution I've not tried but really you're both right!
Comment: This answer does not promote an accurate understanding of what speaker/amp power ratings are, and how they interact.
Answer: If you have some good DIY skills I can't see why you couldn't construct an amp & mic chamber. It would need a way to isolate contact propagated vibrations from the ground such as springs. You would also need to select damping material that was suited for the highest peaks in the audio output (look at the EQ output you see with your mic)
But, unless you have a very good amp and the sound cranked you will probably be better off with software not a real amp.
Comment: +1 for isolating the speaker from the building structure. One way is get a suitable sized inner tube from a tire, put the speaker on it and inflate it just enough to lift the speaker off the floor (if you inflate it more, it won't work so well). Another way is to hang the speaker from something like a shelf, using bungee cords (you can buy them for tying luggage onto car roof racks, etc) Both those techniques are used in "serious" vibration isolation work. Most of the unwanted sound transmitted in buildings is through the structure of the building, not through the air.
Comment: I've done this before and it was a lot of work and sounded terrible because of early reflections, but a better design and better construction might yield better results than what I got. A few companies make these (Demeter springs to mind) and they might be better than my homebrew also. In the end, a speaker simulator and load box might sound better. In either case you won't get the room sound so you don't lose anything going with a speaker sim and it's a lot less work and/or money.
Comment: I really like the bungee cord idea, you could perhaps use the legs of a sturdy upside down table :)
Answer: Having been down this road myself, I agree that even a quiet amp miked up in a room is much much better than the best amp simulator software I've ever used. And you can get very good tone in an apartment at reasonable levels. The other answers are solid, and I want to add a few things I've learned and used over the years.
Some ways to reduce the sound pressure level coming from your speakers, including ways mentioned by other answers:

Reduce the output power (you've already done this)
Reduce the output impedance (look for a 4/8/16 Ohm switch if you have one, set it to the lowest number it has)
Increase the load impedance of the speaker cabinet (you might be able to do this by actually using all four drivers instead of just two - depending on the wiring of your cabinet)
Use a less sensitive cabinet or change the drivers in your cabinet to less sensitive drivers (as mentioned by another answer)
Reduce the bass frequencies in your tone as much as you can stand - they are more likely to annoy the neighbors and you can fill them out again using DIed bass guitar and/or keyboards - or you can DI the guitar before it goes to the amp and get your low end from the DI track, which you can run through an amp simulator or not (I just thought of this idea and I really like it - I'll have to try it next time I record in my apartment!)

Some ways to reduce the amount of sound that makes it into your neighbor's dwellings:

Get the speaker cabinet up off the floor, ideally on some foam pads or platform designed to isolate the cab from the floor (Auralex makes these, among others)
Point the cabinet towards a window or exterior wall; if open-backed, stack up pillows or baffles behind the cabinet since open-backed cabinets are almost as loud from the back as from the front - if you point it towards a window put some pillows or drapes in front of the window because reflections off a window will sound really bad getting into the mic
Build a pillow fort or other baffle system around the amp with the mic inside it (as others have mentioned) Note: This should be a last resort, because whatever baffling you do around the mic and cabinet will at least in some ways reflect sound back to the mic, which will add a lot of early reflections which will sound bad. Also you will be blocking out a lot of the "air" and room tone which is part of the advantage of miking a cab instead of using a speaker simulator or amp modeller. Frankly, if this were my only option I would just DI and use amp modelling instead.

Some other tips:

Obviously, recording during the day on a weekend is least likely to offend. Late Sunday morning might be best if you are surrounded by church-goers, partly because of the next point:
With a really quiet amp, you have to make everything else as quiet as possible to have a good signal to noise ratio. Pre-cool or pre-heat the space with the A/C or heater on full and then shut it completely off before you make a take. Do the same with the refrigerator (don't forget to turn it back on!) Finding a daytime period where you're less likely to wake people and trucks are less likely to drive by outside and people won't be coming and going slamming their doors is also important. Around me, Sunday morning is magic time for this. If you live near adherents to some other major religions, you might find Friday or Saturday evening works better.
Along with the last point, you want to stand as far away from the microphone as possible when recording. If you can get far enough away that you have to wear headphones to hear the amp clearly that's a good sign. If the microphone picks up the acoustic sound of your playing, it's going to sound really bad. It's all pick noise and jangle. You never notice it playing with a loud amp, but if it gets all in the microphone you almost certainly won't like it.
Try having a friend play and walk around in the lobby of your building to see how loud it is from outside the apartment. Usually more sound gets through the door than the shared walls, so this is often a check of the worst-case scenario. If you feel like it's quiet enough outside the door of your place, then you are probably good.
The final fail-safe is to DI all of your tracks, get great takes and/or edit them so they are just how you want, and then rent a space for a day and re-amp them all. I would take a DI of every take just as a safety anyway. There are so many uses for a DI copy of a solid take that you're likely to kick yourself if you don't have one.

Edit for one more note/idea:
You can get real tube amp tone silently by sacrificing the speaker and room sound quality. If I have to be 100% silent, I go with a speaker simulator and load box and I take the speaker out from my amp, run it through the simulator and then into the load box. Unfortunately the one speaker simulator that I like (The DMC Cab-Tone) has been out of production for a while. I have a Palmer and a Red Box, both still in production, and I like the Red Box better between those two. Any load that can be a 100% load (instead of just an attenuator) will work, and I find the THD Hot Plate products are solid. This method lets you use all the tone controls, distortion, presence and reverb controls, power tube and output transformer saturation, and all that from your amp without making a lot of noise. It's a bit of an investment though, and still doesn't sound quite as good as a solid mic in a decent room. If you have a great convolution reverb plug-in to add to this very dry tone, it can sound very convincing and totally will blow away any amp simulator.
Comment: haha perfect answer man, thanks for that! I've heard a few of those things before and some of the are common practice for me, like taking a DI track of the guitar regardless of what I'm doing and I also tend to isolate my amp in a separate room from where I'm recording so there's a little noise as possible from my playing reaching the mic! I'm actually gonna mark this as the correct answer because it's the most detailed one here with some great ideas (especially the bit with the bass frequencies from an amp, I've always found they do darker tones better than bright anyways!)
Comment: I disagree on a few of these points. I've expanded my original answer accordingly.
Comment: Always happy to help out a fellow apartment dwelling musician.
Comment: You mentioned reducing bass frequencies and DIing the bass frequencies, that sounds like a great idea. Please get back to us with results.
Comment: Stuffing an open back will have the opposite effect, especially at low frequencies. While the open back emits sound to the rear, it's out of phase with the sound out front so most of the low frequencies will cancel out. There is a also good cancellation to the sides. Technically speaking it's the difference between dipole and monopole radiation. That's why open back is  useless for bass
Answer: In a situation such as this (home recording with "unenthusiastic" neighbors) there are two approaches, usually taken together.

Build an isolation enclosure.  This can be an existing closet space that you retrofit, or a purpose-built "box" that the amp lives within.  To be effective, it has to be airtight, and ideally has a frame (including floor and ceiling) that is isolated from the main structure.

Use a "power soak" or "dummy load" on your amp output in series with your speaker. A dummy load is a essentially a resistor that is rated for the output voltage of your amp, and to the amp it "looks like" a speaker impedance.  The amplifier thus continues to operate in the same voltage output range as you would use normally, but the majority of the power is dissipated as heat by the dummy load, rather than as SPL from the speaker.


Meu navegador não está conseguindo seguir a rota corretamente e está retornando "erro 404"

Question: Aqui está meu código:
-Rotas
<code>import {
  BrowserRouter as Router,
  Routes,
  Route,
} from "react-router-dom"

import { Home } from '../pages/Home';
import { Cart } from '../pages/Cart';
import { Catalog } from '../pages/catalog';

export function AppRoutes() {
  return (
    <Router>
      <Routes>
        <Route path='/' element={<Home />} />
        <Route path='/Cart' element={<Cart />} />
        <Route path='/catalog' element={<Catalog />} />
      </Routes>
    </Router>
  )
}

-App.tsx

import { useState } from "react"
import { Tweet } from "./components/Tweet"
import {AppRoutes} from './routes/Routes'

function App() {

  return (
    <AppRoutes />
  )
}

export default App

-tsconfig.json

{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "lib": ["DOM", "DOM.Iterable", "ESNext"],
    "allowJs": false,
    "skipLibCheck": false,
    "esModuleInterop": false,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": ["src", "routes", "routes/Routes.tsx"],
  "references": [{ "path": "./tsconfig.node.json" }]
}
</code>
Comment: Olá amigo. Lembre-se de usar as ferramentas de formatação disponíveis para postar código... Quanto ao problema, é um pouco difícil de alguém ajudar sem poder reproduzir localmente... 404 significa não existente - tu tens certeza que os endereços estão corretos?
Comment: Então, sim. O código estava funcionando normalmente até o momento em que mudei a pasta "routes" de lugar. Depois que parou de funcionar até tentei colocar de volta mas não voltou a rodar. Acredito que o problema está nas rotas pois em nenhum lugar indica erro, nem no Vs Code ou no navegador
Comment: Amigo, ao que parece pelo que tu descreveste, o problema está nas tuas rotas. É impossível que alguém consiga te ajudar (além de te dizer - verifica se as rotas estão corretas) sem reproduzir exatamente o teu ambiente (inclusive com a localização de cada dependência). A minha recomendação é que tu vá debugando e ajustando as rotas até encontrares o erro... boa sorte...
Comment: Certo, muito obrigado!
(como marco a pergunta como respondida?)
Comment: Só é possível marcar como respondida quando há uma resposta nela. Se há uma resposta e ela soluciona o caso, quem pergunta pode selecionar como resposta correta (aparece um V verde para ser marcado)
Comment: Podes responder algo aqui então pra mim marcar como respondido e encerrar a pergunta?
Comment: Coloquei uma resposta, mais ou menos o que coloquei nos comentários...
Comment: Muito Obrigado!
Answer: O erro que estás tendo significa página inexistente. Provavelmente está acontecendo porque os recursos - que, de acordo com os comentários que tu colocaste, existiam - foram deletados ou movidos para um lugar que não bate com as rotas que definiste.
Para resolver isso, tu precisas ir ajustando as rotas e debugando até encontrares o erro. Vá ajustando os caminhos (path) de cada rota e veja se eles passam a ser encontrados. Não há muito que a gente possa ajudar além disso, pois precisaríamos reproduzir com exatidão o ambiente onde teu software está rodando para reproduzir e corrigir.


Managing objects of different classes in a single NSMutableArray

Question: I'm looking for advice on whether or not this is a good practice. I apologize for the long form explanation. I have a large grid of x,y coordinates. The grid is occupied by objects of varying classes, all with different methods and data. When a user touches a grid coordinate, I'm looking for the cleanest way to route my program to the proper method, dependent on the object type.
I'll use shapes as an easy way to explain what I'm doing. Say I have 2 classes, Circle and Square both with a parent class of Shape.
I'm adding objects of Circle class and Square class to an NSMutableArray called shapeManager. When a user touches the grid I want to figure out the object type for that coordinate so I can route to the appropriate method.
for (Shape *shape in shapeManager) {

  if (shape.type == kCircle) {

    [self circleSelected:shape];

  }

}

-(void)circleSelected:(circle *)circle { }

Am I recasting the pointer as a different class when I do this? Are there any downsides to this? I'm just looking for a good way to handle a touch event on a grid, when the object that lives at that coordinate is unknown and of multiple possible classes.
Answer: All classes that derive from NSObject inherit a method called isMemberOfClass: that will test for class membership using introspection.  You may find this useful for your purposes.
for (Shape *shape in shapeManager) {

    if ([shape isMemberOfClass:[Circle class]]) {
        [self circleSelected:(Circle*)shape];
    }
    else if ([shape isMemberOfClass:[Square class]]} {
        [self squareSelected:(Square*)shape];
    }
}

There is also an isKindOfClass: method that does a similar test, but will also return true if the receiving object is a subclass of the class you are testing against.
Answer: How about implementing 'selected' method in the subclasses of Shape, which are Circle and Square class. Then the object can call 'selected' method directly.
for (Shape *shape in shapeManager) {
    [self selected];
}

Circle implementation
@interface Circle: Shape
{
}
@implementation Circle
-(void)selected
{
    // do your circle select stuff here
}

@end

Square implementation
@interface Square: Shape
{
}
@implementation Square
-(void)selected
{
    // do your square select stuff here
}

@end

Answer: The downside to your approach comes if you add another Shape - you end up having to change this code. The other approach is to add a method, say userSelected, to your Shape class and have each subclass override this method to do whatever is appropriate for the kind of shape they represent.
In this other approach your loop becomes:
for(Shape *shape in shapeManager)
   [shape userSelected];

And, for example, Circle gains a method:
@implementation Circle

// override Shape's userSelected and do what a circle needs to do
- (void) userSelected
{
   ...
}

Which approach you choose is up to you, there is no right answer per se, but object-oriented style usually favours the latter.
Comment Followup
To go from a child to a parent you do not need a cast, but can include one - this is a fundamental plank of inheritance-based object-oriented languages like Obj-C.
Going the other way, from parent to child, in Obj-C (a) requires a cast and (b) should be protected by a check - both because you don't know which, if any, of the children you have. In Obj-C (a) just tells the compiler you think you know and it should trust you, (b) is you checking to make sure!
You do (b) with [<obj> isKindOfClass:[<classname> class] which tests if <obj> is of type <classname> or any of its children; or you can use isMemberOfClass which tests if <obj> is of type <classname> but not any of its children. The former is more common to allow for easy expansion (e.g. you may start off with Rectangle being a Shape and later introduce Square being a Rectangle; a test for isMemberOfClass:[Rectangle class] would be YES for both Rectangle and Square while isKindOfClass:[Rectangle class] is only YES for Rectangle).
Explicit testing is commonly not required as method dispatch often subsumes it - as in [shape userSelected] above which will call the appropriate implementation of userSelected based on the actual type of shape at runtime. When explicit testing is required using tests and casts is the way to do it.
And yes, collections of mixed type are common, indeed they are another of the planks of inheritance-based object-oriented languages like Obj-C.
[Note: What Obj-C lacks which a number of other languages have is a way to limit what a collection may contain. E.g. an NSMutableArray can contain any object, while in your case it might be beneficial to be able to say NSMutableArray of Shape to limit it to just Shape and its subclasses. C#, Ada, and even C++ (in as much as it enforces anything) all provide this. If you need to you can do it yourself in Obj-C, see this answer.]
Comment: Thank you for your comments on the practice in general. Could you comment on the casting of objects to different classes? I'm having trouble finding any documentation on it.  Can you always simply cast an object back and forth to parent/child classes via the argument type? Is this a common way to manage many objects of different classes that are all derived from the same parent class?


find small occurences of a substring in a string

Question: I'm trying to parse some mathematical expressions with re (parenthesis content).
I've tried this :
>>> re.compile("\(.*\)").findall("(1 + 2) + (3 + 4)")
['(1 + 2) + (3 + 4)']

But I find only the biggest occurence, that include the content between the last and first parenthesis. But I would like to get only the smallest.
How could I achieve this?
>>> re.compile(<expr>).findall("(1 + 2) + (3 + 4)")
['(1 + 2)', '(3 + 4')]

I've tried to replace <expr> with "\((?![\(\)])+\)" (to exclude occurences with parenthesis within parenthesis) but it doesn't seem to work.
Comment: make it lazy :- `\(.*?\)`
Comment: And/Or change `.*` to `[^)]*` - `\([^)]*\)`.
Comment: `.*?` is lazy..it tries to match as little as possible till the condition is met..`.*` is greedy..it tries to match as much as possible
Comment: put your input and regex on https://regex101.com/
and click on regex debugger on left side..you will understand it
Comment: @rock321987 Your suggestion works, but what's the difference between `.*?` and `.*`? (Doesn't `?` mean "0 or 1 occurence of "?)
Comment: Ok, this answers my question. Thank for your help and the link. :)
Answer: Instead of matching everything with .*, exclude from that match the closing parentheses character:
>>> re.compile("\([^)]*\)").findall("(1 + 2) + (3 + 4)")
['(1 + 2)', '(3 + 4)']

See I am using
[^)]*

instead of
.*

Comment: Does not work for `"(1 * (2 + 3) * 4)"`. Better use `\([^()]*\)`
Comment: @tobias_k Nesting seems out of the scope of the OP's question.
Comment: @tobias_k true. I assume, as the OP is doing in the example, simple operations without nested parentheses.
Comment: @ClasG Who knows? But you can just as well make it so that it works with nested parens, too.
Comment: @tobias_k ClasG is right :  I won't need to use it for nested expressions (I should have mentioned it, my bad), but thank you for the suggestion!
Comment: @tobias_k Well... It depends very much on what it's for. Because complexity rises immensely...


constrained least squares by fixed ratio in the coefficients

Question: For multiple least squares linear regression, can we actually specify a ratio between the coefficients as the prior?
For example, for following linear model:
$y = b_1*x_1 + b_2*x_2 + b_3*x_3$
,can we specify $b1:b2:b3 = 1:2:3$?
Conditions:

We don't know what exactly $b_1, b_2, b_3$ are, we only know they are expected to be proportional to each other.
They are not exactly proportional, which means we cannot reduce it to univariate regression problem: $y = b_1*(x_1+2*x_2+3*x_3)$. The ratio between the effects are prior expectations, we want data can help adjust specific values for the coefficients.
Answer: I variant of your question is answered here: Linear model with constraints on coefficients in terms of ratios, but your question have a Bayesian twist.
First you will need some prior on $b_1$ (maybe a weak prior), then you write
$b_2 = \gamma_2 b_1, b_3=\gamma_3 b_1$ and now you need a prior on $\gamma_2$ with prior expectation 2 and (maybe a small) variance, likewise for $\gamma_3$, but now with prior expectation 3.
It shouldn't be difficult to program such a model in bugs or stan.
Comment: Thanks a lot! Kjetlil. So for the prior on $b_1$, I'm think about using one round of univariate regression first, like: $y = b_1(x_1+2*x_2+3*x_3)$ to calibrate $b_1$ as the prior you mentioned. And then use this prior on $b_1$ to do the following multiple regression using MCMC. Is this something sound reasonable? Also can you please point me some specific parts of bugs/stan that I should look at to implement? I'm more familiar with R. are there something related too? Thanks.


number of bits in an RGB image

Question: Im chanced upon this statement while studying the allocation of RAM in embedded device.
Basically suppose we have an image sensor that uses RGB 5-6-5 format. It captures an image size of 320x240. The author proceeds to use
"There are two 150-KB data buffers that contain the raw data from the image sensor (320x240 in the
RGB 5-6-5 format). "
Does anyone know how is two 150KB data buffers enough to store the raw image? How can i calculate the image bits?
I tried calculating
( 2^5 * 2^6 * 2^5 * 320 * 240 ) * 0.000125 = 629145.6 // in KB.
Comment: You are calculating all possible different image you can get
Comment: Can you explain your calculation?  It is bizarre to say the least.  16 bits per pixel x 230 x 320 pixels is 1228800 bits, 153600 bytes or exactly 150 kibibyte. This is an off-topic question in SO - it being about your understanding of bitmaps and arithmetic rather than code
Comment: Thank you for all your answers, definitely have to work on these foundation properly before proceeding. (:
Answer: You should look closer at the definition of the RGB 5:6:5 format. Each color takes up 2 bytes (5 bits for red, 6 bits for green and 5 bits for blue; adding up to 16 bits == 2 bytes), so a raw 320x240 picture takes 320 * 240 * 2 bytes, i.e. 153600 bytes or 150 KB.
Comment: I see, that makes perfect sense, each pixel has RGB components which is a summates to 16 bits. Thank you!

number of bits in an RGB image


How to randomly generate a positive semidefinite matrix subject to Loewner constraint?

Question: For real, symmetric, positive semidefinite matrices $A$ and $B$, let $\leq_L$ denote the Loewner partial order: $A \leq_L B$ iff $B-A$ is positive semidefinite.  Suppose $A$ and $B$ are fixed PSD matrices. Is there a method to randomly generate PSD matrices from the region $\{X | A \leq_L X \leq_L B\}$? Better yet, is there a way to uniformly sample matrices from this region?
Answer: Let $\mathbb S_n$ be the set of $n \times n$ symmetric matrices. Given positive semidefinite matrices $\mathrm A, \mathrm B \in \mathbb S_n$, the following (convex) set
$$\{ \mathrm X \in \mathbb S_n \mid \mathrm A \preceq \mathrm X \preceq \mathrm B \}$$
is a spectrahedron. To sample from spectrahedra, take a look at Narayanan's paper [0] and the references therein.

[0] Hariharan Narayanan, Randomized Interior Point methods for Sampling and Optimization, arXiv:0911.3950.


Design pattern for converting one model to another

Question: I am writing a library in java and I need to convert (map) one model to another and vice versa. What I did was implementing an abstract converter class with 2 generic types, containing convertTo and convertFrom methods, and extended my converters from it.
public abstract class TypeConverter<MyType, OtherLibType> {
    private final Function<MyType, OtherLibType> fromMyType;
    private final Function<OtherLibType, MyType> fromOtherLibType;

    public TypeConverter(final Function<MyType, OtherLibType> fromMyType,
                         final Function<OtherLibType, MyType> fromOtherLibType
    ) {
        this.fromMyType = fromMyType;
        this.fromOtherLibType = fromOtherLibType;
    }

    public final OtherLibType convertFromMyType(final MyType myType) {
        return fromMyType.apply(myType);
    }

    public final MyType convertFromJspritType(final OtherLibType otherLibType) {
        return fromOtherLibType.apply(otherLibType);
    }

}

But for specific implementations I also may need other objects for converting and I don't know what is the best practice to implement such things. I thought about adapter and facade but they don't seem to match my requirements. Is there a design pattern that I could use for this? Thank you in advance.
Comment: I think you should really declare this as an interface `Converter`. It's also not clear to me why it's abstract since it seems to do all it's supposed to, given it has the two functions, so it should just straighforward implement that interface.
Comment: Looks like you might be trying to do the same thing as [MapStruct](https://mapstruct.org/).
Answer: I think this should be an interface like
interface Converter<T, R> {
 R convertTo(T source, R target);
 T convertFrom(R source, T target);
}

Your abstract class would not need to be abstract and straight implement this interface by calling the Functions.
Then you can have a Wrapper that also implements that interface and delegates its called to the wrapped implementations.
class ConverterWrapper<T, I, R> implements Converter<T, R> {
 private Converter<T, I> toIntermediate;
 private Converter toResult;

 // add trivial constructor to initialize the fields

 public R convertTo(T source) {
  I intermediate = toIntermediate.convertTo(source);
  return toResult.convert(intermediate);
 }
 public T convertFrom(R source) {
  I intermediate = toResult.convertFrom(source);
  return toIntermediate.convertFrom(intermediate);
 }
}

Comment: thank you ! but what about objects that I need to use in conversions, how can i pass these values from outside?


What is the amount of different four-digit numbers that can be created from the digits $0, 1, 2, 3, 4$ and $5$?

Question:
What is the amount of different four-digit numbers that can be created from the digits $0, 1, 2, 3, 4$ and $5$?

The solution is $431,$ but I have no idea how this solution was found. How can I solve this problem?
Comment: Then the answer given is wrong. There's also a typo in the correct answer that I gave: it should be $5\cdot6^3=1080$. There are $5$ choices for the first digit, since it can't be $0$, and there are $6$ choices for each of the remaining $3$ digits.
Comment: Are you sure that you've stated the problem correctly? Because the answer to the problem that you've stated is $5\cdot4^3=1080$, not $431$.
Comment: @ yeas I it's stated correct
Comment: Alternatively, if digits cannot be repeated, there are $5\times 5 \times 4 \times 3 = 300$ possibilities
Answer: As stated in some of the comments, the problem is in the description of the question. We can distinguish the following cases:

Using the digits to form a four-digit number. The first digit cannot equal $0,$ while all digits can be used for the second, third and fourth digit. As such, the number of possibilities equals: $$5 \cdot 6^3 = 1080$$
Using the digits to form a number which contains four unique digits. The first digit cannot equal $0,$ while the second digit cannot equal the first, the third digit cannot equal the first or the second and the fourth digit cannot equal the first, the second or the third. As such, the number of possibilities equals: $$5 \cdot 5 \cdot 4 \cdot 3 = 300$$
Using the digits to form a number which contains at most four unique digits. We can distinguish four cases for the number of digits, and the number of possibilities thus equals: $$5 \cdot 5 \cdot 4 \cdot 3 + 5 \cdot 5 \cdot 4 + 5 \cdot 5 + 6 = 431$$

The latter scenario is the one considered by the authors, although the original question was badly posed. It should in fact have read:

What is the amount of numbers that can be created from the digits $0, 1, 2, 3, 4$ and $5,$ if the number cannot contain more than four digits and every digit can be used at most once?