Why do we scale/shift up an octave in the overtone series?

Question: If I take C (middle C on piano ) as a base from which to construct the overtone series, I quickly find G and E to have simple ratios 3:1 and 5:1 and by shifting octaves I get 3:2 and 5:4. And I was wondering why we shift? whats the reason? 3:2 ratio isn't a integer multiple of the fundamental, right? Is it the way the piano keys are constructed/tuned?
I also wonder why the intervals between each overtone get shorter or closer together you further you go down the chain?
Im new and confused to music theory, I apologize if its a dumb question. Im grateful for every answer.
Comment: Can you explain in a bit more detail what you mean by "by shifting octaves I get 3:2 and 5:4" ? I can guess what you mean, but I'm not sure I'm guessing right :)
Answer: You aren't shifting. The ratios of the harmonic series refer to intervals such as a perfect fifth (3:2) or a major third (5:4). They are not relative to the fundamental (5:1 or 3:1).
As to the keys on the piano, they use equal temperament, so the only truly "in tune" intervals are the octave. Since you can't adjust the tuning of the piano while playing like you can with most other instruments, this was developed to enable modulation to any other key where they would be equally slightly "out of tune". If you tune a keyboard using just intonation, which is the pure overtone series, certain keys couldn't be modulated to because they were unacceptably out of tune.
The reason that intervals get closer together the higher you get is because the harmonic seres is an arithmetic series (1×f, 2×f, 3×f, 4×f, 5×f, ...). In terms of frequency, the difference between consecutive harmonics is therefore constant and equal to the fundamental. But because human ears respond to sound nonlinearly, higher harmonics are perceived as "closer together" than lower ones.
Here is a handy graphic of the the overtone series which indicates that you are measuring intervals, not pitches.:


Are non-diatonic chord progressions usually modal mixtures?

Question: I asked a question in the past about non-diatonic notes. In the answer I got a progression of the form:

IV Maj | ♯iv dim  | I64    | V7    | I Maj    IV Maj | ♯iv
  dim  | V7      | V7     | ♯v dim   | vi min   II7    | V7
  | I Maj   I Maj  | ♭iii dim | ii min | V7     ii min
  | iv min6  | I64    | V7    | I Maj

This progression was in reference to the guy playing here, which I liked.
My understanding is that non-diatonic chords are usually chords from different modes but I might be wrong. Using the progressions above, I listed the mode followed by what chord degree it is according to the table I found here.
Ionian  4 | Lydian 4 | Ionian 1 | Ionian 5 | Ionian 1
Ionian 4 | Lydian 4 | Ionian 5
Ionian 5 | ??? | Ionian 6
Lydian 2 (?) | Ionian 5 | Ionian 1
Ionian 1 | Aeolian 3 | Ionian 2 | Ionian 5
Ionian 2 | Aeolian 4 | Ionian 1 | Ionian 5 | Ionian 1
So my question is how does one get to the chord "♯v dim", I can't see it in the roman numeral modes table. Also if I'm looking for interesting non-diatonic chord progressions, should I primarily look at mode mixing?
Answer: Modal mixture means borrowing chords from parallel modes. But here, the ♯v dim chord is the leading tone chord to the vi chord (i.e., it's really a vii°/vi). I would suggest not trying to analyze chords as if they are within "other modes" unless they cannot be construed as anything but modal mixture. The reason for this is that many chords (at least in traditional common practice period harmony) can be described as functioning within the given key. In fact, the "II7" chord you have is analyzable as a "V7/V" chord, and is thus given a proper function within the key compared to a "II7". Now obviously this isn't always the case, but the only time I personally would analyze something as ♯v° is if it was unanalyzable as anything else, which I imagine would be a very rare case. (The ♭iii° chord can be analyzed as a diminished passing chord downwards).
Comment: Other way around. First try primary chords (e.g., I, ii, iii, IV, V, vi, vii° in major), then secondary chords (secondary dominants (V7/V), leading tone chords (vii°/V, etc), then modal mixture (♭III, ♭VI, ♭VII, iv, etc), and then possibly modulation. Just loose guidelines here, not solid set-in-stone rules.
Comment: In some theory texts _primary_ refers to the `I IV V` chords and _secondary means `ii iii vi`, I suppose that leaves `viio` as a alternative `V`.
Comment: Not only secondary dominants, chromatic mediants and related chords. Augmented Sixths and Neapolitan Sixths among others.
Comment: I guess either modal mixture or secondary dominants then.
Comment: Try to analyze secondary chords before modal mixture chords as a rule of thumb :)
Comment: but my table covered most of the chords, shouldn't I go "if not in modal mixture table, then it's a secondary dominant" kind of thing?
Comment: Others might disagree with me, which is totally fine. This is just what I see as an explanation when I look at that chord progression.
Comment: ok, Michael, this definition would be lesson one in triads! but I actually never heard about this terms whether in English nor in German. But I've been  learning the English terminology only for some weeks. What I understood first was secondary dominants: in German they are called "Zwischendominante". Zwischen means between. I,IV,V would be translated the principal chords, the others would be side chords.
Comment: @AlbrechtHügli - secondary dominants are seen as such because they lead to a diatonic chord. As in V/V7 in key C, that's the dominant of the dominant - D>G7. Or V/vi, in key C, that's the dominant of Am, E>Am. Explains better than 'II' or 'III'.
Answer:
Also if I'm looking for interesting non-diatonic chord progressions, should I primarily look at mode mixing?

That's one way. But borrowed chords mostly function the same way in the key as the diatonic chords. So they provide colorful, but not necessarily non-functional harmony. It depends on what you really want, but I think the simple comparison is Romantic era harmony versus Impressionism like Debussy where you might have non-diatonic, non-functional dominant seventh chords, etc.
I recently have been exploring this topic myself. I identified the basic diatonic seventh chord types: major seventh, minor seventh, dominant seventh, and half-diminished seventh, and then looked for various non-diatonic harmonic patterns I could apply to them.
One of the first things I took note of was succession of chord qualities within the diatonic realm and then make contrary patterns. For example, diatonically we have two adjacent minor seventh chords a whole step apart: ii and iii, but we do not have similarly adjacent dominant seventh chords. So, I can get a simple non-diatonic, non-functional progression with something like G7 to A7. To avoid that A7 suggesting a V7/ii I could use G7 A7 B7 for an emphatically non-functional progression.
I also looked at all the chord qualities for the fundamental root progression by descending fifth. Going through the whole diatonic circle of fifths I listed the two chord pairs (which I called bi-grams after a linguistic analysis term) and compared that with the 16 possible bi-grams of chord qualities. I eliminated the bi-grams that were diatonic and selected the others. A diatonic root progression by descending fifth from viiø7 goes to iiim7. I could alter the iiim7 chord by lowering the fifth and get a succession of chord qualities that isn't diatonic: Bø7 to Eø7.
Instead of using a circle of fifths I tried a circle of chromatic mediants. I tried both root progression by ascending minor third and ascending major third. One thing I thought was interesting is how when diatonic seventh chords move through a circle of fifths each progression has two common tones and two tones changing by step. With a circle of chromatic mediants - ascending minor third, using any of the four seventh chord qualities - the smoothest voice leading resulted in two common tones and two tones changing by half step. Both of these sequential progressions had similar voice leading re. common tones.
Finally some interesting progression can be found by holding the chord root while changing the chord quality and then moving sequentially by ascending or descending half step. Something like: start with a minor seventh chord, lower the fifth to create a half diminished seventh on the same root, then drop the root a half step and form a minor seven chord above it by dropping the root, third, and seventh, then continue that sequence. Like this Cm7 Cø7|Bm7 Bø7|.... There are many other possibilities ascending and descending.
Some rules of thumb emerge:

multiple successions of the same chord quality are mostly non-diatonic
changing chord quality on a shared root is non-diatonic
number of common tones in voice leading helps determine harmonic 'pull'

I don't really know how to word that last point concisely. Basically, it seems that regardless of the pitches being diatonic or chromatic, if the number of voices changing is only one the progression is 'weak' or 'gentle', if about half the voices change the progression is 'strong' or 'dynamic', if all the voices change, the progression is 'emphatic' maybe even 'abrupt.'
This was my approach. I was aiming for a fairly traditional sound. Most of it sounds jazz-ish or Impressionistic. You could do something different. I mostly want to say you can try to create your own tonal logic. When you dispense with diatonic+secondary+borrowed harmony there really aren't established conventions.
Another thing to try is progressions and voice leading through any non-diatonic scale. Try the double harmonic as an example. It has all kinds of interesting options with simple triads and seventh chords. By definition all of the progressions will be non-diatonic.
Comment: thinking of the chromatic mediants as a circle is helpful, thank you! ascending roots of chromatic minor third mediants is: C, D#, F#, A, C. major third mediants is a bit smaller with: C, E, G#, C.
Answer: For me, I think the question of "getting to" a another step in the scale (For ex. IV to #v0 or V7 to a #vo ) is really a question of functional harmony not modes. The idea of functional harmony is that the music develops away from and back to the home key in a way that creates some tension and release.
In the case of the video the guy is using very traditional harmonic concepts with a lot of V7 dominant (on C dominant back to the key of F major). It is somewhere between neo romantic/classical and popular song (e.g. Hammerstein). He is using a traditional hummable melodic theme with development towards the dominant via vi and II7 (aka Vof V). He gets there by using Vof III (E7 to A- which gets to G7 to C7 which creates a strong motion back to F. I'm reminded of a slowed down "Surrey with the Fringe on the Top" in its harmonic feeling
Comment: \Yes he uses secondary dominants. He uses I7 (V of IV) to get to Bb as well. I was a little sloppy there in my notation, sorry.  I meant to notate #ivo and #vo as you had done with the o. o is the same as dim (diminished).
Comment: thanks for your answer, this is great stuff. so you're saying he uses a bunch of secondary dominants. What does #v0 or #vo mean?


Mongoose Array Field Can't Updating

Question: Here is my schema;
...
  group: [
    {
      type: mongoose.Types.ObjectId,
      ref: 'groups'
    }
  ],
...

I'am trying update data. I can update other fields but I can not update group field. My given data;
{
  name: 'John Wick',
  role: '631c8f39fb0d6300ebf2d0c1',
  group: [ '632c770cdabb9fbf70a84efa', '632c76e26fec98665363cc43' ]
}

Name and Role can update but group is not. What should I do?
Edit:
Here is my update code;
User.findOneAndUpdate({_id},{{
  name: 'John Wick',
  role: '631c8f39fb0d6300ebf2d0c1',
  group: [ '632c770cdabb9fbf70a84efa', '632c76e26fec98665363cc43' ]
}},{}, (err,doc) => err ? console.log(err) : null)

Comment: Did you copy the code that you are actually using? Because you have double `{{` for the second argument of the `findOneAndUpdate`.
Comment: @NeNaD yes I saw it just now. I was the problem solved now. Thnx for warning
Comment: Add the code that you are using for update to the question.
Comment: Welcome. I also added an answer, if some other people would have the same issue.
Answer: You have double {{ in the second argument of the query. That should be changed with single {:
User.findOneAndUpdate({ _id }, {
  // Data
})
``

Mongoose Array Field Can't Updating


How Do I Know Which Piano Hand Position in the Following Exercise?

Question: In the book "300 Progressive Sight Reading Exercises for Piano", we're taught to put our right thumb on "middle C" and the left pinky finger on "lower C". But exercise #25 is this:

Now I have two choices:

I can move my right thumb to play the B note, OR
I can start the piece with my index finger on middle C

When playing for the first time, I automatically moved my thumb to hit B. But then I saw a video on Youtube where the guy uses method (2) and places his finger on C instead!
So which is it? Piano threads on this forum asking the same question usually gets replies saying "Everyone's hands are different" or "There's no right way to play". This is not helpful advice! I have to use either one, or the other. Which one would you use, and why?
Edit: If you recommend (2) by placing the index finger on middle C, what will you do when a "G" suddenly appears? You'll have to reach out with your pinky finger to play it. Or will you shift your entire hand position back to "thumb on C"?
Comment: I guess the "progressive" sight reading book is focusing on you being able to make fingering choices yourself as you sight-read, but a method book would typically guide you through these choices, starting with thumb on C and eventually introducing a different hand position. By the way, note that fingering choices are themselves a skill that will grow "progressively." The choices you make today and the way you make them might be different than they will in a few years.
Comment: @AndyBonner Thanks for the response! But are all fingering choices equal? My instinct is to just cross my index finger over my thumb for the B note. How do I know what will cause me trouble later for the same piece of music? I mean right now, it's so simple I can probably play the whole piece with just one finger. But no-one will say that's ok! So what are the guidelines? Edit: What's a method book?
Comment: By "method book" I mean a book that focuses on teaching you everything about how to play an instrument. From its title, it sounds like the book you're using just focuses on the skill of sight-reading. There are several popular series of "piano methods"; in the Alfred series, for example, the books marked "Lesson" are the core instructional books.
Comment: If this weren't a lesson specifically teaching the use of the other hand to play the note, I'd say it doesn't matter so much, since there is otherwise nothing for the left hand to do.  In most music, the left hand is occupied with its own notes and might not be available to play those notes.  (If it were expected to play those with the left, they'd generally be marked in such a way to make that clear.)  But this being a training exercise, they probably have good reasons for telling you to do that, which might become more apparent in later lessons.
Answer: Especially when sight-reading, it's helpful to look ahead and plan your fingering. In this case, with such a short piece, it's easy to see that the B is the lowest note and G is the highest. (So we can't pick any one hand position that gives one note to each finger. We'll have to either do some stretching, or move our hand at some point.) We can also notice that there are two of those Bs in the first line and one near the end, and only one G in the piece, at the start of the second line, so maybe we'll need to move just before that G. We even have time to imagine trying out certain options before we start.
(With the disclaimer that my primary instrument is violin): I would start with 2 (index finger) on C, to be prepared for those Bs. I would prefer not to move my 1st finger (thumb) from C to B, simply because any time you play two notes in a row with the same finger, it creates a small gap between the notes as you move.
At the end of the first line, once we've gotten the Bs out of the way, I would prepare for the G by switching from 2 to 1 (from index to thumb) for the pair of C half notes. Finally, now that I have 1 on C, I'd be inclined to handle the final B by crossing my 2nd finger over my 1st as you describe (so that the last two measures are "3 2 1 2 1"). There are other valid options, including using a 4 for the E at the start of the next-to-last measure.
So why didn't I just cross over for the first "B" in the piece? Well, if we started with 1 on C, then the fingering of the second measure would be 1, cross over 2... then... 2 again for the D? That's even more awkward than moving 1 - 1 for adjacent notes. Sometimes, when sight-reading, we find ourselves having to live with awkward fingerings because we didn't notice what's coming, but it's helpful to look at least a few notes ahead and prepare. As you gain skill and familiarity it will become more and more unconscious.
By the way, let's address some of the non-answers you've gotten before when asking about "the best fingerings": Are all fingerings equal? No, of course not. You make a great example: yes, you could play the whole thing with one finger, but that would be an objectively bad fingering. Are some fingerings equal? Sure. Especially at more advanced levels, there are often multiple ways to solve technical challenges, or fingering choices that might rely on personal expressive decisions. But at more beginning, foundational levels, there are often simple, objective reasons that the most obvious fingering is the right choice. If this were a violin piece and was intended for a first-year student, I could confidently say there would be only one "right" fingering (although a more advanced student could well choose other options for expressive purposes).
Comment: This is exactly the right answer, IMO, but one criticism: I think you've buried the lead. The switch from finger 2 to 1 on the repeated C is the key to the solution and should be made more prominent.
Comment: @BhagwadJalPark it gets better. You'll recognize more and more situations/patterns and the various ways you handled them in the past. Until at a certain point you'll notice that for the easy stuff, you won't even need to "think" about it, you just automatically "know".
Comment: @BhagwadJalPark In the sight-reading part of ABRSM exams, candidates are "given half a minute to look through and, if they wish, try out all or any part of the test before they are asked to play it for assessment". Doesn't sound like a lot, but it is very different from 'blind'
Comment: Thanks for this! I guess I always thought of sight-reading as something you do blind, otherwise it's "cheating". But even so, it's a lot of thought I'm going to have to get used to!
Comment: @BhagwadJalPark When I judge auditions that include a sight-reading challenge, we allow auditioners to take a little while to look over the piece before starting (and this would often be a longer passage, like at least half a page). But all the time, especially as your reading skills get stronger, you give some part of your brain to what you're playing right this second, but some part (and your peripheral vision) to noticing what's coming in a measure or two!
Comment: I'm working through the next exercise, but I find I spend up to 10 minutes just working out the fingering, where the actual playing is just 20 seconds! I didn't want to flood StackExchange with this kind of thing, so I posted the question on Reddit with my observations in a comment below: https://www.reddit.com/r/piano/comments/q3k3z2/what_is_the_fingering_for_these_two_bars/ . It can't be this hard to finger two bars! Isn't there another way?
Comment: @BhagwadJalPark And indeed there is another way: trial and error. If you try a particular fingering, you'll quickly discover places where it might have left you with an uncomfortable stretch or an awkward maneuver. Every fingering is chosen for only one of two reasons: either it meets a practical need, making something easier, or it serves an expressive need. Also, as to flooding SE, there's a [chat room](https://chat.stackexchange.com/rooms/440/the-practice-room) associated with this SE where you can always bring up more conversational issues.
Comment: @BhagwadJalPark But ultimately you'll internalize these fingering challenges and their solutions by playing a lot of pieces of gradually increasing difficulty, preferably with practical fingerings provided. If you have no other source of instruction than a sight-reading book, I strongly recommend that you get a method book (and more strongly recommend a real teacher!).
Answer: Working out your optimum fingering is always going to be part of the practice regime.
Couple of points that crop up, referencing this particular piece.
The thumb is usually the most mobile of all the digits - it'll stretch further left and right than the others (although its length gives it other disadvantages).
So, it would follow that using it on C as a base (yes, base) note would work well, as when B comes along, it'll stretch down that extra key, no problem. Physically, all is well.
However - that then produces a problem. The C note prior needs to be held until that B is played. As a beginner, one may not even notice, but what has to happen is the C note played with thumb has to be let go, in order to play the B next. So the C gets cut off a little early. It'll sound like a mini-mistake. In bars 3/4 the same thing will happen.
So a solution is needed, to keep the playing smooth. That's where moving the hand to its left, meaning there's enough digits to cover the keys, will help. Still one-note-per-digit, but meaning at some point, probably bar 4, those Cs will be played using the index finger - or, if you like, play the 1st with index, and the 2nd with thumb, restoring the hand to its original position. But that then will depend on what's coming next...
Answer: For what it's worth, I'd start with 2 on C. In bar 4, play the first C with 2 and the second one with 1. Then, play the E at the beginning of bar 7 with 4.


Java - Recursively Permute List Without For Loops

Question: I want to create a different way of permuting a list like [apple, banana, orange] without using for loops recursively that will work for any size list and input etc. I already created one with using for loops, but I can't figure out myself without using for loops to solve the problem as this second part of solving a permutation without a for loops recursively is also going to be a question on our next exam (study guide I am reading) any idea how I would tackle this so I can see and understand how it works for the next exam question?
Comment: How about google "recursive", "permutation", "Java"?
Answer: You can emulate a loop by the following recursion:

do nothing for the empty list

otherwise

work on the first element
recurse, using the sublist that starts with the second element


ARC kills my method-local NSOpenSavePanelDelegate before I can use it. Is there a fix?

Question: I'm using my application delegate as my open-panel file filter. That looked like too many concerns, so I split the panel delegate code to a new class. When setting up my NSOpenPanel objects, I assign their delegate to an object I alloc/init right there.
I use -panel:validateURL:error:, which triggers when I press the "Open" button, to possibly say the given file isn't allowed. I get a crash, EXEC_BAD_ACCESS, instead. When I added init and dealloc methods to call NSLog, both lifetime methods are called before the panel opens.
Is there some non-unusual tweak to let the local object survive through the panel call and the block response? Or do I have to switch back to some sort of global delegate instance?
Answer: Are you using one of the asynchronous methods with a completion handler block, beginSheetModalForWindow:completionHandler: or beginWithCompletionHandler:? If so, just put a reference to your delegate object in the completion handler. For example, invoke -self on it in an otherwise useless statement.
Answer:
assign their delegate to an object I alloc/init right there.

Most delegate assignments are weak thus ARC is discarding it quickly.
Ask yourself the question "what has a strong reference to the delegate" or "who owns this object"
In your case it's nothing.
The easiest way to fix is to add the delegate as a property of the thing that is creating the panel.
@property MyDelegateObject *ownedDelegate;
Comment: This works, too. But it's saying that the delegate has to be relatively global to the method. Since I create multiple instances of this new location, I might as well move the delegate back to an app-global instance.
Comment: It depends. Are your file filters used anywhere other than your open panels? Use and discard objects are better than turning the app delegate into a dumping ground for all those things you don't know what to do with. Your instinct about SOC is very correct. you can always nil out the delegate when your panel is dumped.
Comment: My NSWindowController and NSDocumentController subclasses each have an `-openDocument:` action. Since the delegate is stateless and the document-controller is app-global, I moved the delegate to be a public property of the document-controller so any window-controller can grab it as needed.


Can a diver from 10 m. sustain injury hitting the pool bottom?

Question: An Olympic diving pool is min 5.03 m deep. A diver from 10 m enters the water in "perfect pencil shape" and maintains this shape in the water without "breaking" the dive.
Can this diver sustain injury from hitting the bottom of the pool with enough speed? Have such injuries occurred?
If so, why don't they increase pool min depth?
Answer: Wikipedia seems to have reliable information:

Diving from 10 m and maintaining a downward streamlined position results in gliding to a stop at about 4.5 – 5m.


problem with R enconding

Question: Me pediram para fazer análises de textos e estou tendo problema com a codificação, alguém sabe como posso converter esses strings com acento diretamente?
Exemplo de como esta aparecendo o arquivo:
vocês dizerem que não!!! Até quando

Outro exemplo:
â¤ï¸(...) Comilanças é amigo secreto na casa clean!ðŸŽ

Já tentei utilizar essa função:
stringi::stri_enc_detect(dados$text)

e obtive essa saída:
    [[1]]$Encoding
    [1] "UTF-8"        "windows-1252" "windows-1250" "UTF-16BE"     "UTF-16LE"     "Shift_JIS"    "windows-1254"
    [8] "IBM420_ltr"

    [[1]]$Language
    [1] ""   "pt" "cs" ""   ""   "ja" "tr" "ar"

    [[1]]$Confidence
    [1] 1.00 0.63 0.28 0.10 0.10 0.10 0.02 0.01

Se alguem puder ajudar serei grato!
Comment: Qual o resultado quando você usa `Sys.getlocale()`?
Comment: Opa, o resultado foi o seguinte:
Comment: [1] "LC_COLLATE=Portuguese_Brazil.1252;LC_CTYPE=Portuguese_Brazil.1252;LC_MONETARY=Portuguese_Brazil.1252;LC_NUMERIC=C;LC_TIME=Portuguese_Brazil.1252"
Answer: Talvez o problema esteja já na importação. Como você está importando os arquivos? Quando o default não funciona corretamente eu costumo tentar definindo encoding = "UTF8".
Tenta:
read.csv("nomedoarquivo.csv", encoding = "UTF-8")
Qualquer coisa tenta ler aqui:
http://people.fas.harvard.edu/~izahn/posts/reading-data-with-non-native-encoding-in-r/
Comment: Muito obrigado!

problem with R enconding


SyntaxError: Unexpected reserved word => prettier/third-party.js

Question: I'm pretty new to Node, npm and webpack. I'm trying to set up a Craft 3 environment with Tailwind css.
Everything worked fine out of the box, but when i run npm run dev i get the following error:
> email@example.com dev /Users//sites/***/www
> gulp dev

/Users/***/sites/***/www/node_modules/prettier/third-party.js:9871
      for await (const place of this.config.searchPlaces) {
          ^^^^^

SyntaxError: Unexpected reserved word
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:616:28)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/Users/***/sites/***/www/node_modules/prettier/index.js:16551:18)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! email@example.com dev: `gulp dev`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the firstname.lastname@example.com dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/***/.npm/_logs/2020-08-28T14_23_16_034Z-debug.log

Why is this hapening and how can i make sure i can fix this in the furure?
Comment: What's your version of node ?
Comment: Have you written any code?
Comment: I updated/added/removed some Craft plugins. But did not write or touched any kind of css/js yet.
Comment: are you importing the Craft 3 package into your code?
Comment: @KiJéy i'm running node at v8.11.3
Comment: @Ramon node 8 doesn't support this syntax (`for await... of`) you need Node 10.0.0 or later : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of
Comment: @KiJéy This was the problem, thanks. Works fine now!
Comment: @Ramon then please check my answer as valid so that people can find this as a resolved issue :)
Answer: As described here : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of
This syntax :
for await (const place of this.config.searchPlaces) {
  // ...
}

is available in NodeJS starting version 10.0.0
Answer:
I faced same issue first I tried with upgrading node v8 --> node v10 works fine.

If you do not want to upgrade your node version you can downgrade prettier version to email@example.com This fix is also working properly.

Downgrade prettier version:
npm i -D firstname.lastname@example.com

More info: https://dev.to/shivampawar/syntaxerror-unexpected-reserved-word-prettierthird-partyjs-3ph7
Answer: I had the same issue in node v8.11.2. Upgraded node to version 12.3.1 and it works fine
Answer: I know it's late but for people coming here, you can either use node v10 or downgrade prettier to v1.x.x.
If any package throws an unexpected error like this please check it's package.json on github or from node_module and look for engines
"engines": {
    "node": ">=8"
},

make sure it matches your node, either change (upgrade) the node version if possible or use a different (older) package version. You can check which package version is suitable by changing the version from dropdown for this file.


'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync

Question:
.Net Core 1.0.0 - SDK Preview 2 (x64)
.Net Core 1.0.0 - VS "15" Preview 2 (x64)
.Net Core 1.0.0 - Runtime (x64)

So, we updated an RC1 app to the latest versions above. After many hours of switching references, it's running. However, when logging in (AccountController/Login), I am getting an error at:
public class AccountController : BaseController
{
    public UserManager<ApplicationUser> UserManager { get; private set; }
    public SignInManager<ApplicationUser> SignInManager { get; private set; }
    private readonly IEmailSender EmailSender;

    public AccountController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, IEmailSender emailSender)
    {
        UserManager = userManager;
        SignInManager = signInManager;
        EmailSender = emailSender;
    }

    // GET: /Account/Login
    [HttpGet]
    [AllowAnonymous]
    public IActionResult Login(string returnUrl = null)
    {
        ViewBag.ReturnUrl = returnUrl;
        return View();
    }

    //
    // POST: /Account/Login
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Login(ViewModels.Account.LoginViewModel model, string returnUrl = null)
    {
        if (ModelState.IsValid)
        {
            // Errs this next line
            var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, false); // <-- ERRS HERE '.PasswordSignInAsync'
            if (result.Succeeded)
                return RedirectToLocal(returnUrl);

            ModelState.AddModelError("", "Invalid email or password.");
            return View(model);
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

It blows up with the following error message:

InvalidOperationException: No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.

Here is the Startup.cs:
public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

        // Add EF services to the services container.
        services.AddEntityFrameworkSqlServer()
           .AddDbContext<LogManagerContext>(options =>
              options.UseSqlServer(Configuration["Data:DefaultConnection:Connectionstring"]));

        services.AddSingleton(c => Configuration);

        // Add Identity services to the services container.
        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<LogManagerContext>()
            .AddDefaultTokenProviders();

        // Add MVC services to the services container.
        services.AddMvc();

        services.AddTransient<IHttpContextAccessor, HttpContextAccessor>();

        //Add all SignalR related services to IoC. - Signal R not ready yet - Chad
        //services.AddSignalR();

        //Add InMemoryCache
        services.AddMemoryCache();

        services.AddSession(options =>
        {
            options.IdleTimeout = System.TimeSpan.FromHours(1);
            options.CookieName = ".LogManager";
        });

        // Uncomment the following line to add Web API servcies which makes it easier to port Web API 2 controllers.
        // You need to add Microsoft.AspNet.Mvc.WebApiCompatShim package to project.json
        // services.AddWebApiConventions();
        // Register application services.
        services.AddTransient<IEmailSender, AuthMessageSender>();

    }

    // Configure is called after ConfigureServices is called.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseSession();

        // Configure the HTTP request pipeline.
        // Add the console logger.
        //loggerFactory.MinimumLevel = LogLevel.Information; - moved to appsettings.json -chad
        loggerFactory.AddConsole();
        loggerFactory.AddDebug();

        loggerFactory.AddNLog();

        // Add the following to the request pipeline only in development environment.
        if (env.IsDevelopment())
        {
            app.UseBrowserLink();
            app.UseDeveloperExceptionPage();
            //app.UseDatabaseErrorPage(DatabaseErrorPageOptions.ShowAll);
        }
        else
        {
            // Add Error handling middleware which catches all application specific errors and
            // sends the request to the following path or controller action.
            app.UseExceptionHandler("/Home/Error");
        }

        env.ConfigureNLog("NLog.config");

        // Add static files to the request pipeline.
        app.UseStaticFiles();

        // Add cookie-based authentication to the request pipeline.
        app.UseIdentity();

        //SignalR
        //app.UseSignalR();

        // Add MVC to the request pipeline.
        app.UseMvc(routes =>
        {
            routes.MapRoute(
             name: "default",
             template: "{controller}/{action}/{id?}",
             defaults: new { controller = "Home", action = "Index" }
             );

            // Uncomment the following line to add a route for porting Web API 2 controllers.
            // routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
        });
    }

And here's the Context:
public class ApplicationUser : IdentityUser
{
    // Add Custom Profile Fields
    public string Name { get; set; }
}

public class LogManagerContext : IdentityDbContext<ApplicationUser>
{
    public DbSet<LogEvent> LogEvents { get; set; }
    public DbSet<Client> Clients { get; set; }
    public DbSet<LogEventsHistory> LogEventsHistory { get; set; }
    public DbSet<LogEventsLineHistory> LogEventsLineHistory { get; set; }
    public DbSet<LogRallyHistory> LogRallyHistory { get; set; }
    public DbSet<Flag> Flags { get; set; }
    protected override void OnModelCreating(ModelBuilder builder)
    {

        builder.Entity<LogEvent>().HasKey(x => x.LogId);
        builder.Entity<LogEvent>().ToTable("LogEvents");
        builder.Entity<Client>().HasKey(x => x.ClientId);
        builder.Entity<Client>().ToTable("Clients");
        builder.Entity<LogEventsHistory>().HasKey(x => x.HistoryId);
        builder.Entity<Flag>().HasKey(x => x.FlagId);
        builder.Entity<Flag>().ToTable("Flags");
        builder.Entity<LogRallyHistory>().HasKey(x => x.HistoryId);
        builder.Entity<LogEventsLineHistory>().HasKey(x => x.LineHistoryId);

        base.OnModelCreating(builder);
    }

Answer:
If AddDbContext is used, then also ensure that your DbContext type
accepts a DbContextOptions object in its constructor and passes it to
the base constructor for DbContext.

The error message says your DbContext(LogManagerContext ) needs a constructor which accepts a DbContextOptions. But I couldn't find such a constructor in your DbContext. So adding the below constructor probably solves your problem.
public LogManagerContext(DbContextOptions options) : base(options)
{
}

Edit for comment
If you don't register IHttpContextAccessor explicitly, use below code:
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

Comment: Can you try to register IHttpContextAccessor? see https://github.com/aspnet/Mvc/issues/3936
Comment: services.AddSingleton();
services.AddSingleton();
adding this to the Startup.cs fixed it. Thanks. If you want to repost that link I'll mark it as answer.
Comment: ok, so I added that to the LogManagerContext.cs and now I get a different error with even less info:
InvalidOperationException: HttpContext must not be null.
get_Context
And I still cannot step into the .PasswordSignInAsync method either
Comment: @BeauD'Amore, shouldn't that be `services.addScoped` ?  A singleton would share state between requests and possible users.
Comment: @NathanGoings `HttpContextAccessor` is a factory method and gives you access to the current http context within the service where it is inserted to.
Answer: I could resolve it by overriding Configuration in MyContext through adding connection string to the DbContextOptionsBuilder:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
               .SetBasePath(Directory.GetCurrentDirectory())
               .AddJsonFile("appsettings.json")
               .Build();
            var connectionString = configuration.GetConnectionString("DbCoreConnectionString");
            optionsBuilder.UseSqlServer(connectionString);
        }
    }

Install these packages if the methods SetBasePath or AddJsonFile are not recognized :

Microsoft.Extensions.Configuration.FileExtensions
Microsoft.Extensions.Configuration.Json
Comment: If you are missing `SetBasePath` or `AddJsonFile`, install those packages:
`Microsoft.Extensions.Configuration.FileExtensions`
`Microsoft.Extensions.Configuration.Json`
Comment: @alhpe It is awesome to say that do not hard code connection strings there as it will leak a security issue. Probably, you could have mentioned what the alternative solution should be.
Comment: please do not hard code connections string on OnConfiguring.. this will leak a security issue
Comment: Use an OS environment variable and read it on your application
Comment: Nice, I forgot maybe the most important line : `optionsBuilder.UseSqlServer(connectionString);`
Comment: I think this is not a good solution. There must be another way to inject this configuration. It will be wonderful if someone may provide a proper way
Comment: Well, this is not a good solution but if you are in hurry, then it can work. Best would be to create the DBcontext in the Startup.cs in the Startup core project and then inject from there.
Comment: thanks, this is the easiest out-of-the-box solution when using the VS2019 ASP.NET Core MVC template
Comment: If you are missing UseSqlServer, install the package: Microsoft.EntityFrameworkCore.SqlServer
Comment: I used IDesignTimeDbContextFactory to migrate the db in the project folder, and use the db in the bin folder at execution. When I started to use IdentityDbContext and IHost, the migration happened in the bin folder. The suggested solution worked for me.
Comment: This problem appeared for me in a mature .NET 6 application after changing a `Dictionary<,>` to a `SortedList<,>` in a referenced NuGet library. I reverted the change back, but this made it work with the `SortedList<,>`
Comment: This should be the first thing to try, for some reason the core6 pattern refuses to respect the configuration if done at the app builder side and the override that the EF scaffold tool creates is insufficient.
Answer: This is the solution i found.
https://github.com/dotnet/EntityFramework.Docs/blob/main/entity-framework/core/dbcontext-configuration/index.md
Configure DBContext via AddDbContext
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<BloggingContext>(options => options.UseSqlite("Data Source=blog.db"));
}

Add new constructor to your DBContext class
public class BloggingContext : DbContext
{
    public BloggingContext(DbContextOptions<BloggingContext> options)
      :base(options)
    { }

    public DbSet<Blog> Blogs { get; set; }
}

Inject context to your controllers
public class MyController
{
    private readonly BloggingContext _context;

    public MyController(BloggingContext context)
    {
      _context = context;
    }

    ...
}

Comment: Thank you Ozan, you are the first person I have found who has mentioned injecting the context into the controller. Have a great day!
Comment: Yes, no one actually points out this ONLY works via injection, and your back end classes can't see that injection unless they're injected. So any backend usage of the context fails even though it looks like you've done everything right.
Comment: It still gives the same error. I had no controllers in my API (Data, Application and Domain are separated into projects), so I added and nothing changed.
Answer: I know this is old but this answer still applies to newer Core releases.
If by chance your DbContext implementation is in a different project than your startup project and you run ef migrations, you'll see this error because the command will not be able to invoke the application's startup code leaving your database provider without a configuration. To fix it, you have to let ef migrations know where they're at.
dotnet ef migrations add MyMigration [-p <relative path to DbContext project>, -s <relative path to startup project>]
Both -s and -p are optionals that default to the current folder.
Comment: We also have the `DbContext` in a different project and as a workaround the EntityFrameworkCore.Design package was added to the Startup project (where it actually was not needed). With the -s parameter there is no need for the workaround
Answer: In addition to the accepted answer, if anyone still getting the error even after doing followings correctly:

In Startup.cs : services.AddDbContext<ApplicationDbContext>(options => ... )
In ApplicationDbContext.cs : public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options){}

Check that DbContext class does not have any parameterless public constructor (need to delete it if any). FYI, you might be added parameterless public constructor for some reason i.e. Scaffolding DbContext.
Details (article that I wrote in my site): ASP.Net Core troubleshooting
Answer: I had this error despite having constructor with DbContextOptions parameter. Error showed up, when i changed solution startup from one to multiple projects. Check if you don't have multiple startup project in Solution -> Right Click -> Properties-> Common Properties -> Startup Project.
Comment: This solution solved my problem
Comment: just so you know, i logged in into my stackoverflow after 10 years only to upvote your answer because i lost like 2 hours on this newbie error. thanks pal !
Answer: In my case, a fresh .NET6 Web API, the Scaffold-DbContext command added 2 Constructors like this:
 public BookStoreDbContext()
    {
    }

    public BookStoreDbContext(DbContextOptions<BookStoreDbContext> options)
        : base(options)
    {
    }

Just remove the first one and it should work.
Answer: Hi there I came across this question and my case is a little bit different
I try to test my AppDbContext file in not asp dot net core web application
so there is no a Dependency Injection to handle the step of adding a specific provider such as SQLServer so my solution is to override the following function in AppDbContext file:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    private string conn = "Server=servername;Database=dbName;Trusted_Connection = True; MultipleActiveResultSets = true";

    if (!optionsBuilder.IsConfigured)
       {
                optionsBuilder.UseSqlServer(conn);
       }
}

in case you use the entity framework core with asp dot net web application you should add this configuration in the startup file in the ConfigureServices function  as follows :
public void ConfigureServices(IServiceCollection services)
        {

            // name of your dbcontext file
            services.AddDbContext<AppDbContext>(option =>
            option.UseSqlServer(Configuration.GetConnectionString("AlternativeConnection")));
            services.AddControllersWithViews();

        }

Answer: if you are using top-level statement Program.cs make sure builder.Services.AddDbContext<> line is declared before this line:
var app = builder.Build();

Answer: Override constructor of DbContext
Try this :-
public DataContext(DbContextOptions<DataContext> option):base(option) {}

Answer: I experienced this issue using EF Core 6:

1st, I added a constructor without parameter in the context file

2nd, I overrided the OnConfiguring method in the same context file as follow:
  protected override void OnConfiguring(DbContextOptionsBuilder options)
  => options.UseSqlServer("MyConnectionString");

Then run the migration

It worked well.
Answer: I simply had the wrong credentials. Classic confusing error message.
Answer: I just had this same error when adding a new controller to my project, I solved it by entering the AppSetting, it had an extra "}" in the Json and this was generating the error, which would not let me make the connection.
I leave my humble contribution :) greetings
Answer: In my case I was reworking some projects, and moved a lot of files.
The problem for me was, that I was missing:
<OutputType>Exe</OutputType>

on the property group.

And thus startup.cs / program.cs did not be hit because its not flagged as an executing assembly.
So running the following without the missing reference:
dotnet ef migrations add {name} -c {my-context}

Resulted in the following error:
System.InvalidOperationException: No database provider has been configured for this DbContext.

After I added the reference the migrations succeeded. Silly mistake, but still a valuable lesson learned :)
Answer: For me the problem was that I had this
builder.Services.AddHttpContextAccessor();
before this
.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(configuration.GetConnectionString("Default")));.
Put builder.Services.AddHttpContextAccessor(); just before builder.Build() and all went well.
Answer: I just moved
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

and
builder.Services.AddDbContext<...Context>(options =>

immediately after
var builder = WebApplication.CreateBuilder(args);

in .NET6/8 and it runs perfectly.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


When is $1234x6789$ divisible by $9$

Question: I've been asked to find all values of $x$ such that $1234x6789$ is divisible by $9$
I feel that I'm supposed to use modulo or bases but I have no real direction.
Comment: For an integer to be divisible by 9, its digit sum is also divisible by 9.
Comment: There's 10 possible digits. Why don't you just try them?
Comment: Is $x$ supposed to be single digit, or can it be a sequence of digits of arbitrary length?
Answer: Theorem:  If a $y \in \mathbb{N}$ is divisible by $9$, then the sum of the digits of $y$ is divisible by $9$.
Proof: We are assuming that $y \equiv 0 \pmod{9}$.  Write $y = \displaystyle \sum_{k=0}^n c_k10^k$ for $c_k \in \{1, 2, ...,9 \}$ and apply rules of modular arithmetic: because $10 \equiv 1 \pmod{9}$, we arrive at $\displaystyle \sum_{k=0}^n c_k \equiv 0 \pmod{9}$.
Note that these steps are reversible, so this is an if and only if criterion.
Answer: The sum of all digits should be divisible by 9.
Note that $10^n\equiv 1$ (mod $9$) for all $n$.
Answer: Let $\overline{abcd}\in\mathbb{N}$  and  $9\mid\overline{abcd}$. This implies that $9\mid(a+b+c+d)$. Similar proof, but with 3.
Knowing the rule, we now must calculate the constant sum of digits of $\overline{1234x6789}$ (excluding $x$), which we denote $s$:$$s=(\sum_{k=1}^{9}k) - 5 = \frac{9 \cdot10}{2} - 5 = 40$$
Now, we should use the divisibility theorem for $9$, in our case:$$9\mid\overline{1234x6789}\implies9\mid (s+x)\tag1$$
The minimum value of $(s+x)$ is $40$, for $x=0$ and the maximum value of $(s+x)$ is 49, for $x=9$. $$(s+x)\in[40;49]\tag2$$
From (1),(2) and knowing that the only natural multiple of $9$ in the range $[40;49]$ is obviously $45$: $$(s+x)=45\implies x = 45-s\implies x=5$$
Thus, $x\in \{5\}$.

When is $1234x6789$ divisible by $9$


Is Writing a Semi Group?

Question: While writing this question, I compose letters from a set $L=\{a,...z,A,...Z\}\cup\{\;\text{   } \;\}$.  Writing has a binary operation which is associative. The result always is an element of $L^n$.
  Does this mean that Writing is a semi group?
Comment: [Strings form a monoid](https://en.wikipedia.org/wiki/Free_monoid), if that's what you're asking.
Comment: From Wikipedia: "Monoids are studied in semigroup theory as they are semigroups with identity".
Comment: Minor point: for it to be a monoid you need "not writing anything" to count as writing (as otherwise you have no identity).
Answer: The answer is yes, but as Rahul pointed out it's even a monoid. From the Wikipagepage:

In other words, a monoid is a semigroup with an identity element. It can also be thought of as a magma with associativity and identity.

I also found this nice figure:
$\hskip0.7in$

Is Writing a Semi Group?


Identical arrays in .NET API endpoint response

Question: Let's take for example this endpoint I have,
[HttpGet("persons/{personId:guid}/profile/organizations/coordinates")]
public async Task<Result<List<ProfileCoordinateViewModel>>> GetProfileCoordinates(Guid personId)
{
    try
    {
        var coordinates = await _profileCoordinateService.GetProfileCoordinates(personId);

        var result = new List<ProfileCoordinateViewModel>();

        foreach (var item in coordinates)
        {
            result.Add(ProfileCoordinateViewModel.FromDomainObj(item));
        }

        return Result.Ok(result);
    }
    catch (Exception ex)
    {
        return Result.Fail("Something went wrong: ")
            .WithError(ex.ToString());
    }
}

For the result that is being returned I am using FluentResults. It returns the following response:
{
  "valueOrDefault": [
    {
      "email1": "firstname.lastname@example.com",
      "email1IsPublic": false,
      "email2": null,
      "email2IsPublic": false,
      "fax": null,
      "faxIsPublic": false,
      "mobile": null,
      "mobileIsPublic": false,
      "palaceBox": null,
      "palaceBoxIsPublic": false,
      "phone": null,
      "phoneIsPublic": false
    }
  ],
  "value": [
    {
      "email1": "email@example.com",
      "email1IsPublic": false,
      "email2": null,
      "email2IsPublic": false,
      "fax": null,
      "faxIsPublic": false,
      "mobile": null,
      "mobileIsPublic": false,
      "palaceBox": null,
      "palaceBoxIsPublic": false,
      "phone": null,
      "phoneIsPublic": false
    }
  ],
  "isFailed": false,
  "isSuccess": true,
  "reasons": [],
  "errors": [],
  "successes": []
}

I want the response to only contain isSuccess/isFailed (depending on which is true) and a single result; not both the value and valueOrDefault objects. I'm guessing it has to do with FluentResults because my repository and service return correctly. Is there any way I can change this?
Answer: It will be a long , but I will give a detailed explanation. And I think it will work for you in the end. In Order to do this ,Let's create a 2 interface

IResult => If you want to return just Success or Message

IDataResult=>If you want to return Success or Message with data
public interface IResult
{

public bool Success { get; }
public string Message { get;}

}

This is IDataResult
   public  interface IDataResult< out T>:IResult
{
    T Data { get; }
}

We are creating a class which is going to abstract IResult;
public class Result : IResult
{
    public Result(bool success)
    {
        Success=success;
    }

    public Result(bool success,string message):this(success)
    {

        Message=message;
    }
    public bool Success { get ; }
    public string Message { get ; }
}

}
Ok now if we want to return just message or success,use SuccessResult class
  public  class SuccessResult:Result
  {
  public SuccessResult():base(true)
  {

  }

  public SuccessResult(string message) : base(true,message)
  {

  }
  }

if you want to return just message or success also with data use SuccessDataResult class
    public class SuccessDataResult<T> : DataResult<T>
{
    public SuccessDataResult(T data) : base(data, true)
    {

    }

    public SuccessDataResult(T data,string message) : base(data, true,message)
    {

    }

}

in Your business or Service Layer you can do like this ;
if I want to return just Message or Success:
        public Result Add(Category category)
    {
        _categoryDal.Add(category);

        return new Result(true, "A new Record Has Added");
    }

If I need to return a data with Success or message,you can use like this ;
        public IDataResult<Category> Get(int id)
    {
        return new SuccessDataResult<Category>(_categoryDal.Get(a => a.Id
         == id),Messages.Get_Record);
    }

Thanks to this structure result always return true,false,message or data. By the way you can create ErrorResult,ErrorDataResult like SuccessResult. The structure will provide this.
    [Authorize(Roles = "admin")]
    public IActionResult Add(Category category)
    {
        var result = _categoryService.Add(category);

        if (result.Success)
        {

            return Ok(result);
        }

        return BadRequest(result.Message);
    }


How to unpublish a node and any related nodes?

Question: I am currently working on a problem where, when a Physician node has been unpublished, its related Review nodes will be unpublished as well. They do have an entity reference built in to distinguish which Review belongs to which Physician.
I have been working with the Rules, Views Bulk Operations (VBO), and Workflow modules to get this to work.
I have many failed attempts using the Rules module, so I don't have any code to supply.
Would anyone be able to point me in a direction?
Answer: Yes this seems perfectly possible with Rules ... In your case, the crucial part of such rule is a Rules Action to perform a Loop. If you're not familiar with such loops, then I strongly recommend to have a look at the tutorial titled "Lists and loops".
In your case, you should use (at least) have a Rules Action to create a loop related to your 'related "Review" nodes' (as in your question). After you do, you should iterate over each item in that list. And for each iteration you should then perform a Rules Action to "unpublish the review being processed in the loop".
Done
PS 1: Refer to my answer to "How to set multiple values to an unlimited Term Refence field with Rules" for some sample rules that are like a variation of your question here.
PS 2: I assume this is about D7 ...
Comment: Thank you for the great direction! I will give this a go for sure. And yes this is D7, definitely should have added that.
Comment: Excellent! Got the appropriate tag on there and checked your response as the best answer.
Comment: @NickGordon: merci for the "accept", and the update of your question ... PS: if you have additional questions later on about all this: get back to here!


Problema com um atributo string de um objeto

Question: Olá!
Estou tendo um problema com um membro do tipo string do meu objeto. Quando eu faço a atribuição objeto.palavra = "alguma palavra", o programa até compila e roda, mas quando eu imprimo o conteúdo, aparece símbolos totalmente diferentes.
Aqui o codigo main:
#include "palavra.h"
#include <iostream>
#include <string>

using namespace std;

int main()
{
    Palavra p1;
    Palavra p2;

    p1.palavra = "abc";
    p2.palavra = "Olani";

    printf("%s, %s\n", p1.palavra, p2.palavra);

    return(0);
}

Palavra.cpp:
#include "palavra.h"
#include <iostream>

//passar a arvore
Palavra Palavra::palavrasemelhante(const Palavra& p1, const Palavra& p2)
{
    //se for igual as duas primeiras letras entao sao semelhantes
    if(p1.palavra[0] == p2.palavra[0])
    {
        if(p1.palavra[1] == p2.palavra[1]){
            return (p2);
        }
    }
    return (p1);
}

const string Palavra::getString()
{
    //retornar palavra para comparação de igual igual
    return (this->palavra);
}

//sobrecarga de operador == para comparar dois objetos da classe Palavra
bool Palavra::operator == (Palavra &p2)
{
    //palavra==p2.getstring ou desse jeitoif ( 0 == strcmp(palavra, p2.getString()))
    if (palavra == p2.getString())
        return (true);

    else
        return (false);

}

e Palavra.h:
#include <iostream>
#include <string>

using std::string;

class Palavra
{
    private:
        //int tamanho;
        //string palavra;

    public:
        Palavra palavrasemelhante(const Palavra &p1, const Palavra &p2);
        bool operator==(Palavra &p2);
        const string getString();
        string palavra;
};

Ao compilar e executar nenhum erro é apontado, mas quando vejo o conteudo fica assim:

Obrigado pela ajuda!
Comment: Uma classe `Palavra` que encapsula um atributo `string palavra` para fazer `palavra.palavra` parece bastante estranho no minimo. Porque não simplificar e utilizar duas `strings` normais ? Isto até evitava ter que definir o operador `==` que acabou complicando ainda mais, e o mesmo para o `tamanho` que já obtem diretamente da `string` com `size()`. Ou seja resumindo, qual o objetivo de toda esta abstração/complicação ?
Answer: A questão está em que você está a utilizar printf para mostrar o que seria uma string em C puro, ou seja um char*, mas na verdade você tem uma std::string e não um char*.
Este problema é visível quando compila. Veja o aviso que eu obtenho referente a esta linha:
printf("%s, %s\n", p1.palavra, p2.palavra);

||=== Build: Debug in TestC++ (compiler: GNU GCC Compiler) ===|
...main.cpp|60|warning: format '%s' expects argument of type 'char*'...
...main.cpp|60|warning: format '%s' expects argument of type 'char*'...
||=== Build finished: 0 error(s), 2 warning(s) (0 minute(s), 1 second(s)) ===|

Minimizei as mensagens do compilador só ao que é relevante
Consegue resolver mantendo o printf com %s mas para isso precisar de aceder ao array de chars que está dentro da std::string através do método c_str:
printf("%s, %s\n", p1.palavra.c_str(), p2.palavra.c_str());
//                             ^---                ^---

Veja a funcionar no Ideone
Uma abordagem mais em linha com C++ seria utilizar cout, pois esse foi desenhado para lidar com std::string:
cout << p1.palavra << ", " << p2.palavra << endl;

Veja também este exemplo no Ideone
Como nota final, veja o que eu comentei. Você neste momento tem uma classe com vários métodos que literalmente guarda apenas uma string, e acaba por estar a replicar lógica que já existe na string. Se apenas precisa da palavra então simplifique e use uma string normal e crie uma função normal para o palavrasemelhante. Dessa forma não só sera mais simples como mais natural.
Comment: Muito Obrigado! Como estou muito acostumado a programar só com C, esqueci desses detalhes do c++. Vou arrumar a classe segundo suas dicas. obrigado novamente!


Selecionar valores de outra tabela com mais de uma linha no WebSQL

Question: Estou usando Ionic + cordova + WebSql.
Tenho basicamente essas tabelas, parceiros e parceriroEnderecos. Na tabela de endereços pode conter mais de uma linha para cada parceiro.
Como faço para retorna esses valores?
Crio as tabelas assim:
databaseValues.setup();
  databaseValues.bancoDeDados.transaction(function(transacao) {
  transacao.executeSql('CREATE TABLE IF NOT EXISTS parceiroEnderecos (' +
    'parceiro_id INTEGER,' +
    'logradouro VARCHAR(200),' +
    'numero VARCHAR(10),' +
    'UNIQUE(parceiro_id, logradouro) ON CONFLICT IGNORE);', []
  );

  transacao.executeSql('CREATE TABLE IF NOT EXISTS parceiros (' +
    'id INTEGER NOT NULL PRIMARY KEY,' +
    'nome_fantasia VARCHAR(300),' +
    'UNIQUE(id, nome_fantasia) ON CONFLICT IGNORE);', []
  );
});

No ParceirosController eu estou tentando fazer assim:
databaseValues.setup();
databaseValues.bancoDeDados.transaction(function(transacao) {
  transacao.executeSql('select * from parceiros', [], function(transacao, parceiros) {
    for (parceiro of parceiros.rows) {
      _enderecos = getParceiroEnderecos(parceiro.id);
      _parceiro = {
        id: parceiro.id,
        nome_fantasia: parceiro.nome_fantasia,
        avatar: parceiro.avatar,
        beneficio_qtd: parceiro.beneficio_qtd,
        beneficio_maior: parceiro.beneficio_maior,
        enderecos: _enderecos
      }
      $scope.parceiros.push(_parceiro);
    }
  });
});

getParceiroEnderecos = function(parceiro_id) {
  _enderecos = [];
  databaseValues.setup();
  databaseValues.bancoDeDados.transaction(function(transacao) {
    transacao.executeSql('select * from parceiroEnderecos where parceiro_id = ?;', [parceiro_id], function(transacao, enderecos) {
      _enderecos = [];

      for (endereco of enderecos.rows) {
        _endereco = {
          logradouro: endereco.logradouro,
          numero: endereco.numero
        }
        _enderecos.push(_endereco);
      }
    });
    return _enderecos;
  })
}

Só que como a transacao deve ser assíncrona, eu não consigo adicionar o endereço dentro do parceiro, algo assim:
parceiros = [
  {
    id: 1,
    nome_fantasia: 'empresa 1',
    enderecos: [
      {
        logradouro: 'Rua 1',
        numero: '123'
      },
      {
        logradouro: 'Rua 2',
        numero: '987'
      }
    ]
  }
]

Comment: Alguma das resposta lhe foi útil? Não esqueça de escolher uma e marcar o ✅ para que possa ser utilizada caso alguém tenha uma dúvida similar!
Answer: Você deve trabalhar com promessas de modo assíncrono da seguinte forma:
databaseValues.setup();
databaseValues.bancoDeDados.transaction(function(transacao) {
  transacao.executeSql('select * from parceiros', [], function(transacao, parceiros) {
    for (parceiro of parceiros.rows) {
      getParceiroEnderecos(parceiro.id).then(function(_enderecos) {
        _parceiro = {
          id: parceiro.id,
          nome_fantasia: parceiro.nome_fantasia,
          avatar: parceiro.avatar,
          beneficio_qtd: parceiro.beneficio_qtd,
          beneficio_maior: parceiro.beneficio_maior,
          enderecos: _enderecos
        }

        $scope.parceiros.push(_parceiro);
      })
    }
  });
});

getParceiroEnderecos = function(parceiro_id) {
  var promessa = $q.defer();

  _enderecos = [];
  databaseValues.setup();
  databaseValues.bancoDeDados.transaction(function(transacao) {
    transacao.executeSql('select * from parceiroEnderecos where parceiro_id = ?;', [parceiro_id], function(transacao, enderecos) {
      _enderecos = [];

      for (endereco of enderecos.rows) {
        _endereco = {
          logradouro: endereco.logradouro,
          numero: endereco.numero
        }
        _enderecos.push(_endereco);
      }
    });

    promessa.resolve(_enderecos);
  });

  return promessa.promise;
}

Neste caso utilize a biblioteca $q para gerar a promessa a ser resolvida na função getParceiroEnderecos.
Comment: https://codepaste.net/xbphfd
No primeiro console.log só exibe um único id, no segundo console.log, todos ficam com o mesmo id


how to save the button state recyclerview

Question: Good days, I am writing an android program for online coupon service. I am currently creating a page that allows user to bookmark the item. Then after that they can see it in their bookmarks folder. The problem I am encountering is after the bookmark is clicked and selected for the specific item. but when i scroll up the selected bookmark becomes deselected state. How can I prevent that from happening. Below is my code
Coupon.java
public class Coupon {
    private String company_name;
    private String offer_desc;

    public Coupon() {

    }

    public Coupon(String company_name, String offer_desc) {
        this.company_name = company_name;
        this.offer_desc = offer_desc;
    }

    public String getCompany_name() {
        return company_name;
    }

    public void setCompany_name(String company_name) {
        this.company_name = company_name;
    }

    public String getOffer_desc() {
        return offer_desc;
    }

    public void setOffer_desc(String offer_desc) {
        this.offer_desc = offer_desc;
    }

}

CouponViewHolder.java
public class CouponViewHolder extends RecyclerView.ViewHolder{
    protected TextView company_name;
    protected TextView offer_desc;
    protected LikeButton star_button;
    protected LikeButton heart_button;

    public CouponViewHolder(final View item){
        super(item);
        company_name = (TextView) item.findViewById(R.id.company_name);
        offer_desc = (TextView) item.findViewById(R.id.offer_desc);
        star_button = (LikeButton) item.findViewById(R.id.star_button);
        heart_button = (LikeButton) item.findViewById(R.id.heart_button);
    }

}

CouponAdapter.java
public class CouponAdapter extends RecyclerView.Adapter<CouponViewHolder>{

    private List<Coupon> couponList;

    public CouponAdapter(List<Coupon> couponList) {
        this.couponList = couponList;
    }

    @Override
    public CouponViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.fragment_one_card, parent, false);

        CouponViewHolder vh = new CouponViewHolder(v);
        return vh;
    }

    @Override
    public long getItemId(int position) {
        return super.getItemId(position);
    }

    @Override
    public void onBindViewHolder(CouponViewHolder holder, int position) {
        Coupon coupon = couponList.get(position);
        holder.company_name.setText(coupon.getCompany_name());
        holder.offer_desc.setText(coupon.getOffer_desc());
        holder.heart_button.setLiked(false);
        holder.star_button.setLiked(false);

        holder.heart_button.setOnLikeListener(new OnLikeListener() {
            @Override
            public void liked(LikeButton likeButton) {
                notifyDataSetChanged();
            }

            @Override
            public void unLiked(LikeButton likeButton) {
                notifyDataSetChanged();
            }
        });

    }

    @Override
    public int getItemCount() {
        return couponList.size();
    }

}

Thank you
Comment: You can store the button state in your local memory, sqllite or sharedprefrences or you can have it in ur server db which will hold the state of button of every user and every coupon
Comment: You have to use boolean isSelected state in your Coupon class and change it while clicking at Button.
Comment: Do you have any sample code ?
Answer: You have to save the selected things on database or sharedpreferences or whatever saving method you use. you can create an interface for making this action on your class or activity.
Answer: 1-For the most cases saving the state of the button in the model list is enough. However,when an user change its fragment or activity, there is possibility of that you model list could be destroyed by the system because of memory usage. For this case you have choose whether persist your data using sharedpref,file,db etc or keeping your data in a store whose lifespan is longer than the activity or fragment. It seems that the page you share is related to your app's main functionality so you should keep your data in a repository whose scope is dependent on the app scope. I recommend you to look at mvvm architecture and repository pattern.


i want to find all if statements in C# code which are not followed by brackets. Through regex

Question: I want to find all if statements and for statements which are not followed by curly brackets '{'. When you write a single line in an if statement you do not mostly enclose it in curly brackets, so I want to find all those if and for statements.
Please help!
Like I want to capture this statement
if (childNode.Name == "B")
    return TokenType.Bold;

but not these kinds
if (childNode.Name == "B")
{
    return TokenType.Bold;
}

I want to do it with regex.
Answer: Since the underlying mathematics disallow a perfect match, you could go for a good heuristic like "find all 'if' followed by a semicolon without an intervening open brace:
/\<if\>[^{]*;/

where \< and \> are begin-of-word and end-of-word as applicable to your regex dialect. Also take care to ignore all newlines in the input, some regex processors need to be told to do that.

You might want to look at StyleCop too. This is a tool which runs a big set of various checks on your source code. This check is already there.
Answer: If you want a 100% working solution then a regex will not fit the bill.  It's way too easy to trip up a regex with real code.  Take for instance the following regex
"^\s*if\W[^{]*\n\s*[^{]"

This will match a good majority of "if" statements that are not surrounded by braces.  However it can easily be broken.  Take the following samples.  The regex will incorrectly flags these as if statements with braces.
Example 1
if ( SomeFunction(() => { return 42; }) )

Example 2
/* Big comment
   if ( true ) {
*/

The list goes on and on.
Bottom line, if you want perfection, a regex will not work.  If you are satisfied with a less than perfect solution then the above regex should do the trick.
Answer: You can Google for Finite-State Machine to find out why it is not possible to write a pure regular expression you are asking for.
On the other hand some reg-ex interpreters, like in the Perl language have the possibility to reference previously matched expression, which make it possible to theoretically implement entire C# grammar. Do not follow this idea though ;) David Schmitt idea is nice.


What is the Lydian Chromatic Concept?

Question: I've recently found out about George Russell's book the Lydian Chromatic Concept of Tonal Organization and I've been curious about exactly what the Lydian Chromatic Concept is and how it can be used to compose music. I eventually plan on getting the book, but I've also tried to learn about it from other sources and they have been really lacking in basic information about it.
So what exactly is the Lydian Chromatic Concept and what are some examples of this in practice?
Comment: I don't have the book (it costs a fortune on Amazon), but from what I know it talks about how would the music be, if it was built around the Lydian mode, instead of the Major scale.
Comment: I've been looking for the same thing. The publishers seem to be very keen on protecting their intellectual property - as is their right of course - I think the only way to find out is to buy the book.
Comment: Google for the title + author + "pdf". You'll likely find a copy. The link that once worked for has been taken down. Looks like another is available.
Comment: I cannot comment on other countries, but in the U.S., if you contact your library, you should be able to "check out' a digital copy of the book at no cost.
Answer: I'm going to give a very cursory simplification for the answer because asking about Lydian Chromatic theory is just like asking about Set Theory or Serialism.
Lydian Chromatic Concept Theory basically asserts that the lydian scale is more closely aligned to the natural, universal properties of sound than the conventional major scale.  It explains and justifies this reasoning through the overtone series, interval vectors, and what is described as tonal gravity.  Tonal gravity is the aural relationship between a given note and the fundamental of it's prime-order lydian chromatic parent scale.  A tonal gravity field is something not unlike a pitch-class region.
Because the perfect fifth is the first interval introduced after the perfect octave, it is

"thus established as the strongest harmonic interval" (pg.2).

In other words, the fifth is considered to be the "foundation" or "cornerstone" interval.  To this end, the fifth then establishes itself as the basic unit of tonal gravity whereby

"a ladder of fifths proceeding upwards from the tonic...produces the
  first seven tones of the Lydian Scale..." (pg.3).

When discussing this theory you need to dispense with functional harmony.  That said, this theory may be used to create tonal, atonal, and pantonal music. It is important not to conflate functionality with tonality.  Tonal Gravity is measured vertically as well as horizontally.
Here is another quote from the text in question that might help:

There is no "goal pressure" within the tonal gravity field of the Lydian Scale.  The Lydian Scale exists as a self-organized Unity in relation to its tonic tone and tonic major chord.  [It] implies an evolution to higher levels of tonal organization.  [It] is the true scale of tonal unity and the scale which clearly represents the phenomenon of tonal gravity itself.

"Goal Pressure" here of course refers to the depends on the Dominant -> Tonic relationship.  "Unity" is the process by which "gravitational energy is passed down a ladder of fifths to its lowermost tone..."
Each Chromatic Order has seven principle scales.  These principle scales (along with most things in this theory) are derived from the overtone series.
From there on, it just gets a lot more complicated.
The Take Away

Lydian Scale is more closely aligned to the natural, universal properties of sound than the conventional major scale.
The harmonic series is the most natural expression of sound at its fundament.
All musical grammar and expression of this language evolves from the harmonic series.
Comment: The Lydian Chromatic Concept does not prefer the Lydian scale because it is "more closely aligned to the harmonic series than the major scale". This case would be very hard to argue: the relevant harmonic (at 11 times the fundamental frequency) is at 551 cents, which is almost exactly in between a 4 (500 cents) and a #4 (600 cents). The real argument for the Lydian scale is the fact that it can be generated by stacking 6 ascending perfect fifths on top of each other. The unique quality of a perfect fifth can of course be motivated by the overtone series.
Comment: @MattL. If you happened to read the top of my answer, you would have seen that I said that the theory "asserts" (as in an *inference*) that the lydian scale is more closely aligned to the natural, universal properties of sound than the conventional major scale, **not** that the theory itself states it explicitly.  Close though the frequencies may be, the 11th partial of the overtone series is almost always understood to be a flattened #4.  I rarely see productive conversations when people start using "cents" and "Hz" as you can quickly dissolve the inherent validity of any note.
Comment: I wasn't about to get into an argument whether the 11th partial is closer to a 4 or a #4, I just pointed out that your mentioning the overtone series might be misleading, because Russell only uses the perfect fifth (and nothing else from the overtone series) as an argument for using Lydian as the basic scale. If he had based his reasoning on higher harmonics, he should have ended up with Lydian b7. So nothing in his justification of Lydian refers to any higher harmonics than the interval of a perfect fifth.
Comment: So it's a good thing that you edited your answer accordingly by adding some text and quotes about the perfect fifth.
Comment: @MattL. Yes, the point you made made me realize that my answer lacked some specificity - specifically relating to use of perfect fifths.

What is the Lydian Chromatic Concept?


Comparing textbox value to database

Question: HI !
I would like to compare values from a textbox with data from a table. I tried this code but i got the error that the input string was in the wrong format!
code:
string connectionString =
    "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=save.mdb";

try
{

   database = new OleDbConnection(connectionString);
   database.Open();
   string queryString = "SELECT zivila.naziv,users.user_name FROM (obroki_save "
       + " LEFT JOIN zivila ON zivila.ID=obroki_save.ID_zivila) "
       + " LEFT JOIN users ON users.ID=obroki_save.ID_uporabnika "
       + " WHERE users.ID='" +Convert.ToInt16(id.iDTextBox.Text)+"'";
   loadDataGrid(queryString);
}
catch (Exception ex)
{
   MessageBox.Show(ex.Message);
   return;
}

Comment: Are you sure that the textbox is all digits? Perhaps use int.TryParse instead.
Comment: Also read up on protecting yourself from Sql Injection! This is a classic example of Sql Injection potential!
http://en.wikipedia.org/wiki/SQL_injection
Comment: Fair enough. Was just following up. Peeps new to this site often forget to follow up on asked questions.
Comment: What line throws the exception?
Comment: i just get the message box that the input string is in the wrong format
Comment: What is the type of users.ID?
Answer: your connectionstring should look like this:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;User Id=admin;Password=;
Further information on connectionstrings you can find on connectionstrings.com
Answer: when building your sql, you're trying to concatenate a string and an Int16 value.  try removing the Convert.ToInt16(), leaving just the string value of the textbox.
Comment: i get an error in the conditional expresion(that's what the program said)
Answer: Try changing your last line to
+ " WHERE users.ID=" +Convert.ToInt16(id.iDTextBox.Text);

basically removing the single quotes from around the Int16
Answer: You could try this:
string connectionString =
    "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=save.mdb";

try
{
       Int16 id = Int16.Parse(id.iDTextBox.Text);

   database = new OleDbConnection(connectionString);
   database.Open();
   string queryString = "SELECT zivila.naziv,users.user_name FROM (obroki_save "
       + " LEFT JOIN zivila ON zivila.ID=obroki_save.ID_zivila) "
       + " LEFT JOIN users ON users.ID=obroki_save.ID_uporabnika "
       + " WHERE users.ID=" + id.ToString();
   loadDataGrid(queryString);
       database.Close();
}
catch (FormatException fex)
{
   MessageBox.Show(fex.Message);
   return;
}
catch (Exception ex)
{
   MessageBox.Show(ex.Message);
   return;
}

This way you would intercept bad data and protect yourself from Sql Injection.
Also, don't forget to Close your connection, or read up on the using the using keyword.
Also try to run the query with a hardcoded id value in your sql editor to make sure it works:
SELECT zivila.naziv,users.user_name
FROM (obroki_save AS os LEFT JOIN zivila AS z ON z.ID=os.ID_zivila)
LEFT JOIN users ON users.ID=obroki_save.ID_uporabnika
WHERE users.ID=16

Answer: if your ID field is an int, you shouldn't be putting ' around it.
so change
 + " WHERE users.ID='" +Convert.ToInt16(id.iDTextBox.Text)+"'";

to
 + " WHERE users.ID=" +Convert.ToInt16(id.iDTextBox.Text);

Comparing textbox value to database


Does $\sum_{n=1}^\infty \frac {\left(\cos\left(\frac{n\pi}{8}\right)\right)^n}{n}$ converge?

Question:
The Problem is: Does the series $$\sum_{n=1}^\infty \frac {\left(\cos\left(\frac{n\pi}{8}\right)\right)^n}{n}$$ converge or diverge or
oscillate ?

My approach : Actually, the series is not absolutely convergent because the subsequence $T_{16k} \gt \sum_{j=1}^k \frac{1}{16j}$ and hence becomes divergent where $T_n$ represents the partial sums of the absolute series .
Now, I have tried to apply the Dirichlet's test on the series but I think the series $$\sum_{n=1}^\infty  \left(\cos\left(\frac{n\pi}{8}\right)\right)^n$$ is not bounded because if $n =8k,8k+1,...,8k+7$ for all non-negative integers $k$ , then except $n=8k$, the rest of the series forms into distinct brackets of infinite geometric progressions with common ratio(s) $r \lt 1$ but we get $1+1+..1+...$ in the series for $n=8k$ values and hence the series becomes unbounded .
I can't approach further, a small hint is warmly appreciated .
Comment: What's to the $n$-th power? The cosine or the arc?
Answer: Let $a_n$ be the $n$th term of our series. I'll show $\sum a_n$ is the sum of a convergent series and a divergent series. This implies $\sum a_n$ diverges.
Define $b_n=0$ if $n$ is a multiple of $8,$ $b_n=a_n$ otherwise. Define $c_n = \frac{1}{n}$ if $n$ is a multiple of $8,$ $c_n=0$ otherwise. Then $a_n=b_n+c_n$ for all $n.$
Now $|b_n| \le (\cos(\pi/8))^n$ for all $n,$ and $\sum_{n=1}^{\infty}(\cos(\pi/8))^n$ is a convergent geometric series. Thus $\sum b_n$ converges.
As for $\sum c_n,$ let $S_n$ be its $n$th partial sum. Then
$$S_{8m} = \sum_{k=1}^{m} \frac{1}{8k}$$
and thus $S_{8m}\to \infty$ as $m\to \infty.$ Therefore $\sum c_n$ is divergent.
So $\sum a_n$ is the sum of a convergent series and a divergent series as advertised, and we're done.


Activating conda environment from bash script

Question: I would like to change my conda environment from a bash script.
I want to run bash script_yxz, where 'script_xyz' is like:
#!/bin/bash

conda activate my_env

and switch to my_env.
This already works if I run source script_yxz.
But I have the problem that I am not able to 'source' on remote machines with 'sshpass'.
To better understand my purposes, my goal is to run on my terminal
sshpass -p "password" ssh -o user@server "bash script_xyz"

and changing the environment on the server.
This is why I need to use bash instead of source.
I have read a lot of solutions on various forums but none of them works.
Comment: https://superuser.com/questions/1442641/activating-conda-environment-over-ssh
Answer: #!/bin/bash

eval "$(conda shell.bash hook)"
source ~/anaconda3/etc/profile.d/conda.sh

conda create -n testing python=3.10 -y

conda activate testing
python --version

#output
Answer: seems like the conda script is not imported by default so this should fix it
source ~/anaconda3/etc/profile.d/conda.sh
conda activate <env>

Answer: You can use bash,zsh or any shell aliases for this purposes. You just add
alias my_conda='source /home/$USER/anaconda3/bin/activate && conda activate MyPy38'

line into the .bashrc,.zshrc or .any_other_shell_rc.
"N.B. My environment name is MyPy38". So,replace it according name as well as the path /home/$USER/anaconda3.
Also you can create separate file for aliases. Just create a file called .bash_aliases and add
if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

lines to .bashrc,.zshrc or .any_other_shell_rc and keep the command
alias my_conda='source /home/$USER/anaconda3/bin/activate && conda activate MyPy38'

into the .bash_aliases. Now,  source ~/.zshrc ~/.bashrc or just close and open a new terminal. Run the command my_conda and BOOM!
Also, you can add some other aliases for jupyter-notebook jupyter-lab spyder etc. like
# Just activate my conda
alias my_conda='source /home/$USER/anaconda3/bin/activate && conda activate MyPy38'

# Open Jupyter Notebook in my Env
alias my_jupn='source /home/$USER/anaconda3/bin/activate && conda activate MyPy38 && jupyter-notebook'

# Open Jupyter Lab in my Env
alias my_jupl='source /home/$USER/anaconda3/bin/activate && conda activate MyPy38 && jupyter-lab'

# Open Spyder in my Env
alias my_spyder='source /home/$USER/anaconda3/bin/activate && conda activate MyPy38 && spyder'

To confirm active environment name python code
import sys
print(sys.executable)


For $H, K$ normal subgroups of $G$ with $H \le K$, then $K/H \trianglelefteq G/H$

Question: Dummit and Foote leave this as an "easy exercise for verification" and I would like to verify that I am indeed reasoning correctly.
Proof
Take an arbitrary element $kH \in K/H$, and let $G/H$ act on $K/H$ by conjugation. $$(gH)(kH)(gH)^{-1} = (gH)(kH)(H^{-1}g^{-1}) = gh_1 kh_2 h_3^{-1} g^{-1} = gh_1kh_4g^{-1}$$ But $H\le K$, and so $h_1 \in H$ is also in $K$, then $h_1 kh_4 \in K$, and $K$ is normal in $G$, so $gKg^{-1} = K$, and thus $(gH)(kH)(gH)^{-1} \in K$.
My Question
How do I recover my coset $kH \in K/H$? I have made an error along the way, and can't see where my error lies.
Comment: The product of elements in $G/H$ is given by $(g_1H)(g_2H) = g_1g_2H$. I'm not sure what you're doing exactly.
Comment: @Cocopuffs jmi4's proof is not efficient, but it is nonetheless correct.
Comment: @Phira I see, I was confused by the switch between left cosets and right cosets or elements..
Answer: The second equality sign in your proof is not an equality, as you go from a set notation to a notation that gives a generic member of the set. At the end, you did the reverse notational misstep, by writing a set being an element instead of a subset of another set.
So, you start out with a set that you want to be a coset of type $k'H$ with $k' \in K$, (not necessarily the same $k$!) so it is enough to show that your generic element can be written as $k'h'$ with $k' \in K$ and $h' \in H$, but since $H$ is a subgroup of $K$ this is exactly the same thing as showing that the generic element is in $K$ which is precisely what you have done (up to notational problems).

For completeness, let me detail Cocopuffs' comment:
Since $H$ is normal, you can calculate with the cosets "the easy way":
$(gH)(kH)(gH)^{-1} = (gkg^{-1})H= k'H$ where the first equality uses the normality of $H$ and the second equality uses the normality of $K$-
Comment: Understood. Thanks for the precise explanation


General equation of a plane through $3$ points.

Question:
Find the general equation of the plane through the points $A(1,1,0),\, B (1,0,1),$ and $C(0,1,2)$.

How is this done?
Comment: @Marra Feel free to edit; I did initially, and probably mistakenly chose linear algebra.
Comment: Have you searched on the web before asking this question. Please show your efforts first
Comment: Why is this a linear algebra question and not a analytical geometry question?
Answer: Let the general equation of the plane be $ax+by+cz+d = 0\;,$ Then the equation of the plane passes through the point $A(1,1,0)$, that is $$a(x-1)+b(y-1)+c(z-0) = 0\tag1$$
The plane also passes through $B(1,0,1)\;,$ so we put $x=1,y=0,z=1\;,$ and we get
$$a(1-1)+b(0-1)+c(1-0) = 0\tag2$$
Now the plane also passes through $C(0,1,2)\;,$ so we put $x=0,y=1,z=2\;\bf{in \; (1)\;,}$ and we also get
$$a(0-1)+b(1-1)+c(2-0) = 0\tag3$$
Now eliminating $a,b$ and $c$ from these $3$ equations we get an equation of the plane.

We can also eliminate $a,b$ and $c$ as
$$\displaystyle \begin{vmatrix}
 x-1& y-1 & z\\
 0& -1& 1\\
 -1& 0 & 2
\end{vmatrix}=0\Rightarrow -1\left(y-1+z\right)+2(-x+1) = 0\Rightarrow 2x+y+z = 3$$
Answer: Equation of the plane if given $3$ points can be found by $B-A=(1,0,1)-(1,1,0)=(0,-1,1)$ and $C-A=(0,1,2)-(1,1,0)=(-1,0,2)$. You now find the cross-product of $$(B-A)\times(C-A)=\begin{bmatrix}i & j & k \\0 & -1 & 1 \\-1 & 0 & 2 \end{bmatrix}=(-2,-1,-1)= \vec{n}$$ $i$, $j$ and $k$ are unit vectors that are directed along the $x$, $y$ and $z$ axis respectively. $\vec{n}$ is known as the normal vector $\vec{n}$ and is perpendicular to the equation of the plane. Now use the general vector equation of the plane:$$\vec{r}\cdot\vec{n}=\vec{a}\cdot\vec{n}$$ where $\vec{r}$ is the position vector relative to the origin of any point $(x,y,z)$ in the plane and $\vec{a}$ is a known point that lies on the plane. So using $\vec{a}=A$ we get $$(x,y,z)\cdot(-2,-1,-1)=(1,1,0)\cdot(-2,-1,-1)=-2-1+0=-3$$ In Cartesian coordinates this is $$-2x-y-z=-3=\color{blue}{2x+y+z=3}$$ as the equation of the plane.
Answer: The general equation for a plane is $ax+by+cz=k$
Plug in the values for points A,B, and C and you have a linear system of three equations which you can solve. One way to do this is to represent the system with a matrix and use Gaussian elimination.
Note that there are 4 unknowns, so there is no single solution for a,b, and c since you can just multiply the equation by some constant and it stays the same, so you just solve for ratio of a to b to c.
Also if there is no single solution, then there is a solution set (multiple planes can satisfy the conditions).
Comment: You are putting the cart before the horse. How do you know *in advance* that the plane doesn't pass through the origin? If you cannot exclude that possibility, you cannot "just solve $ax+by+cz=1$" because every plane that satisfies this equation must not pass through the origin.
Comment: If you put $k=1$, the plane will never pass thro' the origin.
Comment: That isn't one of the criteria in the question.
The only thing $k=1$ does is make the answer $\frac{2}{3}x + \frac{1}{3}y + \frac{1}{3}z = 1$ which is the same as the equation in the other answers, just divided by 3.
Comment: oh, I see, I didn't think of that. thanks


Como acessar uma variavel array codeigniter

Question: Tenho dificuldades em pegar valores dentro de uma variável array no codeigniter ajude-me entender como funciona isso de uma vez por todas
Fiz uma busca no banco de dados que é enviada para a view por uma array:
Controller
$dados= array(
'perfil' => $this->perfil->perfil($id)
);

Na view tenho os dados que veio do controller.
Verifico minha variável $perfil com var_dump($perfil) e aparece isso:
Array
(
[0] => stdClass Object
(
[artigo_id] => 2
[artigo_titulo] => A volta de cristo
[artigo_imagem] => 8f5364fb6f5204224529ce3345073906.jpg
[artigo_autor] => Nativo Natan Melo
)
)

Como faço para pegar as informações do índice artigo_autor?
Tento acessar fazendo
$perfil->artigo_autor;

Mais da um erro :

Trying to get property of non-object.

Como eu devo proceder?
Comment: O retorno do metodo tem que ser `row`
Comment: Basta `$perfil[0]->artigo_autor`
Comment: Não tem como eu acessar tipo assim;
$perfil->artigo_autor ?
Comment: http://stackoverflow.com/questions/6601236/codeigniter-return-result-and-row
Answer: Se o método $this->perfil->perfil($id) deve retornar apenas um unico registros mude o retorno dele de result() ou result_array() para row() assim não é criado o indíce zero e é possível acessar direto as propriedades do objeto.
Exemplo mude:
$query = $this->db->query("YOUR QUERY");
return $query->result();

Para:
$query = $this->db->query("YOUR QUERY");
return $query->row();

Leitura recomendada:
Documentação - row()
Comment: Perfeito, nunca mais eu esqueço . Muito obrigado


Sufficient statistic for Poisson in wiki?

Question: In Wikipedia:
https://en.wikipedia.org/wiki/Sufficient_statistic#Poisson_distribution
it says that $X_1+\cdots+X_n$ is a sufficient statistic for the parameter of the Poisson distribution and its proof follows by using the factorization theorem.  However, the expression they obtain is:
$$ e^{-n\lambda}\lambda^{(x_1+x_2+\cdots +x_n)}\cdot {1 \over x_1!x_2!\cdots x_n!}$$
which also depends on $n$. Am I correct by assuming that this proof is flawed?
I know another proof using another result, but I wonder about the correctness of this claim in wiki.
Comment: This is not clashing with the definition of sufficiency.
Comment: You misread Wikipedia: the formula you quote is the probability for the vector $(x_1,x_2,\ldots,x_n).$  Please read on from that statement through the end of their demonstration that the likelihood depends only on the mean of the $x_i$ (or, equivalently, their sum, because $n$ is known).
Answer: A sufficient statistic is sufficient for a particular family of probability distributions, and in this case that family is actually not the family of Poisson distributions, each member of which is supported on the set $\{0,1,2,3,\ldots\},$ but rather it is a family of distributions supported on the set $\{0,1,2,3,\ldots\}^n$ of all $n$-tuples of finite cardinal numbers. Thus the random variable involved is an $n$-tuple $(X_1,\ldots,X_n)$ in which the components are independent and each has a $\operatorname{Poisson}(\lambda)$ distribution.
Within the set of all such $n$-tuples one finds the observable data $(x_1,\ldots,x_n)$. If the observable data are altered within that set, the number $n$ does not change; only the $x\text{s}$ change. Thus the proof is not erroneous.
If the number of independent identically distribued Poisson observations were a random variable in its own right, then one would have a different family of distributions and the sum of the observations would probably not be a sufficient statistic.
Answer: The proof of the factorization theorem is based on the sample size (the conditional distribution of the sample given the test statistic, of size $n$, for each $n$), thus, it is specific to each $n$. For this reason, the sample size $n$ is considered fixed/known.
Most "answers"/"comments" here focus on claiming "yes"/"obvious", without scientific basis, but this provides a more formal answer.