Insert an element in sorted and rotated list

Question: A list of sorted and rotated element is given. Elements are either sorted in ascending or descending order. For example - I've list of sorted elements as follows
10,12,14,16,18,20,51,53,54,59

Now this list is rotated by X number of times and then it looks as follows.
51,53,54,59,10,12,14,16,18,20

If you want to insert an element in this list what would be the most efficient method to do it.
For element to be inserted is 13, If list is traversed in a linear fashion, false insertion may happen between 59 and 10.
I'm not expecting any code, rather discussion of algorithm is what I'm looking forward to.
Value 21 can be inserted as either first /last element. Account for boundary condition such as - to be inserted element, the first and last element are of same value.
Comment: Is it a *linked list* (where random access is impossible) or an *array* (where random access is possible)?
Answer: This can be solved in log(N) time. In short:

Use binary search to find the biggest / smallest element of the list. This takes O(logN). Implementation is easy just compare the element you are looking at with the first element of the list.
Use binary search to insert the new element, using only the necessary part of the list. This takes O(logN) as well.

More on point 1:
Say you need to find the biggest element in 51,53,54,59,10,12,14,16,18,20.
First you pick the middle element (say it would be 12). 12 is smaller than 51, therefore the biggest element is on the left from 12. You split the interval in half, and get 54. 54 is greater than 51, therefore the biggest element is between 54 and 12. And so on
Comment: Please explain how to get `59` from the list `51,53,54,59,10,12,14,16,18,20` with binary search.
Comment: You need to assume that all elements are distinct or something similar; it's sort of difficult to find the one in an input consisting of n-1 zeros and 1 one.
Comment: Why would it take O(log N) time to do the second insertion? What if the insertion has to be at the start of the array, then you'd have to shift every element over, taking N time
Comment: You are right -- in my solution, I actually was solving the part to find the element (or the place to insert the element). If inserting takes O(N), then, of course, this problem can not be solved faster than O(N), and O(N) solution is trivial.
Answer: The real question of course, is about the data-structure and efficiency required.

What is the ordering (ascending / descending)
Where is the "minimum"

Note that you need to know about the ordering, otherwise 4,2 could be interpreted either as:

2,4 ascending and rotated once
4,2 descending

From 3 elements, you can guess 4,2,3 is ascending and rotated once because of the way the maximum and minimum values are set together.
Indeed, you should probably use a Circular structure, which would make rotation easy. Then you can maintain an Accessor to this structure:

Which points to the minimum
Which points to the current beginning

Given the minimum, it's easy (one comparison to its right-hand neighbor) to know what the ordering is. And from that point on, insertion in the Circular structure is easy too.
Answer: Keep track of the minimum element during the X 'rotations'. Then use binary search in the relevant half.
Comment: The problem assumes you are NOT the person who did the rotation :)
Comment: @Olexiy: True. But often treating the cause is better than treating the symptoms ;)
Answer: Assuming that your list allows efficient random access this is a binary search with a offset. If you've found the right index you move the element 1 index position to the left. This has complexity O(log n) for the search and O(n) for the list copy operation.
Answer: One the solution I came up with,
1.Check for boundary conditions such as

If new element is b/w first and last element OR vice versa
If new element is equal to either first OR last element

If any of the above conditions are met insert element at the the first place.
2.Take the middle element

check if new element == Middle element - insert new element at this position
Check Is new element is b/w Middle element and Right most OR it is b/w Left most and Right most element.

3.Compute number of element b/w  Left-Middle OR Middle-Right based on above conditions.

If number of elements are <= 2, insert new element b/w Left-Middle OR Right-Middle
Otherwise compute new  Left, Middle and Right element and perform step 2.


Service continues to act as shared when shared is set to false

Question: According to Symfony docs, doing shared: false on a service should mean that each time you call a service, you get a new instance. However, this doesn't seem to work for me. I am using Drupal 9 which runs on Symfony 4.4.
My services.yml :
services:
  my_module.arbitrary_data:
    class: Drupal\my_module\Services\ArbitraryData
    arguments: ['@another_module.contextual_uid']
    shared: false

https://symfony.com/doc/4.4/service_container/shared.html
I've also tried the deprecated scope: prototype and scope: request methods to no avail. If I load a page, my services outputs unchanged data from the last time the page was loaded until I clear cache.
Regardless of doing this, the services fail to run after the first page load after clearing cache and just proceed to output unchanged data every time. This feels like "unwanted caching".
Edit 11/15 3:47PM
The render array from the plugin using the service, as requested:
$service = \Drupal::service('my_module.arbitrary_data');
$data = $service->get('acr');
$data = array_shift($data);

return [
  '#markup' => $data['value'],
];

Comment: I agree that according to https://www.drupal.org/docs/drupal-apis/services-and-dependency-injection/structure-of-a-service-file this is supposed to be supported. I don't, however, understand the symptoms you described in the way you described them.
Comment: Where are you invoking the service? Inside a hook which is cached maybe? What does the cache look like on the render array which is outputting the data?
Comment: Setting a service to not shared only has an effect on the service properties in memory, not the Drupal cache data stored in the database.
Comment: @Clive It's being used in a controller that is not being cached, in fact the route that calls the controller is set to no_cache.
Comment: @cilefen Imagine you have a custom service which returns the current time. On the first request, the service returns the time. On the second request, the same time as the first request is returned. I have a feeling that there is a cache context that needs to be changed somewhere, I just don't know where or what.
Comment: Could you post a copy of the render array being returned from the controller in the question (or whatever other method you're using to return the content). Your problem isn't related to the `shared` parameter by the way, as 4uk4 mentioned
Comment: @Clive I have added it to the original post for readability. The controller is part of a plugin, if that matters.
Answer: Thanks to user @Clive 's questioning, it led me to assess this issue as a Plugin problem rather than a Service problem. Since the service is being used in a plugin, and the plugin was being cached (by default), my output was not changing.
Implementing cache max-age into the plugin's render array fixed this issue.
return [
  '#markup' => $data['value'],
  '#cache' => [
    'max-age' => 0,
  ],
];


makefile for CGAL (libcgal8)

Question: I don't know why, but at each new version of CGAL, the procedure to compile completely changes. So, it's not even possible to recompile old piece of code (6 months old) because it doesn't work like that anymore.
I'm frankly very tired of redoing all the makefile of my projects that use CGAL each time. This time, for libcgal8, I don't find any simple substitute. Here's the makefile I was normally using:
ifndef CGAL_MAKEFILE
CGAL_MAKEFILE = /usr/local/cgal/share/cgal/cgal.mk
endif
include $(CGAL_MAKEFILE)

LIBPATH = \
          $(CGAL_LIBPATH)

LDFLAGS = \
          $(LONG_NAME_PROBLEM_LDFLAGS) \
          $(CGAL_LDFLAGS)

COMP=-frounding-math -fopenmp -std=c++0x -l json -L$(LIBPATH) $(LDFLAGS)
EXEC=../crender

all: main.o
    g++ -fPIC main.o $(EXEC) $(COMP)

main.o: main.cpp ../common/common.hpp
    g++ -c main.cpp $(COMP) -o main.o

So, what do I have to change to make it work again ? If possible, a solution that will survive to the future changes of CGAL.
If it can help, here's the kind of error that I get:

In function CGAL::Gmpq_rep::Gmpq_rep()':
      main.cpp:(.text._ZN4CGAL8Gmpq_repC2Ev[_ZN4CGAL8Gmpq_repC5Ev]+0x14): undefined reference to__gmpq_init'

And I get these kind of errors for other functions like "__gmpg_add", "__gmpq_sub" and "__gmpq_mul."
SOLUTION:
You need to add "-lgmp" in the compilation instruction. It's sad that it's not done by default by the makefile provided by CGAL!
Comment: Since January 2009 (release 3.4), CGAL is using cmake as build system. Since then, all include/link compiler flags are provided through the cmake mechanism (CGALConfig.cmake).
Comment: As mentioned above, now CGAL uses cmake as build system. While compiling CGAL example with cmake, I encountered similar problem. Solution is to add and link GMP library. Here is how its done for cmake: http://stackoverflow.com/questions/6975718/cmake-basic-library-linking-problem/6980807#6980807
Answer: (Answered in the comments and in an Edit. See Question with no answers, but issue solved in the comments (or extended in chat) )
The OP wrote:

You need to add "-lgmp" in the compilation instruction. It's sad that it's not done by default by the makefile provided by CGAL!

@sloriot Added:

Since January 2009 (release 3.4), CGAL is using cmake as build system. Since then, all include/link compiler flags are provided through the cmake mechanism (CGALConfig.cmake).
As mentioned above, now CGAL uses cmake as build system. While compiling CGAL example with cmake, I encountered similar problem. Solution is to add and link GMP library. Here is how its done for cmake: Cmake basic library linking problem
Answer: This is my makefile for linux and mac os x (no using cmake):
CPP        := g++
OPCJE      := -W -Wall -pedantic -O0 -Wno-c++11-extensions
BIBLIOTEKI := -lboost_math_c99 -lboost_thread -lm -lCGAL -lmpfr -lgmp
PISZ := echo -e
UNAME_S := $(shell uname -s)

on Mac os X some library are different name (brew install)
ifeq ($(UNAME_S),Darwin)
 BIBLIOTEKI = -lboost_math_c99 -lboost_thread-mt -lm -lcgal -lmpfr -lgmp
 PISZ = echo
endif

all source
    SRC = $(wildcard *.cpp)
    OBJ = $(addsuffix .o, $(basename $(SRC)))
BIN_DIR  = ./bin
W_ZRODLA = $(wildcard *.cpp)
PROGRAMY = ${W_ZRODLA:%.cpp=$(BIN_DIR)/%}

$(BIN_DIR)/%: %.cpp
    @mkdir -p ./bin
    $(CPP) $(OPCJE) $< -o $@ $(BIBLIOTEKI)

wszystkie: $(PROGRAMY)
    @echo

clean:
    rm -f ./bin/*

mem: 01
    valgrind -v --tool=memcheck --leak-check=full ./01

makefile for CGAL (libcgal8)


Practice and performance

Question: This question is going to take some time to explain (at least for me), so pardon the length ahead of time.  Also note that it seem like it elicits opinions but this is not the intent.  I'm interested in people's opinions on what works for them but I'm sure there is an objective perspective based on research in cognitive neuroscience and am aware of some musicians taking advantage of this.
The nature of the question applies more to classical performance rather than improv (at least that is what I'm interested in).
So here is some background to illustrate where I'm coming from (what's on my mind).  I have always found it easier to learn a song and commit it to memory before attempting to include all the expressive markings indicated in the sheet music, such as dynamics, accents, etc.  It seems reasonable to me and has "worked" in the sense that eventually I get to a performance level, i.e. the piece is memorized, clean, can be played expressively, and I can even improvise by playing with the basic components of the piece.  This approach can be described loosely as 'Figure out what to play then how to play it', or 'Get the melody correct, then the directions'.  I even have memory of past instructors guiding me in that direction but some of that could be me filling in memories.  Back in high school I had a violin teacher who insisted on playing every note the very first time exactly as it is indicated, with accents, vibrato, dynamics, expressiveness.  All these dimensions at the very first effort to play.  He promoted the idea that if you start perfectly there will be no real practice necessary (my embellishment).  Really what I think he meant is that practice time would be minimized.  I'm not talking about a hour on one given day, but the months that go into getting ready for a solo performance.  At the time this seemed impossible to me and a little obsessive.
Later in life I began to read about how "muscle memory" works and how we train ourselves by repetition.  Clearly no one wants to repeat a mistake or a bad habit, that is counterproductive.  But is it not the case that by practicing to play a group of notes in tune without proper attention to accents and dynamics you've made a type of mistake?  Is doing things this way (learn the what then the how) a set up to only have to retrain yourself?
I follow my old violin teacher's advice w/r to playing fast.  In fact all my teachers promoted the idea that to play fast you need to first play perfectly.  But I usually equate this to perfect placement of the fingers in the instrument and perfect timing of the various body parts involved.  Again, I take the position that it isn't much effort to add dynamics and emotion after the piece is completely memorized and at tempo.  But I'm not completely sure that's true.
Anyone who has mastered an instrument knows it takes effort to learn each new technique, to learn the correct amount of force or pressure required to create different tones and volumes, to learn vibrato and tremolo.  So is it even reasonable to expect anyone to play all aspects of a piece from the first attempt at the first note?  Or is this the secret to expert performance?
Based on the above my questions are:

What approach do people take for working a piece of music up to solo performance quality?
Does anyone use the approach I attribute to my violin teacher?
Does anyone know of a scientifically proven superior approach to practice based on neuroscience?
Comment: The answers for the questions you asked are basicaly the "secrets" that every high performance musician wants to know. Someone could write a book about this subject. In fact, several people did and there is plenty material and lots of point of views. I could cite, for example: "Technique, Mechanism, Learning" by Eduardo Fernández, "The Musician's Way" by Gerald Klickstein or even "The Inner Game of Music" by Barry Green and W. Timothy Gallwey.
Comment: i don't see how you can play something at performance level if you can't even play the notes. need to learn the piece in order..Notes, rhythm/speed, feeling (dynamics, accents, etc). the easier the piece compared to your ability the easier it is to play more aspects of the piece correctly off the bat. comment and not an answer because i can't speak to #3.
Comment: We may be talking past each other, or maybe I didn't say things correctly.  Why not play just the first note as a piece?
Comment: What do you mean "play just the first note as a piece"?
Comment: You could pare this down to something as short as: "Is it better to learn the notes and chords in the right order and then learn the accents and dynamics and timing, or should all the elements of every note be learned right from the start?"
Comment: I believe @ggcg means it's possible to play the very first note with the correct dynamics, accenting, etc. So can the second note be played with correct dynamics, accenting, etc. If I understand correctly, what happens is one sacrifices the speed of play in order to achieve these other qualities. That's the point of training our muscle/kinesthetic memory: we learn the hand movements, muscle contractions, etc. correctly, and then we simply speed them up. Have I understood the idea, ggcg?
Comment: Thank you @jdjazz, that is what I was getting at, perhaps poorly.  But I think some would argue that if you play note one, pause, then play just note one and two you can get all aspects expressed including speed.
Comment: @TiagoPC, I have read some but will check out those you cited as well.  Thanks.
Answer: This may help one aspect: repetition of success.
As a teacher put it quite succinctly during a recent rehearsal, "too many students play a passage 10 times wrong, then get it right, declare success, and move on."  That won't work.  As Todd W. discussed, muscle/neuro training requires repetition of the right way .  The moment you achieve success with a passage, or a measure, or whatever,  repeat until you can get it right X times in a row ( 5 < X < 15 ) .
Comment: That makes sense.  I have heard that from all my teachers.  In addition, when plying anything the first time your body doesn't know what is right or wrong so the very first thing you attempt is memorized as a pattern (for better or worse).
Answer: The branch of science you actually want to ask about is cognitive research, which is about how humans think and learn. Neuroscience is more about brain and nerve function and chemistry below the level of conscious thought.
Cognitive research tells us several things that are relevant to learning music:

We have to learn fundamentals before we can learn more advanced concepts. As musicians, this confirms what we sort of know already: we have to master the basic techniques, finger positions, etc., before we can more easily learn long sequences of precise motions that create a piece of music.
Part of human learning involves chunking, which is when our minds assemble simpler bits of information into related chunks of information. For example, we might start off playing a chord by placing each finger individually one at a time, but in time, we see the chord notated on the page and our fingers can very quickly form the shape needed to play the chord. Our minds have chunked those different finger positions together into one overall hand position. Chunking continues to more and more difficult concepts.
We retain information learned best when we are experiencing a strong emotion or stress when presented with the information. That suggests that the more we can feel the emotion of a piece, the better we might remember it. At the same time, we might not have to feel the piece itself. If we set out to learn music that reminds us of a long lost loved one, we might be more likely to learn it faster and remember it better.

My take on this information and your question is that there isn't one right way to learn a piece. It may help to have a strategy and awareness of what fundamentals you need to master and how you want to assemble your chunks.
I learn pieces the way you do: I want to learn the notes in order with the timing and then I feel like the expression and emphasis and accents come easily. One reason why that makes sense to me is because the note order is more fixed and rigid. If I choose to play a different note, it's a different piece. If I play some accents more strongly than others, that is more my interpretation. Likewise with tempo and rubato. Therefore, I personally disagree with teachers who say you should perfectly recreate all of the markings on a score every time. A computer can do that.
Suggested reading: Why Don't Students Like School?
Comment: +1, the point about chunking is really fascinating. This makes me wonder if there are two simultaneous learning processes that occur as we learn a new piece: our brain learns the shapes of chords, melodic lines, etc. and our fingers learn the muscle patterns associated with playing the song. What are your thoughts on this?
Comment: I didn't mean to confuse cognition with neurology but that was not what I meant.  I was referring to a situation where the fundamentals were known and a new piece was being learnt.  I do not believe you addressed my question at all.  It is not about "learning" an instrument but about learning to play a piece given that you know how to play the instrument.  But I am grateful for your last paragraph, the personal experience.
Comment: Also, I am not sure that cognition and neurology are unrelated.  If the two branches of science  define them differently then they are, but everything you describe is due to neurological processes.
Comment: @ggcg The bullet about chunking would seem to directly address your question, in my view. I think you're asking about which way to learn a piece. No matter how you learn a piece, you're chunking, so the question is, which kinds of chunks do you want to form. Also my third bullet is about learning a piece. No part of my answer was meant to be about learning an instrument - I understand your question is about learning a piece. Many times when I approach a new piece I discover there is a technique I will need to learn to be able to play it, hence the first bullet.
Comment: @ggcg I'll leave it up to you if you want to look at the Wikipedia pages or other sources for the difference between cognitive science and neurology. I only thought I would point that out in case you wanted to do more research about how humans learn since you specifically asked for an answer based on science. The branch of science that includes studies of how humans learn is most commonly called "cognitive science".
Comment: @ToddWilcox Obviously a human will inject their own feel but that does not invalidate the markings.  In the context of classical performance these are important.
Answer: This is just personal experience, but when I am setting out to learn a piece thoroughly, I focus on notes/rhythms/fingerings first. I want to get that all set before I work on interpretive stuff like dynamics, phrasing, articulation and such. That being said, I start off slowly in both categories. Even after I have the notes/rhythms/fingerings down solid and up to a good tempo, when it is time to add the interpretive stuff, I go back to the beginning and play slowly again. I want to make sure that if practice these correctly from the beginning, and it takes some slow, conscious thought to add these to the notes I already learned. I cannot add these to the correct notes "at tempo" and expect to get it right.
If I am sight-reading (which I am quite good at), I try to process as much as I can of all of it the first time. But I also know I am not going to get it 100% correct, even if mostly correct.

Practice and performance


Is there a name for a chord with a major 3 and b5? When can it be used?

Question: I think most of the 3 notes played at the beginning of Ocarina of Time's Lost Woods theme for reference.
In C, these 4 are considered triads:
<code>Major:      C E G
Minor:      C Eb G
Diminished: C Eb Gb
Augmented:  C E G#
</code>
The other ways in which you can alter the 3rd and 5th are to lower the 3rd and raise the 5th, which is the same as a major triad in 1st inversion. However, I can't figure out what lowering just the 5th does. It seems to create a major second interval (enharmonically diminished 3rd) and doesn't fit into any inversion of another chord.
Is there a special name for this chord, when would it be appropriate to use it?
Comment: A lot of overlap here: https://music.stackexchange.com/questions/66363/why-is-a-5-chord-not-a-triad
Comment: I would say in some cases you just want it to be b5 (some specific music situations), so if you don't want 5th to sound and specifically want b5 this kind of triad is possible.
Comment: Seems pretty clear: what is the triad R M3 b5 called? But is that the same as R M3 #4..? OP - help!
Answer: The other two answers ably address the question as written, but having listened to the piece itself, someone should address that that isn't the chord that's being played.
In the actual piece, it's just a major triad with a ♭5 (actually ♯4) non-chord tone.
Remember that not every simultaneity or grouping of notes creates a chord; there are often outside pitches used to embellish said chord, and that's what's happening here.
Comment: Since most chords are built on odd numbers, why is #4 preferrable to b5? Or is it jazz v. blues?
Comment: I don't fully agree with the "non-chord tone" thing. The melody quite clearly outlines an F-A-B chord, especially if you play just the flute-like melody alone, without the backing instruments. It could even be said that the whole melody line sounds like the notes of a G13/F chord. What is expected of chord symbols here: a theory-hygienic harmonic analysis of everything that's sounding, or just practical instructions for accompaniment. (a rhetorical question)
Comment: @Tim and Piiperi, for the `B` natural, the #4 makes clear that tone is a _melodic_ non-chord tone. If the `B` was called b5, then it's confused what the 5th scale degree is. Do we really want to say there is a b5 rather than a Lydian tinged melody over plain F and C major triads? The important point is the OP is mistaking a melodic non-chord tone for a chord tone. A sensible lead sheet would show an 'F' chord symbol and a melody with a 'B' natural.
Comment: https://www.youtube.com/watch?v=vgjvyQ1slEc
Comment: If you followed the same attitude to non-chord tones as chord tones, the 3 bar would be `CMaj7`. The seems no point to complex symbols when a notated melody makes it obvious.
Answer: In jazz C-E-Gb is the basis of what's called a "flat 5" chord, a common type of altered chord.
You'll normally find it with a seventh, either as a dominant chord (C-E-Gb-Bb = C7b5) or as a major 7th (C-E-Gb-B = Cmaj7b5).
Regarding your comment that it doesn't fit any inversion or other chords, I'd say that's not completely so. Especially if you meant that that the flat 5 note doesn't belong to the parent major scale, we can say that it does belong to a Lydian major scale.
For example, on a C major scale, you can build an F major chord as F-A-C, and if you lower the 5th you get a F-A-Cb i.e. F-A-B which is your chord.
Using the C-E-Gb example, written as C-E-F#, that's a chord built on the G major scale.
So one way to think of that chord is as a major chord with a #11, which gives it a Lydyan mode flavour. (The main flavour of the Lydian scale being the #4 instead of perfect 4th)
OK, now I actually listened to the tune you mentioned -- the first three notes are actually F-A-B, and the effect is to start off the melody with a strong Lydian flavour (F Lydian).
Comment: Doesn't a #11 presume there's 1,3,5 there as well, so in key C, there's G and F#?
Comment: Yes, a 5th is presumed, but it can be omitted without losing much. In Jazz at least, roots and 5ths are the least important notes in chords. (Roots are played by the bass, and (perfect) fifths, are implicit and may be omitted, especially if the chord has a lot of other notes). The most important chord notes are the thirds, the sevenths, and other 'color' notes. Hence I suggested above that "one way" of looking at it is a major chord (without the 5th, easily implied) with a #11. And listening to the Lydian flavour of the actual music, kind of supports that, at least to my ear...
Answer: C E Gb could be the a minor dim7 without root of A.
If I play this I'd interpret the triad C E Gb as the upper notes of a scondary dominant  of D79 (without root and 5th)
the enharmonic tone of Gb = F# would be a be a secondary VII7 (without the 5th.) leading to G or (dm7 G)
listen to  the variation  C / C+5 / F / Fm / C /Fm#7b5/  Dm / G
Answer: On the assumption you really mean C E G♭, then it's F♯7♭5, (G♭7♭5 sounds rubbish!), alternatively called Am6, obviously missing a note from each, but nevertheless sounding pretty authentic. It could also be part of D9, but would depend on what key it's found in, and where.
Wish the ♯ sign would come up bold..!


Tree traversing doesn't print desired solution

Question: (java)
I have class called Node, which has following fields:

value (integer)
connectedNodes (array of Node objects, always has same size = 2)
combination (object of Combination class)

Combination class has one field called messageContext, let's just say that it's a message which needs to be shown on the screen when something happens (described later).
Also, we have one Tree object, which has only one field: root (Node object)
Now, let's say that we have one String called combinationStr = "1121". Now, we use Tree's method called addCombination:
public void addCombination(Combination finalCombination, Node current, String combination, int counter) {

    if(counter==combination.length()) {
        return;
    }

    int value = combination.charAt(counter)-48;
    if(current.connectedNodes[value-1]==null) {
        current.connectedNodes[value-1] = new Node(value);
    }
    if(counter==combination.length()-1) {
        current.combination = finalCombination;
        return;
    }
    addCombination(finalCombination,current.connectedNodes[value-1],combination,counter+1);

}

finalCombination object is an object that is going to be assigned to the last Node's combination field, added to the Tree for one combinationStr. So, we use this function to create the Tree-like structure that has path: -1 (root) -> 1 -> 1 -> 2 -> 1
When we come to the last one, traversing the Tree, we should see message appear. This is the messageContext of finalCombination.
Okay so, now let's use while(true) loop that will let us input a number, which will be like a path-chooser. If we input 1, we will go to node 1 and have other options to choose.
While loop looks like this:
    Scanner scanner = new Scanner(System.in);
    Node currentNode = tree.root;
    while(true) {
        for(Node node: currentNode.connectedNodes) {
            if(node!=null) {
                System.out.print(node.value + " ");
                continue;
            }
            System.out.print("nullnode ");
        }
        System.out.println("");
        if(currentNode.combination!=null) {
            System.out.println(currentNode.combination.messageContext);
        }
        if(currentNode.connectedNodes[0]==null && currentNode.connectedNodes[1]==null) {
            currentNode = tree.root;
            System.out.println("root");
        }
        int x = scanner.nextInt();
        currentNode = tree.takeStep(currentNode,x);
    }

So, what are we doing here is actually printing the value of current Node, then printing values of Node's we can go to. If Node doesn't exist, we print nullnode.
The takeStep() method looks like this:
public Node takeStep(Node current, int value) {
    if(current.connectedNodes[value-1]!=null) {
        return current.connectedNodes[value-1];
    }
    return this.root;
}

It just checks if there is a node we want to go to and returns that node, if it does. If it doesn't exist, it will return us to root.
But, what's the problem with this code ?
Well, look at the whole main class:
    Tree tree = new Tree(new Node(-1));
    String[] combination = {"1121","11","2212"};
    for(String s: combination) {
        Combination tempCombination = new Combination();
        tempCombination.messageContext = s + " ova poruka";
        tree.addCombination(tempCombination,tree.root,s,0);
        tree.traverse(tree.root);
        System.out.println("END");
    }

    Scanner scanner = new Scanner(System.in);
    Node currentNode = tree.root;

    while(true) {
        System.out.println(currentNode.value);
        for(Node node: currentNode.connectedNodes) {
            if(node!=null) {
                System.out.print(node.value + " ");
            }
            else {
                System.out.print("nullnode ");
            }
        }
        int x = scanner.nextInt();
        if(currentNode.combination!=null) {
            System.out.println(currentNode.combination.messageContext);
            if(currentNode.connectedNodes[0]==null && currentNode.connectedNodes[1]==null) {
                currentNode = tree.root;
                break;
            }
        }
        currentNode = tree.takeStep(currentNode,x);
    }

When we enter number x, we will call takeStep and check if that node exists connected to current one. But the problem is: When we input 1, it prints everything normally, when we input 1 again, it prints everything normally, when we input 2, it prints everything normally... but when we input 1 again, it says there are 2 nullnodes, and for some reason it doesn't change to root. Can anyone help me please? Here are the full classes:
NODE:
public class Node {
    int value;
    Node[] connectedNodes = {null,null};
    Combination combination;

    public Node(int value) {
        this.value = value;
        this.combination = null;
    }
}

TREE:
public class Tree {
    Node root;

    public Tree(Node root) {
        this.root = root;
    }

    public void addCombination(Combination finalCombination, Node current, String combination, int counter) {

        if(counter==combination.length()) {
            return;
        }

    int value = combination.charAt(counter)-48;
    if(current.connectedNodes[value-1]==null) {
        current.connectedNodes[value-1] = new Node(value);
    }
    if(counter==combination.length()-1) {
        current.combination = finalCombination;
        return;
    }
    addCombination(finalCombination,current.connectedNodes[value-1],combination,counter+1);

}

public void traverse(Node current) {
    System.out.print(current.value+ " ");
    for(Node node: current.connectedNodes) {
        if(node!=null) {
            traverse(node);
        }
    }
}

public Node takeStep(Node current, int value) {
    if(current.connectedNodes[value-1]!=null) {
        return current.connectedNodes[value-1];
    }
    return this.root;
}}

COMBINATION:
public class Combination {
     String messageContext;
}

Can you please help me ? I just want to reset to root when it hasn't anywhere to go else ? Thank you in advance!
Answer: I ran your code and found out that you are storing the message context in the parent node instead of the actual node which marks the end of the combination. So I changed this piece of code in addCombination.
    public void addCombination(Combination finalCombination, Node current, String combination, int counter) {

    if (counter == combination.length()) {
        //Storing at the original node.
        current.combination = finalCombination;
        return;
    }

    int value = combination.charAt(counter) - 48;
    if (current.connectedNodes[value - 1] == null) {
        current.connectedNodes[value - 1] = new Node(value);
    }
    addCombination(finalCombination, current.connectedNodes[value - 1], combination, counter + 1);

}

And changed following in the main code.
 while (true) {
        System.out.println(currentNode.value);
        //Moved it up now as the node it self has the message context.
        if (currentNode.combination != null) {
            System.out.println(currentNode.combination.messageContext);
            if (currentNode.connectedNodes[0] == null && currentNode.connectedNodes[1] == null) {
                currentNode = tree.root;
                continue;
            }
        }
        for (Node node : currentNode.connectedNodes) {
            if (node != null) {
                System.out.print(node.value + " ");
            } else {
                System.out.print("nullnode ");
            }
        }
        int x = scanner.nextInt();
        currentNode = tree.takeStep(currentNode, x);
    }

Now try the code it is resetting to root as expected.


Regex parsing multiple elements, with the first one being optional

Question: I am trying to integrate my timesheets app with Fogbugz by using a text pattern in the time entry's notes to indicate that work was done on a case.
Scenario A:
If work was done on case#123, the note would be:
[123] Rewrote javascript code.
Desired output: Case: 123 Note: Rewrote javascript code.
Scenario B:
If work was not related to a case, the note would be:
Rewrote javascript code.
Desired output: Case: Null Note: Rewrote javascript code.

To parse the string, I'm using Pentaho Data Integration's Regex Evaluation transformation, but I think the regex would probably be the same regardless of the tool in question.
This is the code that I'm using:
(\[(.*)\])(.*)

For Scenario A, I get:
Ignorable field: [123]
Case: 123
Note: Rewrote javascript code.
Scenario B, I get:
Ignorable field: null
Case: Null
Note: Null
Now to the question (finally!) - is there a way for me to get the note portion to show up if there is no "[##]" pattern showing up?
Answer: You may want to try this:
(\[(.*)\])?\s*(.*)

Comment: That worked! Thanks! Regex has always felt a little like rocket science to me.
Answer: ^\s*(\[[^]]+\])?\s*(.*)

Don't use .* if you don't absolutely, positively want to match everything. What you are trying to match is "everything up to the closing ]", and this should be explicit in the regex.
Explanation:
^          # start-of-string
\s*        # any number of leading white-space (gets ignored)
(          # match group 1
  \[       # literal [
  [^]]+    # anything but ]
  \]       # literal ]
)?         # end match group 1, make optional
\s*        # any number of intermediary white-space (gets ignored, too)
(.*)       # anything else on that line

Answer: That's not strictly a regex problem.  It consists of two parts:  regex matching, and then apply a little logic:
if the [n+] part matched, output "\1 Note" else "Null Note".


ObjectDataSource.Select() not always firing on page postback

Question: I have a form with:

1 text box ("MyTextBox")
3 check boxes ("MyCheckBox1", "MyCheckBox2", "MyCheckBox3")
1 submit button ("MySubmitButton")
1 ObjectDataSource ("MyObjectDataSource")
1 GridView ("MyGridView")

My ObjectDataSource looks like this:
<asp:ObjectDataSource ID="MyObjectDataSource" runat="server"
                          SelectMethod="MySelectMethod"
                          TypeName="MyTypeName">
    <SelectParameters>
        <asp:ControlParameter Name="MyRegularString"
                              Type="String"
                              ControlID="MyTextBox"
                              PropertyName="Text" />

        <asp:Parameter Name="MySpecialString"
                       Type="String" />
    </SelectParameters>
</asp:ObjectDataSource>

The second parameter ("MySpecialString") is filled like this:
Protected Sub MyObjectDataSource_Selecting(...) Handles MyObjectDataSource.Selecting

   Dim MySpecialString As String = "Key1=" & MyCheckBox1.Checked.ToString & ";" & _
                                   "Key2=" & MyCheckBox2.Checked.ToString & ";" & _
                                   "Key3=" & MyCheckBox3.Checked.ToString & ";"

   e.InputParameters.Item("MySpecialString") = MySpecialString

End Sub

Whenever I change the value of MyTextBox and press MySubmitButton, the select method of MyObjectDataSource is invoked and everything works OK.
But if I change the value of any of my check boxes (without changing the value of MyTextBox) and press MySubmitButton, the select method is not invoked, thus the "MyObjectDataSource_Selecting" event doesn't take place and I get the same results as before.
One way I found to work around this was to explicitly invoke MyGridView.DataBind method whenever MySubmitButton was clicked. Is this the best way to handle these type of parameters? What I am afraid is that this may cause the select method to be called twice making the page slower.
Thanks in advance for any help.
CD
Answer: This is what I ended up doing.

Replaced all the asp:ControlParameters with asp:Parameters.
Explicitly invoked MyGridView.DataBind method whenever MySubmitButton was clicked.

I checked and the select method is not invoked twice when doing this.


How to save in a different subfolders the attachments of my users?

Question: I want each user's attachments (they will be school assignments docs, photos, maps) to be saved in user's own subfolder in order to be able to collect them easily and separately.
How would this made possible and what are the best modules to utilize in order to achieve it?
Comment: Can you explain your question further which version of Drupal? and how files are attached , is it using any modules or Drupal FAPI ?
Comment: I am using Drupal 7! Files are attached by using a file field in a special content type called assignment.
Comment: I have posted answer, you can try that method ! for configuration goto "content type" field settings and in the file path put the token value.
Answer: In Drupal 7, the core File module and the Token module (https://drupal.org/project/token) will let you do this.
In the settings for your file field, specify a file directory using a user token. I recommend prefacing the token'd directory with users/ (or something) so that you can easily find all of these files separate from other files on the site.
For example to use the user ID as the directory, set the 'file directory' to
<code>users/[user:uid]
</code>
You can see all the user-related tokens available to you on your site at admin/help/token.
Comment: When you say settings of the file field you mean at the file field of a particular content type. right?
Comment: I get the following error when I try the users/[user:uid] solution. File directory is using the following invalid tokens: [user:uid].
Comment: Install the filefield module..you will get those token available to choose from.
Comment: Well that's embarrassing. 1. Yes, it looks like you are putting the token in the right place. 2. It looks like the file module will support [current-user:uid] but not [user:uid].

n.b. The filefield module is for Drupal 6.
Answer: filefield and Token module can do it, nice and clean.

The File (Field) Paths module extends the default functionality of
  Drupal's core Upload module, the FileField module and many other File
  Upload modules by adding the ability to use node tokens in destination
  paths and filenames.
In simple terms, File (Field) Paths allows you to automatically sort
  and rename your uploaded files using token based replacement patterns
  to maintain a nice clean filesystem.
Comment: Can I use it even if some users already uploaded content?
Comment: nope!  this will be applied only after the settings are submitted.


Flatten inner list in a list of lists

Question: Let's say I have the following lists of objects:
lol = [['When was America discovered by Christopher Colombus?', ['1492', '1510', '1776', '1820'], '1492'], ['What is the name of the school that Harry Potter attends?', ['Hogwarts', 'Gryffindor', 'Voldemort', 'Magic School'], 'Hogwarts'], ['How many colors are there in the common depiction of the rainbow?', ['5', '7', '9', '11'], '7']

I'm trying to flatten the inner list (e.g. remove the brackets).  The result would look like
['When was America discovered by Christopher Colombus?', '1492', '1510', '1776', '1820', '1492']

I have seen general solutions for flattening entire lists such as here:
Flattening a shallow list in Python
But I cannot figure out how to selectively flatten a single list within a larger list of lists.
Answer: I think you mean that you want not just the output you show, but the other two in your sample output as well.  Here's how to do that:
lol = [['When was America discovered by Christopher Colombus?', ['1492', '1510', '1776', '1820'], '1492'], ['What is the name of the school that Harry Potter attends?', ['Hogwarts', 'Gryffindor', 'Voldemort', 'Magic School'], 'Hogwarts'], ['How many colors are there in the common depiction of the rainbow?', ['5', '7', '9', '11'], '7']]

r = []
for x in lol:
    r.append([x[0]] + x[1] + [x[2]])

for rr in r:
    print(rr)

Result:
['When was America discovered by Christopher Colombus?', '1492', '1510', '1776', '1820', '1492']
['What is the name of the school that Harry Potter attends?', 'Hogwarts', 'Gryffindor', 'Voldemort', 'Magic School', 'Hogwarts']
['How many colors are there in the common depiction of the rainbow?', '5', '7', '9', '11', '7']

Answer: If you know how to flatten an entire list, and you want to know how to flatten just the first list, then you aren't really asking how to flatten a list, you are asking how to select the first item in a list, in which the answer is to do sublist=lol[0] and then apply the answers to the other questions to sublist.

Flatten inner list in a list of lists


Should I get better accuracy predicting rare events or their reverse?

Question: I remember whenever one needs to predict rare events (naive bayes classifier or logistic regression) that it is smart to simply predict the reverse of the rare event, which is far more common one can get far higher accuracy results.
I just tried the methods and discovered it actually did not matter at all.
I admit I did some copy-pasting but checked it multiple times and did not see a mistake in my code. It does give slightly different accuracies, so I figure the code must not be pure duplicates.
Here is a quick glance at my code and the data.
<code># A tibble: 574 x 5
   Survived Pclass   Sex   Age  Fare
      <int>  <dbl> <dbl> <dbl> <dbl>
 1        0      3     0    22  7.25
 2        0      3     0    35  8.05
 3        0      3     0    NA  8.46
 4        0      1     0    54 51.9
 5        0      3     0     2 21.1
 6        0      3     0    20  8.05
 7        0      3     0    39 31.3
 8        0      3     1    14  7.85
 9        0      3     0     2 29.1
10        0      3     1    31 18
# … with 564 more rows

# summary
    Survived           Pclass           Sex              Age             Fare
 Min.   :0.00000   Min.   :1.000   Min.   :0.0000   Min.   : 1.00   Min.   :  0.000
 1st Qu.:0.00000   1st Qu.:2.000   1st Qu.:0.0000   1st Qu.:21.00   1st Qu.:  7.859
 Median :0.00000   Median :3.000   Median :0.0000   Median :28.00   Median : 10.500
 Mean   :0.04355   Mean   :2.512   Mean   :0.1742   Mean   :30.65   Mean   : 23.557
 3rd Qu.:0.00000   3rd Qu.:3.000   3rd Qu.:0.0000   3rd Qu.:39.00   3rd Qu.: 26.000
 Max.   :1.00000   Max.   :3.000   Max.   :1.0000   Max.   :74.00   Max.   :512.329
                                                    NAs    :128

log_mod_1 <- glm(Survived~Pclass+Sex+Age+Fare, data=tr_subs, family='binomial')
pred_1    <- predict(log_mod_1, tr_subs, type = 'response')
pred_1    <- ifelse(pred_1>0.5, 1 , 0)
mean(pred_1 == tr_subs$Survived, na.rm=TRUE)

log_mod_0 <- glm(notSurvived~Pclass+Sex+Age+Fare, data=tr_subs, family='binomial')
pred_0    <- predict(log_mod_0, tr_subs, type = 'response')
pred_0    <- ifelse(pred_0>0.5, 1, 0)
mean(pred_0 == tr_subs$notSurvived, na.rm=TRUE)
</code>
What I tried:
I checked and Pclass and Sex should not cause problems, being a factor. (I tested it, not sure though whether that is mathematically correct when estimating those theta's.)
Even after removing the NA's I got the same result.
Question:
I wonder, what is it about this approach. Is it by chance due to the data that I don't achieve higher accuracies, is it the method that doesn't do what I intended or did I maybe, even after close to 2 hours trying to figure something out, overlook a mistake in my code?
Comment: I see a threshold of 0.5 in your code. You may be interested in [Classification probability threshold](https://stats.stackexchange.com/q/312119/1352). Also very relevant: [Why is accuracy not the best measure for assessing classification models?](https://stats.stackexchange.com/q/312780/1352) and [Is accuracy an improper scoring rule in a binary classification setting?](https://stats.stackexchange.com/q/359909/1352)
Comment: You say "predicting rare events" but is sounds like you're actually predicting their *probability*. Note that under the usual iid assumptions the variance of the sample proportion is the same for both $\hat{p}$ and $\widehat{_{1-p}}$.
Answer: You are using logistic regression, which is based on a binomial model. Also, you are not predicting rare events, but their probabilities. But for events: Predicting if the event $E$ should occur is the same as predicting that the reverse event, $E^c$, should not occur, so one cannot be more precise than the other, it is really the same.
And for a random variable $X \sim \mathcal{Binom}(n, p)$, the variance of $X$ is $np(1-p)$, which is the same as the variance of $n-X \sim \mathcal{Binom}(n, 1-p)$. So there is no difference.  Also, note the comment above by @Stephan Kolassa, and read Classification probability threshold  (and the other links there.)


Views Contextual Filter by Day and Night

Question: I have a content type with a boolean field, using radio buttons for day and night.
I would like to create a view with a contextual filter, which shows "day content" between 8:00 am - 8:00 pm and "night content" between 8:00 pm and 8:00 am.
Which is the best way for creating the contextual filter or view?
Or if you'd have a better suggestion, I could change my content type and fields too.
Answer: your approach is correct.
You can do one thing..Just create a view and contextual filter in view for radio field.
use hook_views_pre_view() hook to add arguments.
function MODULE_NAME_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'myview' && $display_id == 'page_1') {
    $current_time = date('H'); //24hrs format
    if ($current_time >= 8 && $current_time <= 20) {
      $args[] = "value of day radio button";
    }
    else {
      $args[] = "value of night radio button";
    }
  }
}

Hope this will help
Comment: Just to be clear, **do not** use the PHP code in a contextual filter. Modify the contextual filter argument through a hook.
Comment: Okay..That's a good approach..
you can use hook_views_query_alter() hook. and set where clause for that field. by calculating above code. Let me alter my previous comment.
Comment: While I haven't tested it, I was always under the impression the `hook_views_query_alter` was very heavy. I personally use `hook_views_pre_view` to change the args of a view, although I am sure there are at least a couple other options. Please correct me if my assumption is incorrect.
Comment: Ya..right you can use `hook_views_pre_view` hook for this..there are other hooks which can be used..such as `hook_views_query_alter`.
But for this case you can use `hook_views_pre_view`
Comment: I have tried the code below:

`function hook_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'home_featured_content' && $display_id == 'panel_pane_1') {
$current_time = date('H'); //24hrs format
if ($current_time >= 8 && $current_time <= 20) {
  $args[] = "1";
}else {
  $args[] = "0";
  }
 }
}`

When I try to preview with "1" value as contextual filter, it shows me Day Content, but when I try "0", no result returns. And if I try "Night" as contextual filter, it shows me Night Content. How should I change the code?
Comment: Try setting different values for radio inputs for day and night values.
and use those values in code in `if ($current_time >= 8 && $current_time <= 20) {
  $args[] = "value of day radio button";
}else {
  $args[] = "value of night radio button";
  }`
Answer: Interesting idea.
First off however, I think you should use a date(time) field instead of the boolean. You can then use the between operators for your filter. I haven't used the date field as a contextual filter though so I will double check that in a few.
The other option, if necessary, would be to do your check on time() in a hook_views_pre_view and change your $view-args to the corresponding boolean (make sure to change the right element of the array if you have multiple contextual filters).
I would only use the second option if the date contextual filter is not an option for you.


Delete cells if job sheet no longer exists

Question: Everyone;
I have this bit of code that copies data from worksheets with a numeric name (a job number) and pasts them into a column +1 on a master sheet to be email off every night.
I want to delete job pages when the jobs are complete. When I delete a page, my data isn't being removed from the Master Email sheet.
How can I modify this code to delete from cells 18-39 in column XXX if the value in cell 19 (the job number) is no longer in the workbook?
Thanks for any help!
Private Sub Worksheet_Activate()
    Dim ws, MASTER111 As Worksheet
    Dim ColIndex As Integer
    Dim CopyRange As Range
    Set Master = ThisWorkbook.Sheets("MASTER111")

    ColIndex = 2 'first column on Master sheet to paste data
    For Each ws In ThisWorkbook.Worksheets
        If IsNumeric(ws.Name) Then
           Master.Cells(19, ColIndex) = ws.Range("A1") 'put job name in first row
           Set CopyRange = Intersect(ws.UsedRange, ws.Range("N:N"))
           CopyRange.Copy
           Master.Cells(16, ColIndex).PasteSpecial xlValues
           Master.Cells(18, ColIndex) = "Job #"
           Master.Cells(19, ColIndex) = ws.Range("A1") 'put job name in first row
           ColIndex = ColIndex + 1
           Set CopyRange = Nothing
        End If
    Next ws
End Sub

Comment: Try using [Range.Clear](https://msdn.microsoft.com/en-us/vba/excel-vba/articles/range-clear-method-excel) If a condition is met like `If Cells(19,ColIndex)="" Then Range(Cells(18,ColIndex),Cells(39,ColIndex)).Clear` If 19 is blank then....
Comment: You haven't shown any attempt of your own. Did you think we would write this all for you? As it stands, *this question is too broad*.
Comment: @CallumDA I'm hoping someone who knows more than I do would have a more eloquent solution than I could come up with. I was going to make a 'table of contents' and delete the cells if values weren't present in the table... but that is a junk way of doing this. I'm still very new to all this.
Comment: @danieltakeshi I took your advice and have the code below. This is working for one column (A). How do i extend this down to, like, AA?
`Private Sub Worksheet_Change(ByVal Target As Range)

  Dim colindex As Integer
  colindex = 1
 If Cells(2, colindex) = "0" Then Range(Cells(4, colindex), Cells(8, colindex)).Clear

End Sub`
Comment: @mystic_muffin you have to add the code on your loop, right after `For Each ws In ThisWorkbook.Worksheets`
Comment: @danieltakeshi by doing this is seems to interrupt my loop and paste all my data into one column A. I can see the data flashing all in one cell before it settles on the last set of data it's supposed to paste in.
Comment: @mystic_muffin Are you using the increment on the counter? `ColIndex = ColIndex + 1` If you don't, it just loops on `ColIndex = 1` that is column A
Answer: Taking your code as sample, if you want to clear on change of events on the desired Sheet.

Add the code to the desired Sheet. Not on Modules. e.g.: Sheet1

Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo CleanExit
If Cells(2, Target.Column) = "0" Then
    Application.EnableEvents = False
    Range(Cells(4, Target.Column), Cells(8, Target.Column)).Clear
End If
CleanExit:
    Application.EnableEvents = True
    On Error GoTo 0
End Sub

And next time try to edit you question with your new code, don't post large codes on comment.
Comment: Thanks so much! I get so nervous being so green and working with deleting data. I really appreciate all of the help.


Are modules bimodules?

Question: I'm thinking on the following question:
If $A$ is a commutative ring, $M$ is $A$-module if and only if $M$ is $(A,A)$-bimodule?
I know that $M$ is and module-$A$ because $A$ is commutative, but is the question true?
Thanks for your help :)
Comment: Where are you havin problems checking if this is so or not?
Comment: The problem is that I don't know if it is true. Is it?
Comment: But if you try to prove it, what happeens?
Comment: Which specific part of the definition are you having trouble confirming / disproving?
Answer: If we define the right $A$-module multiplication on $M$ as the left-module structure, i.e. $$ ma := am, \qquad m \in M, a \in A $$
then this is in fact a right $A$-module structure, due to $A$'s commutativity, we have
$$ (ma)b = b(am) = (ba)m = (ab)m = m(ab) $$
Answer: You can easily check that every left $A$-module is in an obvious way a right $A^{\textrm{op}}$-module, where $A^{\textrm{op}}$ is the same ring as $A$ except multiplication $\cdot$ in $A^{\textrm{op}}$ is defined in the opposite way: $a \cdot b$ is defined as $ba$.
If $A$ is commutative, then $A = A^{\textrm{op}}$, so every left $A$-module is also a right $A$-module.

Are modules bimodules?


Laravel: Carregar imagens e arquivos linkados

Question: Eu tenho o seguinte código: <link rel="stylesheet" href="css/v1.css">, mas a pagina não carrega ele. Ao inspecionar elemento aparece o seguinte erro:
Como mostra a imagem, ela vem com o link:  http://localhost/naslojas/css/v1.css, porém se eu adicionar o public na url:  http://localhost/naslojas/public/css/v1.css, funciona normal.
Isso está acontecendo com mais de um arquivo e com imagens também. Já me falaram que eu precisaria configurar os hosts do xampp e do windows, mas não tenho a menor ideia de como fazer isso e se esta é realmente a solução.
Como posso resolver esse problema?
Answer: Obs: mude os caminhos de acordo com a sua instalação.
Vai no seu arquivo hosts em:
C:\Windows\System32\drivers\etc

E adiciona nova linha:
127.0.0.1 naslojas.dev

depois, vai no seu arquivo httpd-vhosts.conf em:
C:\xampp\apache\conf\extra

E adiciona:
<VirtualHost *:80>
    ServerName naslojas.dev
    ServerAlias www.naslojas.dev
    DocumentRoot "C:\xampp\htdocs\naslojas\public"
    ErrorLog "logs/dominio1-error.log"
    CustomLog "logs/dominio1-access.log" common
    <Directory "C:\xampp\htdocs\naslojas\public">
        DirectoryIndex index.php index.html index.htm
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

após tudo configurado, reinicie o apache.


"An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll"

Question:     static void Main(string[] args)
    {
        int numVal = -1;
        int numval = -1;
        bool repeat = true;

        Console.WriteLine("Welcome to the perpendicular line finder!");

        while (repeat == true)
        {
            Console.WriteLine("Please write the gradient of the line");

            string userValue = Console.ReadLine();

            try
            {
                numVal = Convert.ToInt32(userValue);
            }
            catch (FormatException e)
            {
                Console.WriteLine("That is not a valid number");
                continue;
            }
            catch (OverflowException e)
            {
                Console.WriteLine("That number is too large, sorry i cannot help you");
                continue;
            }
            Console.WriteLine("So the gradient is {0}? Y/N", numVal);
            string go = Console.ReadLine();
            if (go == "Y" || go == "y")
            {
                repeat = true;
            }
            else
            {
                repeat = false;
            }

            Console.WriteLine("Please write the number that was added or subtracted");
            Console.WriteLine("but if it was subtracted leave the minus sign in");

            string userValue2 = Console.ReadLine();

            try
            {
                numval = Convert.ToInt32(userValue2);
            }
            catch (FormatException e)
            {
                Console.WriteLine("That is not a valid number");
                continue;
            }
            catch (OverflowException e)
            {
                Console.WriteLine("That number is too large, sorry i cannot help you");
                continue;
            }
            Console.WriteLine("So the added or subtracted number is {0}? Y/N", numval);
            string go1 = Console.ReadLine();
            if (go1 == "Y" || go1 == "y")
            {
                repeat = true;
            }
            else
            {
                repeat = false;
            }

            int answer = -1 / numVal;

            Console.WriteLine("A perpendicular line to y = {0}x+{1} is y = {3}x", numVal, userValue2, answer);
            Console.ReadLine();
        }

It comes up with this error:
An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll
This happens when I run the code and get down to the second to last line of code.
I am new to c# and have no idea of what to do please help me.
Comment: Sorry, but the charter of this site does not extend to livestock.
Comment: **Read the error message**, which tells you exactly what's wrong.
Answer: Console.WriteLine("A perpendicular line to y = {0}x+{1} is y = {3}x",
    numVal, userValue2, answer);

The format string refers to a non-existent argument {3}, replace with {2}.
Comment: Thanks but the answer it gives is always "y = 0x" can you explain why.
Comment: @Piggy `int answer = -1 / numVal;` does not look right. Should be something like `double answer = -1.0 / numVal;` (pay attention to `1.0`). Integer division cuts fractional part.
Comment: Thank you, I realized that the -1 was wrong but I didn't now how to change it.
Comment: @Piggy Alternatively, you could do `-1 / (double)numVal`. It would not be an issue in `numVal` would be `double`.


Conditioning on Independent Variable

Question: I want to prove that if $x$ and $y$ are independent, that is $P(x | y) = P(x)$,
then $P(x | y, z) = P(x| z)$. Intuitively this is clear, as $y$ does not provide any information about $x$ because they are independent and introducing $z$ should not affect this.
I am struggling to show this formally. How can I prove this?
Comment: @user597654 I accidentally used someone else's account on the same computer, so I created my own account. I changed the variables because the system wouldn't let me post otherwise. I hope that's alright.
Comment: @Quack no, it's not really allowed. Reposts of questions are only allowed when they add constructive meaning to the dialogue that a previous question didn't. However, since I understand your position, it can slide this time only.
Answer: It's good that you're struggling to show this, since it's false! Here's a counterexample (swap $X, Y, Z$ for $A, B, C$):
Answer:
Intuitively this is clear, as $Y$ does not provide any information about $X$ because they are independent and introducing $Z$ should not affect this.

Why should it not?   $Z$ may be related to $X$ and $Y$ in a way such that jointly $Y$ and $Z$ provide information about $X$.   $Z$ may add clues.
Consider for example $Z=X+Y$ where $X$ and $Y$ are independent.   $Y$ alone provides no information about $X$, however it is clear that knowing values for both $Y$ and $Z$ fixes the value for $X$.   That is to say, $X$ is not conditionally independent of $Y$ when given $Z$.
Independence of two random variables does not entail that they will be conditionally independent when given a third random variable.

I am struggling to show this formally. How can I prove this?

Because it is not generally true, therefore you cannot prove it.

Conditioning on Independent Variable


Is a perfect complexes locally quasi-isomorphic to a bounded complex of free modules of finite type?

Question: I'm a little confused by the definition of perfect complex on a scheme $X$, namely a complex $E^{\cdot}$ of $\mathcal{O}_X$-modules such that for every $x\in X$ there exists $U\ni x$ open such that $E^{\cdot}|_U$ is quasi-isomorphic to a bounded complex of locally free $\mathcal{O}_X$-modules of finite type.
My question could be silly, but is that true that one could just define a perfect complex as a complex locally quasi-isomorphic to a bounded complex of free $\mathcal{O}_X$-modules of finite type?
Given a perfect $E^{\cdot}$, I would argue that one can consider $U\ni x$ such that $E^{\cdot}|_U$ is quasi-isomorphic to $F^{\cdot}$, which is a bounded complex of locally free sheaves over $U$, hence find for every $k$ an open $U_k\ni x$ such that $F^k|_{U_k}$ is free, and taking finite intersection over those $k$ such that $F^k\neq 0$, I find another open $V=\bigcap U_k$ neighborhood of $x$ such that $F^{\cdot}|_V$ is in fact a complex of free $\mathcal{O}_X$-modules
Is this reasoning correct or am I wrong somewere? It sounds wierd to me because the definition is usually given talking abound locally free modules. If I'm wrong, could you suggest a counterexample? Thanks in advance
Answer: Yes, this is correct.  The use of "locally free" in the definition may stem from the fact that for modules over a ring, you can define a perfect complex simply as one that is quasi-isomorphic to a bounded complex of locally free modules of finite type.  That is, in the affine case, there's no need to restrict to an open set $U$ if you say "locally free" instead of "free".


Spy/stub a request inside a route (through chai.request)

Question: The problem
I have an endpoint called /players that makes an http request to an external server and I don't want that request to be performed on my tests, but I was not able to figure how I can mock it under this circumstance.
The code
test/controllers/test-players.js
// ...

it('returns all players', done => {
  chai.request(app) // the content of app is not relevant
    .get('/players')
    .end((err, res) => {
      expect(err).to.not.exist
      expect(res.body.length).to.equal(3)

      done()
    })
})

// ...

controllers/players.js
const request = require('request')

module.exports = (req, res) => {
  request('http://externalendpoint.com', (error, request, body) => {
    res.json(body)
  })
}

Details
I am using:

Node (v6)
Express (v4)
Mocha (v3)
Chai (v3)
Sinon (v1.17)

Ideas?
Answer: I found a solution for this. I just intercepted the request using nock:
const fixture = [{id: 1, name: 'User'}, {id: 2, name: 'Admin'}, {id: 3, name: 'Subadmin'}]

nock('https://domain.com')
  .get('/some-endpoint')
  .reply(200, {fixture})

it('returns all players', done => {
  chai.request(app) // the content of app is not relevant
    .get('/players')
    .end((err, res) => {
      expect(err).to.not.exist
      expect(res.body.length).to.equal(3)

      done()
    })
})


How to access current locale in react app using react-intl

Question: I am using react-intl to Internationalize my react app. I want to access current selected locale to set Accept-Language while sending api requests, currently I am using code below the get it in a react component:
import React, { Component } from 'react';
import { intlShape, injectIntl } from "react-intl";

class CurrentLocale extends Component {

    constructor(props) {
        super(props);
    }

    render() {

        const intl = this.props.intl;

        return (

{intl.locale}

            );

    }

}

CurrentLocale.propTypes = {
    intl: intlShape.isRequired
};

export default injectIntl(CurrentLocale);

but how can I get it in something like this?
import axios from 'axios';
import AppConfig from 'Constants/AppConfig';

 // I need something like intl to use intl.locale while sending requests...
    export default
        axios.create({
            baseURL: AppConfig.apiUrl,
            timeout: 5000,
            headers: {
                post: {
                    'Content-Type': 'application/json;',
                    'Accept': 'application/json;',
                    'Accept-Language': 'fa-IR,en-US' // here i want to change this
                },
                get: {

                    'Content-Type': 'application/json;',
                    'Accept': 'application/json;',
                    'Accept-Language': 'fa-IR,en-US'// here i want to change this
                }
            }
        });

Answer: You can do something like:
export default intl => {
  axios.create({
    baseURL: AppConfig.apiUrl,
    timeout: 5000,
    headers: {
      post: {
        "Content-Type": "application/json;",
        Accept: "application/json;",
        "Accept-Language": intl
      },
      get: {
        "Content-Type": "application/json;",
        Accept: "application/json;",
        "Accept-Language": intl
      }
    }
  });
};

And in your component simply call that function.
class SomeComponent {
  sendRequest = () => {
    await send(this.props.intl);
  }
}


How to filter for Microsoft Exchange Distribution lists from general AD LDAP groups?

Question: We are integrating an application to Active Directory groups through an LDAP handler, and we need to be able to tell apart AD groups that come from Microsoft Exchange Mail Distribution lists and the rest of them, so we need an LDAP filter for these LDAP handlers that only picks AD groups created from Exchange lists... so far we have not been able to find how to do this by only the means of a filter.
The reason for this is that we want to be able to delegate control of user groups to the end-users of the application, so that they are able to take better advantage of groups since a good deal of the mailing distribution lists are made on a per project, team or function group basis, and these criterion make a lot of sense for the application.
We cannot list all of our user groups since most of them are irrelevant and we have an asbsurd amount of them, so we don't want to pollute the application's database.
Comment: group sprawl should be contained, not encouraged
Comment: so you already have too many groups and now you want users to manage them?
Comment: they already are, might as well use them
Answer: Microsoft Exchange Distribution lists are just standard AD groups that are "mail enabled". One of LDAP properties you can use to check if given AD group is mail enabled is "proxyAddresses". So you can use the following LDAP filter:
<code>(&(objectCategory=Group)(proxyAddresses=*))
</code>
Comment: Thanks for information, I have edited my answer. Interesting thing is that before posting my answer I have verified this filter by using it in "saved query" in "Active Directory Users and Computers" and it worked.
Comment: Yup, it worked, only that objectCategory should be "Group" and not "group"


How to write a quickfix list to a file

Question: I'm looking for a way to write content of a quickfix window to a file with a specific formatting, preferably in a way that is easily scriptable.
What I'm trying to achieve is a very light integration of Vim and ipdb:

I set 'breakpoints' as items on a quickfix list with mapping:
nmap <leader>s :call setqflist([], 'a', {'items': [{'filename': @%, 'lnum':line('.'), 'text':'break'}]})
Write content of the quickfix to .pdbrc file with break file_path:line_number formatting
Run ipdb on specified script
Comment: I just checked, you can definitely save quickfix contents using `:w`.
Comment: yeah, i know, but what if quickfix window is not currently open? and this misses my formatting requirement
Comment: Presumably, you're going to write a vim function that does all this automatically. So in that function, after you get the formatting done, you can do a quick set of calls (`:copen`, `:w save_file`, and `:q`) to open quickfix, save to file, and close it. That takes care of one problem. The other is the formatting which hopefully romainl's answer helps you solve.
Answer: You have two problems:

Turning items into a list of properly formatted lines.
You will need to:

get the quickfix list with :help getqflist(),
format each item of the list with :help map(),
derive file_path from the bufnr field with :help bufname() and possibly :help fnamemodify().

Writing that list to a given file.
You will need :help writefile().

How to write a quickfix list to a file


How to display flags to anonymous users and redirect to login after clicking a flag?

Question: I want to display flag to anonymous user and upon clicking the user should be redirected to register/login page.
I found one answer to this problem in the question about
"How to display a flag to anonymous users?".
I tried this solution but did not work, may be I did not put the code in correct place?
I am using Bartik as my template and I put the code in node.tpl.php.
Any suggestions?
Comment: i put it just at the end of the file, not under any specific function.
Comment: Under which function i am supposed to put this?
Comment: possible duplicate of [Display flag to anonymous user](http://drupal.stackexchange.com/questions/35472/display-flag-to-anonymous-user)
Answer: Maybe the Flag anonymous module is what are you looking for.
Answer: Why not just use the Session API module.

The Session API is a very simple set of functions that extend the core
  sessions workings, allowing data to be stored and associated with a
  user's session.
There is no need to install this module unless you are instructed to
  do so by another module.
Currently this module is used by
Flag DrupalChat Mozilla Persona Session Favorites Domain User Default
  The Sign-Up Problem
Comment: Because the session API module is essentially abandoned (last release was in 2012, and is not stable - see RC1 in the name.)  It currently breaks the page cache, and if you are using a reverse-proxy cache it will not work.  See https://www.drupal.org/node/1983696


How to fix migrate query() that's breaking my migration?

Question: So I have a Drupal 2 Drupal (d2d) migration configured as follows:
class RanchoAboutNodeMigration extends RanchoNodeMigration {
  public function __construct(array $arguments) {
    parent::__construct($arguments);

    ...

    // This is an entity reference field
    $this->addFieldMapping('field_attached_images', 'iid')
         ->separator(',')
         ->sourceMigration('Image');
    ...
  }

  protected function query() {
    // Get the default query
    $query = parent::query();
    $query->leftJoin('image_attach','ia','n.nid = ia.nid');
    $query->addExpression('GROUP_CONCAT(DISTINCT ia.iid)', 'iid');
    $query->addField('ia', 'iid', 'iid');
    $query->addField('ia', 'nid', 'inid');

    return $query;
  }
}

The query causes two problems:

I can only import items one at a time through drush mi or the UI
Most important: I'll eventually run into a PDOexception for duplicate rows and then the error "Could not save to map table due to NULL value for key field nid" with migrate attempting to move totally empty rows.

Both items can be addressed by commenting out the line with $query->addExpression(), but then I miss some desired images. When the migration is actually working, everything migrates correctly, including the referenced image(s).
Any thoughts on what's causing this bizarre behavior when things go wrong and how to address it?
Only thing I can think is to create a local query in prepareRow(), but I don't think I've seen anyone else do that before.
Answer: Adding a query to prepareRow() is the way to go:
  public function prepareRow($row) {
    if (parent::prepareRow($row) === FALSE) {
      return FALSE;
    }
    $query = Database::getConnection('default', 'd6source')
           ->select('image_attach', 'ia')
           ->fields('ia')
           ->condition('nid',$row->nid);
    $query->addExpression('GROUP_CONCAT(DISTINCT ia.iid)', 'iid');
    $query->groupBy('ia.nid');
    $result = $query->execute();
    foreach ($result as $r) {
      $iid[] = $r->iid;
    }
    $row->iid = implode (",", $iid);
  }

This has the huge added benefit of not messing up the source row count.


Java Object and array memory location

Question: I'm writing an array-backed hashtable in Java, where the type of key and value are Object; no other guarantee.
The easiest way for me code-wise is to create an object to hold them:
public class Pair {
    public Object key;
    public Object value;
}

And then create an array
public Pair[] storage = new Pair[8];
But how does the jvm treat that in memory?  Which is to say, will the array actually:

be an array of pointers to Pair() objects sitting elsewhere, or
contain the actual data?

edit
Since the objects are instantiated later as new Pair(), they're randomly placed in the heap.  Is there any good way to ensure they're sequential in the heap?  Would I need to do some trickery with sun.misc.unsafe to make that work?
Explaining my motivation, if I want to try and ensure that sequential items are in the same page of memory, is there any way to do this in Java?
Comment: I think you know that, but public Pair[] storage = new Pair[8]; does not create the pair objects. Just said, if you dident. :)
Answer: The array will be an object on the heap containing pointers to the Pair objects which will also be on the heap (but separate from the array itself).
Comment: +1.  Any good way to group them together?  Otherwise, it seems like non-primitive arrays would be a sloppy mess in memory.
Comment: The array itself will be a contiguous block and if the other objects are allocated at the same time (assuming no other threads and no GC runs in the middle) then they'll be placed in next to each other in memory too.  However, there's no guarantee they'll be in the same memory page.  You could serialise the objects into a byte array yourself and force the layout that way, but it won't be pretty.
Comment: Not so much worried about pretty at this point; getting around the hardware abstractions never looks good.  Thank you!
Answer: No, the storage array will only contain pointers to the actual Pair objects existing somewhere else on the heap. Yet, remember to instantiate 8 Pair objects and make each element of the array point to these objects. You need to have something like this after the code that you have written:
for(int i=0;i<storage.length;i++)
    storage[i] = new Pair() ;

Only then will the Pair objects be created and correctly referred to by the storage array.
Comment: Oh, I know I have to initialize the objects, but I was wondering if the array guaranteed the objects would be sequential in memory; that sounds like a definite no.  +1, thanks for the answer!
Comment: i am not sure if chronologically-sequentially created objects are contiguous in memory, but it seems unlikely considering the garbage collection is done automatically in the language. But, since the objects are not contained in the array, there is no guarantee about this. The pointers in the array must of course be sequential.

Java Object and array memory location


How can I migrate a font library?

Question: I have a Drupal 7 multi-site platform which contains a sites/all/libraries/fonts/<fontname> directory, where there are several font files.
I am porting one of the Drupal 7 sites to a new Drupal 9 platform, where I have created a Drupal 9 version of the theme. I want to use these fonts on the Drupal 9 site.
Where should I copy these font files? How do I tell the Drupal 9 theme about them?
Comment: `To where should I copy these D7 font files on the new D9 site` somewhere on your D9 custom theme's folder. `how do I tell the D9 theme about them?` [Add them to your CSS](https://www.w3schools.com/css/css3_fonts.asp)
Answer: It appears that you don't need to update the theme YAML files (theme.info.yml, theme.libraries.yml) to tell Drupal about the new font, just copying the font directory across to somewhere inside the D9 theme, and referencing it in the CSS was enough, as suggested in the comments.

How can I migrate a font library?


Setting up an embedded Neo4J 2 server for testing REST API calls

Question: Can anyone point me in the direction of what I need to do to set up an embedded Neo4J 2 server that I can fire REST calls for unit testing?
Answer: You can use something similar to my in-memory server, just use the CommunityBootstrapper inside your tests.
There is also a unit-testing ServerBuilder which is used for Neo4j's own functional tests against Neo4j server, check the Neo4j Sources for how it is used.


Can MLE be indepedent of the observations?

Question: Let the random variable $X$ follow the distribution:
$$ f(x;\theta) = \theta^2(x+1)(1-\theta)^x$$
where $x$ takes values in $[0, \infty)$ and $\theta$ in $[0, 1]$. The likelihood is defined as:
$$\mathcal{L}(x \mid \theta) = p_\theta(x)$$
and for $N$ i.i.d observations:
$$\mathcal{L}(\theta) = \prod_{i=1}^N p_\theta(x_i)$$
Due to the monoticity of the $\ln$ function, we can instead maximize the log-likelihood:
$$\ln(\mathcal{L}(\theta)) = \ln \left( \prod_{i=1}^N p_\theta(x_i) \right) = \sum_{i=1}^{N} \ln p_\theta(x_i) = \sum_{i=1}^{N} x_i\ln \left[\theta^2 (x+1)(1-\theta)\right]$$
The derivative of the likelihood with respect to $\theta$ is:
$$\frac{d\ln(\mathcal{L}(\theta))}{d\theta} = \sum_{i=1}^{N} x_i \frac{d}{d\theta} \ln\left[\theta^2 (x+1)(1-\theta)\right] = \sum_{i=1}^{N} x_i \frac{d}{d\theta} \left[ \ln(\theta^2) + \ln(x_i + 1) + \ln(1-\theta)\right]$$
Taking the derivatives of the terms inside the brackets we obtain:
$$\sum_{i=1}^{N} x_i \left(\frac{2}{\theta} - \frac{1}{1-\theta}\right)$$
and setting this to zero leads to:
$$\sum_{i=1}^{N} x_i \frac{2}{\theta} = \sum_{i=1}^{N} x_i \frac{1}{1-\theta} \Longleftrightarrow \frac{2}{\theta}\sum_{i=1}^n x_i = \frac{1}{1-\theta} \sum_{i=1}^n x_i \Longleftrightarrow \frac{2}{\theta} = \frac{1}{1-\theta}$$
Solving the last equations leads to $\hat{\theta}=\frac{2}{3}$.
Is it possible for the MLE to be independent of the observations ($x_i$ are not involved in calculation of $\hat{\theta}$)? If yes, is there something in the form of $f(x;\theta)$ that indicates that?
Comment: Your calculation of the likelihood equation is incorrect. It is easiest to work with a single observation when calculating the MLE.
Comment: I think the calculation with logarithm has a mistake: $\ln(p_\theta(x)) = 2\ln \theta + \ln(x+1) + x \ln(1-\theta)$
Answer: First, it should be noted that your computation is incorrect: you cannot distribute the $x_i$ across all of the terms. The log-likelihood function should instead look like the following:
$$\sum_{i=1}^n 2 \log \theta + \log(x_i+1) + x_i\log(1-\theta)$$
so that the derivative of the log-likelihood function is
$$\sum_{i=1}^n \frac2{\theta} - \frac{x_i}{1-\theta} = 0$$
or solving,
$$\hat\theta = f(\bar x)$$
where $f$ is the function defined such that $f^{-1}(\theta) = \frac{2(1-\theta)}{\theta}$ and $\bar x$ is the sample mean. This does indeed depend on the data.
More broadly speaking, let's take a step back and ask conceptually what it would mean for the MLE to not depend on the data. Intuitively, this amounts to claiming that no matter what the data says, our best guess of the true parameter is the same. Does this make sense? If this was true, what would even be the point of looking at the data?
Comment: @adosar the uniqueness and existence of an MLE depends on a lot. In elementary probability courses, you usually deal with regular exponential families and parameters that do not lie on the boundary of the parameter space. The proofs that these methods are well behaved are extremely complicated. But one does not need to go far in statistics to find models that deal with this problem all the time.
Comment: Oops, thank you for pointing out the fallacy in the calculation. Your last paragraph was my motivation for asking this question. I found it meaningless that MLE is independent of the data (of course I had made an incorrect computation). Also, is there any way that can can prove that indeed the MLE we calculate by setting the derivative to zero is a maximum? I mean all the sources I have seen they don't further examine whether this critical point is a minimum or maximum (e.g. taking the second derivative).


How to open njsproj project in Visual studio 2012

Question: When I open njsproj project in Visual studio 2012 it gives an error incompatible project
Answer: You need the Node.JS Tools for Visual Studio.
Answer: In Visual Studio, go to Tools -> Get tools and Features -> Workloads -> select NodeJs Development
Links in older answers are outdated.
Comment: I found that after checking the `Node.js` workload, it was still showing as incompatible.  But when I right-clicked the project and reloaded, it opened correctly.
Comment: I have Node.js development checked and the njsproj still shows up as incompatible and does not load. Using VS 2017 15.9.7
Answer: Info for VS 2015:
They moved from CodePlex to GitHub.
New link is https://github.com/Microsoft/nodejstools#readme
The current version is here http://aka.ms/ntvslateststable.
Today it´s V1.2.


Nginx proxy_pass based on file extension and query string

Question: I need to proxy_pass static assets (.js .css) based on file extension and query strings.
For example:
domain.com/foo.css - go to upstream1
domain.com/foo.css?V=1234 - go to upstream2
Reason is I have a 3 server setup - a router, an application server and a static server. I would like any request with clean url domain.com/foo.cs to go to upstream1 (where my static server is configured). And any request that has query string url domain.com/foo.css?V=1234 to go to upstream2 (where my application server is configured).
Maybe it can be done using http://wiki.nginx.org/HttpLuaModule?
Thanks!
Answer: Use a map.
<code>map $arg_v $node {
    default        upstream1;
    "~^[0-9]+$"    upstream2;
}

server {

    listen 80;
    server_name domain.com;

    location ~ \.(css|js)$ {
        proxy_pass http://$node;
    }

 }
</code>
Comment: @RadoslavStefanov Oh yeah, typo in my post. Use `$node` not `node`.
Comment: Hi Xavier,

This does seem to sort of work. However, it just sends requests to upstream1. When I try to request domain.com/test.js?V=asdf or domain.com/test.js?V=1234 it always proxies to upstream1.

I guess I should update the regex ?
Comment: @RadoslavStefanov There's no reason that test.js?V=1234 would be proxied to upstream1. How do you test it, and what's your full config ? If you have not only digits then yes you will need to update the regex.
Comment: I just applied this config for testing and requested domain.com/bla.js?V=1234

map $arg_v $node {
    default        192.168.10.1;
    "~^[0-9]+$"    192.168.10.2;
}

server {

    listen 192.168.10.80:80;
    server_name domain.com;

    location ~ \.(css|js)$ {
        proxy_pass http://node;
    }

 }

This actually gives me an error:

nginx: [emerg] host not found in upstream "node" in /etc/nginx/sites-enabled/test:13


Unusual chord progression

Question: I'm beginning my harmony studies, and I'm using some pop music to practice.
I started to analyse a tune from Spice Girls: "Say You'll Be There". Its tone is D major, so the verses feature this chord progression:

    vi II IV  I
    Bm E  G   D

First attention point: the second degree is major, not minor as usual. I do see this type of harmonization before, but don't understand it fully yet.
What really puzzles me is the chord progression of the bridge:

    V vi  IV  V
    C Bm  Bb  A

It suggests a modulation to F major, but the chords Bm and A don't belong to that tonality. It seems to me this bridge alternates between D major and F major in its chord progression, what is very unusual, at least for my studies so far.
Like I said, I'm a beginner practitioner and I might miss something. What could it be?
Comment: When you progress past being a beginner, you will discover that "the scale of a key contains 7 notes" is just a simplified idea to get you started. Any key contains all 12 notes, and all 24 major and minor chords (not to mention other chord types!) - it's just that some of the notes and chords get used more often than others. And IMO "tonality" is like "pornography" - you can't define exactly what tonality is, but you know it when you hear it. (And FWIW J S Bach wrote plenty of chord progressions that are far more "way out" than the two you quoted from the Spice Girls!)
Comment: You're right. The chord progression templates are by no means rigid. What I'm trying to understand are the relations and functions the chords of the song's bridge are performing.
Comment: In your second chord progression, given that C is V and Bb is IV, Bm must be ♮iv, not vi.
Answer: As a preface, I know the song you're talking about and those aren't quite the chords. I haven't heard it in at least a decade, but I'm going to use the chords that I believe to be correct in my answer.
There are two general concepts about harmony that are important to understand when looking at progressions that mix chords from the key and chords not from the key:

Chords from outside the key are overwhelmingly common and do not represent a breaking of the rules but an adaptation of them; indeed, when looking at borrowed chords, generally what defines them is their relationship to the "original" key.
Chromatic basslines are also very common and, because they can't occur in a diatonic system by definition*, they necessarily invoke lots of borrowing.

Let's look at the first progression first because it's easier.
BMi | E      | G  (Gmi) | D  (D/C#) |
 vi   V-of-V   IV (iv)    I  (I/VII)

There's only one standout label here, and it's on the E. In the key of D, E would typically be called V-of-V; it is the chord on the fifth of the key... of the chord on the fifth of the key. This is termed a secondary dominant. Secondary dominants are a relatively advanced concept (particularly if you're not comfortable with what a primary dominant is; if that's the case, I'd investigate that further before looking at secondary dominants). Nonetheless, a brief summary of their purpose is to provide a temporary suggestion of another key: V-of-V suggests V; V-of-IV suggests IV, V-of-vi suggests vi... and so on.
Generally, V-of-V is followed by V, but fairly often it is followed by IV instead. The reasons for this aren't so simple, but basically what it comes down to is the fact that Bmi-E strongly suggests the dorian mode on B (which comes from A major) and then the G quickly pulls you back to the D major system. This is a fairly common chord progression in pop music because it gives you access to a lot of notes while leaving you grounded in familiar territory.
I've also added a Gmi and D/C# in brackets. This is because the chorus almost certainly uses the minor chord on the fourth, at least some of the time, and the bass line that I remember has a pretty fat C# in it. Functionally, these don't change much, but it's worth noting that iv is another very common borrowing and is perhaps the most prominent example of a concept called modal interchange, where chords from parallel scales are used.
Now, the second progression:
C        | G/B  | Bb | A7
bVII       IV/vi bVI   V7
(IV-of-IV) (IV)

N.B.: You have this labelled as a bridge, but I'm fairly certain this is a pre-chorus.
This is a chromatically descending bassline. It attempts to get us to the dominant chord in four bars, and so it starts three semitones above the intended root and moves the root down a semitone until it gets to the ending point. At a high level, this is how chromatic basslines work: The chromaticism of the bassline is the anchor. There are few things more common in contemporary music than the chromatic bassline, and to explain all of the possible variations and their differences would require an exceedingly large block of text.
But back to the Spice Girls. The first chord is C; this is another example of modal interchange and it comes from the mixolydian mode. The chord that generally follows the bVII is the IV, and that's what we've got here. The Bb is also an example of modal interchange, but this time we're borrowing from minor; it gives us access to F as a melody note and serves the purpose of moving the bassline one semitone closer to A. The last chord is the dominant chord of our key and serves as an ideal transition back to a tonic chord (in this case B minor).
An important note of distinction here is that at no point in time have we actually modulated to a different key. We've suggested a lot of different scales, but with the exception of E (which, as a secondary dominant, is an example of tonicization) the key we've suggested has always had a tonic of D.
A little disclaimer about my transcription: I didn't actually listen to the song when I came up with these changes and I haven't heard the song for many years. Nevertheless, the only chord that can actually be "wrong" here is G/B, and what you may find that the bass is actually playing a G, not a B. This doesn't affect the overall analysis too much, however, as it simply means that the descending chromatic line is in the melody, not the bass. I will verify one way or another later today.
*Diatonic systems contain one of each letter name; this quickly becomes impossible to maintain with a chromatic bassline.
Answer: I listened to the song now and the key is Bb minor (I suppose you transcribed it in Bm to be easier? )
anyway, the verses use : a progression of 2 chords that can be seen built on a Dorian scale (or a simple chromatic alteration of a chord built on 4th step of the minor scale, a "borrowed " chord) - after that, I hear the same chord that changes from Major to minor (it's got a similar sound to the progression that you wrote) and at the end , the final chord of these four chords is a Major and it sounds like a new tonic in the relative Major (it is the same tonal area, and more or less the same notes)
that cool, 70s and Soul-oriented pre chorus (or bridge) is made of quartal chords , especially
I hear : Db 7/4  that brings to Gb Major 7th   - in your transcription, it will be:  C 7/4 , F Maj7 - not Bm (are you sure??)
and these 2 chords are part of one tonality (call it tonal "area" if you like)

if you listen to the melody that they sing, they sing the Major 7th, when the Maj 7 chord occurs
after that, there's a key switch ( a "tonal center" change) and, in my transcription, I hear a 7/4 chord that is a B 7/4  and it's exactly one whole step lower than the first one of the pre chorus

In your key , it will be :    C 7/4,  F Maj7,    Bb 7/4 ....
and it goes directly to the last 7/4 of the series, which in my key is Ab 7/4  and in your key is A (7/4)
If you listen to ,,,,say Michael Jackson of the first album, or Stevie Wonder in the 70s,,, these harmonies were common , Spice Girls used some good song writer here...
Comment: Listening to the version I found on YouTube, this tune is clearly in D♭ major, not B♭ minor. [Wikipedia agrees with me](https://en.wikipedia.org/wiki/Say_You'll_Be_There#Composition).
Comment: ah wikipedia agrees with you? and who cares- B b minor with a Dorian variation, thats all-
Comment: Well, agree that who cares if Wikipedia agrees, but the key is clearly D♭ major, not B♭ minor. These two keys are not the same.
Comment: I suppose that you are not familiar with modes, right? B b minor (Dorian) is exactly in the same key of Db- it's exactly the same thing- the song starts with a B b minor and follows a mixed mode composition technique- the second chord is built on the IV step of B b minor (Dorian progression) and, using a plagal (IV-I) cadenza, it resolves in Db Major- Happy now?
Comment: Ignoring your obnoxious condescension, modes are not keys. You said key of B♭ minor. The first chord is a B♭ minor, but this is not the key. The key is D♭ major. No need to appeal to "mixed mode composition technique" to determine the tonality here.
Comment: I did not say that modes are not scales, I said that they are not keys. The key of D♭ major has tonal center D♭, while the key of B♭ minor has tonal center B♭.
Comment: Anyway, I think that the problem is based on different kinds of music analysys, I feel the tonic chord is the B b minor (with a dorian relationship/ variation on the chord that follows) and of course, yes, it transforms into Db Major.  It' the same tonal area - it only needs a view that is not classical
Comment: Please, now do a little experiment and play the second chord: it's an Eb Major , right ? A chord that does not exist in the key of Db (I'm sure you know it would be minor) - since here we're not talking of "secondary dominants" - because the Eb is not moving towards a momentary tonic...it's clear that it's about mixed modes, Eb Major would be a chord built with a Db Lydian scale - I agree that the key is Db Major, but it's got variations -that I see coming from a modal harmony approach, but one can analyze it from another point of view
Comment: Yes, E♭ Maj is not a chord diatonic to D♭ major (it actually sounds like an E♭7). I agree that it's fine to talk about this as mixing modes or borrowing chords or whatever, but this doesn't change the key center of the song. To me it feels like the chords are all moving towards the D♭ Maj chord. It feels like you could view the B♭ min - E♭ Maj as ii - V7 in A♭, then G♭ Maj - D♭ Maj as IV - I in D♭.
Comment: OK, then...it's in Db ! I agree that you can also view it in Db Major, with the second "diatonic" chord (Eb) with a chromatic alteration, if you like it...
Comment: I also think that the problem here was which analyzing method is more correct, being a modern song...but to me, if I think about the progression, it could have been written by Bach, it's not so "modern" after all,,,the best is when the pre-chorus comes in, with all those 7/4 chords...what do you think about the pre chorus ?
Comment: Those changes in the pre-chorus are nice. I'm not sure that I am hearing them the same way as you. I hear **BMaj7 - B♭min - AMaj7 - A♭(sus4)**. I can't tell if there is a resolution to **A♭** in there or not, the mix seems to be hiding that from me (and I am listening on a laptop right now). I am not exactly sure what you mean by, e.g. **B 7/4** above. Is that a seventh chord with the 4th in the bass? In any case, the only sus chord I am hearing is the final **A♭**, but I could be missing something here. This is undoubtedly the most time I have ever spent listening to Spice Girls ;)
Comment: me too, me too...lol...I think the video on Youtube has something strange relating to the frequencies (my guitar is 440 Hz but the video, who knows?) - Anyway, I 'm listening again and the pre chorus seem to open the sequence with a Bass in B (I thought the chord was a 7/4 because playing it on my guitar it sounded very cool and seventies (Wonder, Jackson, and so on)... so it would have been a B/Db , on guitar, a quartal chord. That bass resolves on a "momentary" tonic (Gb Maj7) , then the following chord seems to be a B 7/4 with the Bass in B -even if it's not clear , frequencies are too bass
Comment: I thought about that chord (Gb Maj 7 ) coz at that moment I feel a sense of "tranquillity,serenity" that is the characteristic of those delta chords, of course, I 'm not sure 100% , I wish I had the original CD- Now I'm listening to Spice Girls "Say You'll Be There" (Spice World Version...) as well, I hope it's better, I also spotted a dim chord somewhere...
Answer: Related to the bridge: is this the real chord sequence as played on the record or does this come from a simplified score ?
if the Bb in the bridge is a Bb7 we might have a tritone substitution from E7 to Bb7 leading to the A chord.  This is a development of a ii - V7 - I sequence as often used in jazz (originally Bm - E7 - A) including in situations where the composer uses secondary dominants

Unusual chord progression