Box scale patterns vs intuition?

Question: I know there's 7 box patterns for the major scale on the guitar. I think some people have it as 5 patterns.
I've never done scales that way though. I've only done it by ear where I can go up and down scales because I've done it many times. I also do it randomly because you can go between two octave points any way you want. For example, I could go just use 2 strings for an entire scale. I always thought 7 patterns was limiting because there's probably hundreds of patterns one could potentially use because there's so many paths one could take.
But I'm wondering if I should still learn those 7 patterns. Are there benefits to them, or can you do it by intuition just as well?
Comment: How do you know there are 7?
Comment: Robben Ford doesn't know what "scale patterns" mean https://www.youtube.com/watch?v=TjfB7XDlfwc&t=8m45s   Even the thing he's describing is musical patterns, not the _visual dots-on-a-grid patterns_ that many guitarists actually mean with "patterns".
Comment: @ggcg I googled it. afaic there's at least 100.
Comment: Intuition = immediate understanding without reasoning. How one achieves this, i don't know! Do you mean playing scales by simple hit and miss? One of the ideas of learning patterns is that they become automatic and take out of the equation the thinking 'I need that note, now where is it on the neck?' Intuition isn't going to help you learn much.
Comment: @Tim too late for hit and miss (been doing that for the last 10 years). I can generally hit the note I have in my head now.
Answer: You seem to be basing a lot of your statements on assumptions and none of us can confirm or deny their validity.  I could never convince you to use 6 strings if you claim that 2 is enough.  But I cannot fathom how having more options reduces your freedom, as you imply.  There are more benefits to learning patterns than can be listed here, but I will try.
First of all you mention "intuition".  Without getting to far off on a tangent that should be in another exchange group I'd argue that there really is no such thing.  People don't have mystical or magical powers to know things they don't already have some experience with.  At least there is no objective scientific evidence for it.  What most people call "intuition" is most likely pattern recognition.  So I would argue that the more patterns you learn, the more intuitive you will become over time.  Your subconscious mind will compare, contrast, and connect patterns you learn while you sleep.  This will forge a deep knowledge of how such patterns are connected.
As for learning by ear?  I do not equate this to "intuition", this is a form of pattern recognition, and a powerful one.  Learning anything by ear is the right path for music since we need to use our ears.  But there are severe limits to noodling around on an instrument using only your ear.  Your ear should be what guides you in making musical decisions but to master an instrument you need to have the patterns in your muscle memory.  If you want to develop virtuoso skills you need to commit patterns to muscle memory so you don't have to think about it or fish for notes when you perform.  In a sense there is more than one thing to learn when learning a musical instrument.  There is music itself (which is universal across all instruments) then there is the instrument and the idiosyncrasies that it presents.  I would compare learning patterns to a boxer learning combinations.  When you learn martial arts you throw 1000 jabs, 1000 hooks, etc.  But then you commit 3 and 5 move combinations to memory.  If the first punch doesn't land or the other guy reacts differently than expected you don't stop mid stream and change your mind.  The mind gets in the way, introduces latency which kills the fluidity of the movement.  You will sometimes see a pro throw a wild combo at the air and think why are they doing that?  Once the combo was let loose it's going to finish regardless of the circumstances.  I'm not trying to imply that musicians should throw out notes that don't work.  The analogy is not perfect.  But the point is, thinking gets in the way of performing and it is worth committing patterns to memory.
I am not sure what specific "box" patterns you are referring to.  I have only heard that term in relation to the pentatonic scale and blues licks that seem to generate a lot of 4 note 2 string patterns that use only 2 fingers.  If you are referring to the standard forms of the diatonic modes that do not shift position these are worth learning because they connect to standard chord forms.  Even if one could successfully play melodies without using patterns I doubt chords would be as easy.  We spend a lot of time learning standard chord forms to make playing charts on the fly easy.  I cannot imaging the effort required to fish around for a G7(b9#5) on the finger board.  It has a shape and most guitarists have it memorized (or perhaps 2 or 3 versions).  Learning how the mode shapes connect to chord shapes allows one to rapidly access one pattern from another.  You still need to use your ear when it comes to choosing the right notes but why would you want to have to fish for the notes you want when they are organized into patterns that connect to the other elements of music.  This is a very guitar-centric idiosyncrasy. The layout of the guitar lends itself to being understood using geometrical patterns.  A horn player would never benefit from attaching a mode pattern to a chord form since this geometry is not present in the horn.  I am not referring to tonally connecting a mode to a scale which everyone does.  I am referring to the fact that the E-form is related to Ionian, D-form to Dorian, C-form to Phrygian, etc.  Knowing these basic patterns will, over time, allow you to immediately know, by muscle memory, what elements of music are under your fingers.
As I alluded to in my comment there are a lot more than 7 forms.  All of them are useful in some way but their usefulness is different.  For example I mentioned the connection between chords and scales.  Chord form typically only cover a 4 fret neighborhood of the neck so learning the standard forms of the scales makes sense here.  However you need to learn to shift all the way up the neck.  In the classical guitar repertoire we have the famous Segovia Scales.  These are scale patterns that climb up the neck, starting on the bass string in the lower position and ending way up at the 15th fret on the high e string, and back.  The ascending and descending patterns are typically different.  Segovia organized things this way because he felt that these patterns (from among 100s or 1000s) were the most economical in terms of learning to perform, and sounded best on the classical guitar.  You can play a single note in 3 or 4 places and it will sound different at each place.  The "box" patterns you mention are connected.  Once you learn the connections you can weave in and out of them passing through different positions.  You  mention 100s of ways to play something in your question.  Without committing something to muscle memory you have 0 ways to play something.  Learning patterns doesn't limit your options, it opens them up.  You just have to be committed to practice and learning more about how they are connected.
Most shredders will emphasis the value of 3 note per string scale forms because they think that they are "easier" to play at high speeds, and they are correct.  It is also easier to apply consecutive picking to them.  Then there are the 2 string groupings of patterns that repeat as you go up the neck, passing through 3 octaves using a single pattern.  Which one of these should you, or any guitarist, learn?  ALL OF THEM.  Learning the guitar should be a cumulative process.  There is no best pattern, all of them are important but for different reasons.  I see a lot of videos and books that disparage one technique or pattern in favor of another.  These are sales pitches.  They are all useful and important for mastering the guitar.  A good instructor will be able to point out the different uses of each pattern and how they are connected.
Every pattern is worth learning. Some are easier to play than others and those should probably be emphasized more.  I would only advise against falling into the trap of "this versus that".  There is no "better" pattern that trumps all others making them worthless.  Each pattern or set of patterns has a definite purpose or use on the guitar.  Learn what the connections are to the other elements of guitar playing.
Comment: @ggcg so you're right in a lot of ways. but the way I'm using this is different. for example, I use a lot of alternate tunings so those boxes only work in standard tuning. Also, I've already committed everything to muscle memory. so what you're saying is true but for a complete beginner. also, I don't like looking at anything visual. I do everything by ear. and I do mean everything. but I'll keep what you said into account as I said a lot of what you're saying rings true.
Comment: 'E-form=Ionian, D-form=Dorian, C-form Phrygian'. Help! I don't understand. Unless it's related to the lowest note in a scale pattern?
Comment: Not at all.  The c form of the key signature is embedded in phrygian, or lydian.   You can find it embedded in others too.   But as you climb up the neck from e form, to d form, to c form, to a form,  to g form you pass through the ionian, Dorian, phrygian, mixolydian, and aeolian respectively.   My connection is based on position and where my index finger is.
Comment: It's just geometry based, nothing else.  Wouldn't work in other tuning
Comment: this is a great answer, thanks for the effort you put into it. I do agree with your points on being open to different ways of learning. that's why even though I've been playing for a long time I'll always consider myself a beginner. btw, a quick example of the 7 major scale boxes: http://www.fretjam.com/major-scale-positions.html
Comment: @foreyez, those patterns are just the 7 modes in "standard form".  That is what I was referring to in my answer.  Phygian and Lydian as well as ionian and locrean are essentially the same fingering, leaving 5 important ones.  These correspond to a chord form in the CAGED system.
Comment: @ggcg I always liked CAGED, I've mainly been using it to find different ways on the fretboard to create the same chord. but you're saying that each letter corresponds to a scale box? so then it's 5 shapes not 7. if that's the case that's great and I'll read more into it. https://www.learnjazzstandards.com/blog/caged-scales-for-guitar-c-major/
Comment: Actually I'd say it's more than 7.  If you only want to see the connection between mode shapes and CAGED you only need five.  That doesn't make the others less valuable in other contexts.  Also, consider the harmonic minor modes as a new set, now you're up to 14.  Maybe get your hands on the Segovia scales and see how these connect the pieces of the cage together.  Now you're free!
Comment: @ggcg sorry I might've spoken too soon. I tried the scale patterns for like 5 minutes and it's not for me. but I will use CAGED to get an idea of where the roots are, apart from that I do it all by ear / muscle memory I don't even look at the fretboard most of the time. so there's no point (for me) in learning visual patterns or trying to commit them to memory. however, I'll keep this in mind. it might be useful in the future.
Comment: Actually I think you are making a lot of unfair and false assumptions.  There is nothing "visual" about these patterns.  It's all in feel.  No one should be looking at the fingerboard, box patterns or not.  Everything should be feel.  The patterns are useful for a lot of reasons.  One is sight reading, unless you don't do that.  Once you know the degrees under each finger you can read fluidly without much effort.  Also, 5min is not a commitment.  No offense but I can't imagine mastering anything, hand, eye, or ear, in 5min.
Comment: That is a new parameter to consider.
Answer: I think you are in a rare and interesting situation :)
Most people learn scales as positions on the fretboard, repeated mechanically over and over, often without even having a strong sense of how they actually sound.
And for most people, the challenge is to break out of those muscle-memory patterns, if they want to be able to play anything interesting at all.
For example, a common exercise to that end is to play melodies, scales, improvisations, etc. using only one string. If you are forced to use only one string, you have to rely almost exclusively on your ear and understanding of scale structures, rather than by using those all too familiar box patterns.
But you, apparently, are the exception... :)
Answering your specific question, I'd say that learning the standard 5 positions should do you no harm, but as to how much good it will do, that depends on how well you already can play scales in all keys all over the fretboard, and what are you aiming for.
If you can already pretty much do what you want to do, scale-wise, I would not recommend that you spend much time re-learning the same thing from scratch in another way. Rather, I would suggest you invest that time and energy into serious ear training, perhaps into sight reading, into learning the fretboard, or into developing other areas of your playing that are fundamental to the goals you want to achieve.
On the other hand, is you're still feeling insecure about scales, keys, etc. then it may make sense to learn the 5 CAGED boxes, because that will give you a reliable and dependable system, on which you can build further layers afterwards. And because you already have a good sense of those scales, it shouldn't take you too long to do that.
Perhaps you can test yourself in this regard with this video, see how far you can follow the scales in all keys as the video goes on:

I'd say that the more you can follow (key change every 4 bars? every 2 bars? every bar?) the less you need to bother learning the standard position boxes.
Comment: You don't gain anything by breaking from your muscle memory.  If scales are mechanical then I'd say the person had a poor instructor.  You can sing with the "pattern".  Also, forcing yourself to play on one string doesn't mean you don't learn patterns, that is not pattern free.  You just learn a different pattern.  At the end of the day it's a matter of will whether you become mechanical but the method doesn't make you mechanical.

Box scale patterns vs intuition?


Shift time in multi-index to merge

Question: I want to merge two datasets that are indexed by time and id. The problem is, the time is slightly different in each dataset. In one dataset, the time (Monthly) is mid-month, so the 15th of every month. In the other dataset, it is the last business day. This should still be a one-to-one match, but the dates are not exactly the same.
My approach is to shift mid-month dates to business day end-of-month dates.
Data:
dt = pd.date_range('1/1/2011','12/31/2011', freq='D')
dt = dt[dt.day == 15]
lst = [1,2,3]
idx = pd.MultiIndex.from_product([dt,lst],names=['date','id'])
df = pd.DataFrame(np.random.randn(len(idx)), index=idx)
df.head()

output:
                      0
date       id
2011-01-15 1  -0.598584
           2  -0.484455
           3  -2.044912
2011-02-15 1  -0.017512
           2   0.852843

This is what I want (I removed the performance warning):
In[83]:df.index.levels[0] + BMonthEnd()
Out[83]:
DatetimeIndex(['2011-01-31', '2011-02-28', '2011-03-31', '2011-04-29',
               '2011-05-31', '2011-06-30', '2011-07-29', '2011-08-31',
               '2011-09-30', '2011-10-31', '2011-11-30', '2011-12-30'],
              dtype='datetime64[ns]', freq='BM')

However, indexes are immutable, so this does not work:
In: df.index.levels[0] = df.index.levels[0] + BMonthEnd()

TypeError: 'FrozenList' does not support mutable operations.

The only solution I've got is to reset_index(), change the dates, then set_index() again:
df.reset_index(inplace=True)
df['date'] = df['date'] + BMonthEnd()
df.set_index(['date','id'], inplace=True)

This gives what I want, but is this the best way? Is there a set_level_values() function (I didn't see it in the API)?
Or maybe I'm taking the wrong approach to the merge. I could merge the dataset with keys df.index.get_level_values(0).year, df.index.get_level_values(0).month and id but this doesn't seem much better.
Answer: You can use set_levels in order to set multiindex levels:
df.index.set_levels(df.index.levels[0] + pd.tseries.offsets.BMonthEnd(),
                    level='date', inplace=True)

>>> df.head()
                      0
date       id
2011-01-31 1  -1.410646
           2   0.642618
           3  -0.537930
2011-02-28 1  -0.418943
           2   0.983186

Comment: This is an excellent, clean solution to the problem of re-indexing, but I marked the solution below as the answer because it solved my overall problem of merging with better performance. By skipping the re-indexing, it was faster overall.
Comment: I'm out of votes, but I cleared one out and upvoted this because I like this solution as well.
Comment: Thanks, much appreciated! I liked your solution as well!
Answer: You could just build it again:
df.index = pd.MultiIndex.from_arrays(
    [
       df.index.get_level_values(0) + BMonthEnd(),
       df.index.get_level_values(1)
])

set_levels implicitly rebuilds the index under the covers. If you have more than two levels, this solution becomes unweildy, so consider using set_levels for typing brevity.
Comment: This works as well. I hadn't thought of this approach.
Answer: Since you want to merge anyway, you can forget about changing the index and use use pandas.merge_asof()
Data
df1
                      0
date       id
2011-01-15 1  -0.810581
           2   1.177235
           3   0.083883
2011-02-15 1   1.217419
           2  -0.970804
           3   1.262364
2011-03-15 1  -0.026136
           2  -0.036250
           3  -1.103929
2011-04-15 1  -1.303298

And here is one with last business day of the month,  df2
                      0
date       id
2011-01-31 1  -0.277675
           2   0.086539
           3   1.441449
2011-02-28 1   1.330212
           2  -0.028398
           3  -0.114297
2011-03-31 1  -0.031264
           2  -0.787093
           3  -0.133088
2011-04-29 1   0.938732

merge
Use df1 as your left DataFrame and then choose the merge direction as forward since the last business day is always after the 15th. Optionally, you can set a tolerance. This is useful in the situation where you are missing a month in the right DataFrame and will prevent you from merging 03-31-2011 to 02-15-2011 if you are missing data for the last business day February.
import pandas as pd
pd.merge_asof(df1.reset_index(), df2.reset_index(), by='id', on='date',
              direction='forward', tolerance=pd.Timedelta(days=20)).set_index(['date', 'id'])

Results in
                    0_x       0_y
date       id
2011-01-15 1  -0.810581 -0.277675
           2   1.177235  0.086539
           3   0.083883  1.441449
2011-02-15 1   1.217419  1.330212
           2  -0.970804 -0.028398
           3   1.262364 -0.114297
2011-03-15 1  -0.026136 -0.031264
           2  -0.036250 -0.787093
           3  -1.103929 -0.133088
2011-04-15 1  -1.303298  0.938732

Comment: Also, I wanted to keep the month end dates, so I just changed `direction='backward'` and the order of the data frames and that works.
Comment: This is excellent - on my larger data, this merge is faster than re-setting the index and then merging.

Shift time in multi-index to merge


Check if current time is between start time & end time in JavaScript

Question: I'd like to find out how I can check if the current time is between 11am and 8pm in JavaScript.
Also, is there a way I can check how many minutes until 8pm from the current time?
Thanks!
Comment: Moment is rather bloated for just comparing a few dates. https://inventi.studio/en/blog/why-you-shouldnt-use-moment-js
Comment: `moment` can be the test tool to help in your case. Here are apis you might need: https://momentjs.com/docs/#/query/is-between/, https://momentjs.com/docs/#/displaying/difference/
Comment: Does this answer your question? [Compare two dates with JavaScript](https://stackoverflow.com/questions/492994/compare-two-dates-with-javascript)
Answer: I think you want something like this..

checkTime();

function checkTime() {
    var date = new Date(); // current time
    var hours = date.getHours();
    var mins = date.getMinutes();
    var day = date.getDay();
    var totalMins = (hours * 60) + mins;
    var targetMins = 20 * 60
    var remainMins = targetMins - totalMins

    if(hours >= 11 && hours < 20) {
      document.getElementById("text").innerHTML = "Yes Current time is between 11am to 8pm And " + remainMins + " mins left to be time 8pm";
      console.log("Yes Current time is between 11am to 8pm And " + remainMins + " mins left to be time 8pm");
    }
    else {
      document.getElementById("text").innerHTML = "There is " + remainMins + " mins left to be time 8pm";
      console.log("There is " + remainMins + " mins left to be time 8pm");
    }
}

Comment: You should use `hours > =11` otherwise it will show `11:30` is `not between 11AM to 8PM`.
Answer: You can get current time with new Date().
Set hour, minute, second, milliseconds values with .setHours(11, 0, 0, 0).
You can compare it with if (fromTime <= currentTime && currentTime <= toTime) {.
toTime - currentTime will return difference in milliseconds so convert it ti minutes by dividing it with (1000*60).
Try complete code below.

function checkTime(currentTime) {
  let fromTime = new Date(currentTime).setHours(11, 0, 0, 0);
  let toTime = (new Date(currentTime)).setHours(20, 0, 0, 0);

  console.log(currentTime.toString());

  if (fromTime <= currentTime && currentTime <= toTime) {
    console.log('Time is between 11AM and 8PM');

    let mins = Math.ceil((toTime - currentTime) / (1000 * 60));
    console.log('Minutes left to 8PM = ' + mins);
  } else {
    console.log('Time is not between 11AM and 8PM');
  }
}

let currentTime = new Date();
checkTime(currentTime);
let customTime = new Date(2020, 10, 10, 15, 0, 0, 0);
checkTime(customTime);
Answer: Once you have a JavaScript date object, you can use the getHours method to get the hour of the day (in 24-hr time), then just compare the numbers.
To get elapsed minutes, you can subtract one date object from another, then divide by 60,000 (the number of milliseconds in a minute):

// Checks if current time is between 11am and 8pm
const
  date = new Date();
  hours = date.getHours(),
  isBetween = (hours >= 11) && (hours < 20),
  readableDate = date.toLocaleString();
console.log(`"${readableDate}" is between 11am and 8pm?: ${isBetween}`);

// Calculates minutes until 8pm
  const
    oneMinute = 60 * 1000, // JS times are measured in milliseconds
    eightPM = new Date();
  eightPM.setHours(20, 0, 0, 0); // Sets the new date object's time to 8pm
  const
    millisecsDuration = eightPM - date, // **Assumes it's before 8pm!
    minsDuration = parseInt(millisecsDuration / oneMinute);
  console.log(`Minutes until 8pm: ${minsDuration}`);
Comment: You probably want hours >= 11.
Answer: This is my approach:

function dateCompareToday() {
    const today = new Date();
    return new Date(today.setHours(11,0,0)) > today &&  today > new Date(today.setHours(20,0,0))

}

console.log(dateCompareToday())

And with parameters:

function dateCompareToday(a, b) {
    const today = new Date();
    return new Date(today.setHours(a,0,0)) > today &&  today > new Date(today.setHours(b,0,0))

}

console.log(dateCompareToday(11,20))
Answer: I got the time using new Date(). and then used .getHours(), .getMinutes() and .getSeconds() to get the exact time.
I then used if (hours > 11 && hours < 20) to check if it was between 11am and 8pm.
I reduced the date from endTime (endTime was 8pm) which returned the difference in milliseconds so I converted it to minutes by dividing it by (1000 * 60).
Then I just put in the result inside divs.
The divs are updating every second.
Try out my code below!

function newTime() {
  var date = new Date();

  var hours = date.getHours();
  var minutes = date.getMinutes();
  var seconds = date.getSeconds();
  if (hours > 12) {
    var hours = hours - 12;
  }
  if (hours < 10) {
    hours = "0" + hours;
  }
  if (minutes < 10) {
    minutes = "0" + minutes;
  }
  if (seconds < 10) {
    seconds = "0" + seconds;
  }

  var time = hours + ":" + minutes + ":" + seconds;
  $("#answer1").html("The time now is: " + time);

  hours = date.getHours();

  if (hours >= 11 && hours < 20) {
    $("#answer2").html("The current time is between 11am and 8pm!");
    let endTime = (new Date(date)).setHours(20, 0, 0, 0);
    let minsLeft = Math.ceil((endTime - date) / (1000 * 60));
    $("#answer3").html("Minutes left till 8pm: " + minsLeft);
  } else {
    $("#answer2").html("The current time is not between 11am and 8pm!");
  }

}

setInterval(newTime, 1000);

Comment: There's a bug here. (When I looked, it said `The time now is: undefined:40:3`.)
Comment: That error is now fixed! Thank you for informing me!
Comment: To get `padding` `0` you can use [String.prototype.padStart()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart) like `hours.toString().padStart(2, "0")`
Answer: This function allows for ranges such as 10pm-4am as well
function isCurrentHourBetween(minHour, maxHour){
  if (maxHour > 23 || maxHour < 0) {
    console.error(maxHour, ' ~ Invalid Max Hour')
    return false
  }
  if (minHour > 23 || minHour < 0) {
    console.error(minHour, ' ~ Invalid Min Hour')
    return false
  }

  const currentHour = getCurrentHour()
  // get the current hour with any of the ways listed in the other answers
  // should be a number 0-23

  if (currentHour < 0 || currentHour > 23) {
    console.error(currentHour, ' ~ Invalid Current Hour')
    return false
  }

  if (minHour < maxHour) {
    if (currentHour >= minHour && currentHour <= maxHour) return true
    else return false
  } else if (minHour > maxHour) {
    if (currentHour >= minHour || currentHour <= maxHour) {
      return true
    } else return false
  } else {
    if (currentHour === minHour && currentHour === maxHour) return true
    else return false
  }
}

Answer: Date.parse supports the format mm/dd/yyyy not dd/mm/yyyy. For the latter, either use a library like moment.js or do something as shown below
var dateFrom = "02/05/2013";
var dateTo = "02/09/2013";
var dateCheck = "02/07/2013";
var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var c = dateCheck.split("/");

var from = new Date(d1[2], parseInt(d1[1])-1, d1[0]);
var to   = new Date(d2[2], parseInt(d2[1])-1, d2[0]);
var check = new Date(c[2], parseInt(c[1])-1, c[0]);

console.log(check > from && check < to)


I cannot connect App to my PostgreSQL database - No Suitable Driver

Question: I'm doing a school project where I need to connect my app to a PostgreSQL Database.
I'm almost finishing, but I can't make the connection. I think I'm doing something wrong. I'll explain with some pictures.
This is the piece of code that it's probably causing the problem:
<code>private Connection conn;
    private String host = "<--my ip here->>";
    private String db = "android";
    private int port = 5432;
    private String user = "android";
    private String pass = "android";
    private String url = "jdbc:postgresql://@s:@d:@s";

    public DB() {
        super();
        this.url = String.format(this.url, this.host, this.port, this.db);

        this.conecta();
        this.desconecta();
    }
</code>
I can't find PostgreSQL 10 on dependencies list when trying to add library dependencie, even though I've just installed it.
I also have this problem of 2 Databases showing on my PgAdmin 4, the 9.5 port is 5432 and the 10 is 5433, my database for the app is 9.5 (port 5432)
I've add theses ports exeptions to my firewall.
Could someone help me,please?
Comment: You should not try to connect to PostgreSQL directly from Android, you should connect to a web service or REST API and the backend powering that web service should connect to the PostgreSQL database.
Comment: Could you please expand your answer on how excatly could I do that or what steps should I take?
Comment: Trying to answer that in a comment is hard, also is not appropriate to add it here as an answer since it is not your original quesstion. What I can say is, try to create a web service or REST API first, it would connect to PostgreSQL and your android app will connect to the web service or REST API.
Answer: Try to add newest postgres jdbc driver from central repository.
If it is android application it is better to create a web service and use it as proxy. In that case you can control load.
ps. piece of code got 5432 port and  "the 10 is 5433"
Comment: Here is my situation: https://i.imgur.com/j3kmS6u.png and https://i.imgur.com/G8LD0vU.png . I can't find any other to install when I click on add Library Dependecie
Comment: try to add this line to your config:

Class.forName("org.postgresql.Driver");
Comment: can you provide build.gradle file
Comment: Buidgradle from Module:app https://codeshare.io/2WWxJ8

Buildgradle from Project https://codeshare.io/5OJg8j
Comment: should be another there you write dependencies like:

compile group: 'postgresql', name: 'postgresql', version: '9.0-801.jdbc4'
Comment: Ok, I'll give it a try


Best way to save data using node.js with Heroku

Question: I'm programming private guild Discord bot and I need some easy and free way to save bot data like warns.
What do you recommend?
Comment: Warns = warnings? I've worked with mongodb (npm library = mongoose) and that's super simple to set up. Firebase isn't too bad, but more complicated than mongo. I don't know much about Heroku.
Comment: Yup, I want bot to save warnings of guild members (but that's not all)
Comment: @BlunderingPhilosopher Oh man, you're awesome. MongoDB is amazing - it works with no problem. Submit a question with this, so I'll accept it
Answer: As I mentioned in the comments, I'd recommend:

MongoDB / Mongoose (npm)

Nice, simple tutorial by the Net Ninja: MongoDB For Beginners
Mlab = nice hosting service (free up to 500MB I think)

Firebase

I haven't used Heroku in a long time, so I can't recommend that one anymore, but mongoDB is super easy to setup - the Net Ninja has some sweet tutorials that make things nice and simple.


How to create a reference to a class field?

Question: My issue is that I would like to create a reference to a class field. (So that I can modify the reference later and have the results show up in the actual class field.)
public static Transform operator +(Transform transform, ManipulationInformation manipulationInformation)
{
    // I would like to make this into a reference type.
    Vector3 type;
    switch (manipulationInformation.ManipulationType)
    {
        case "Scale":
            type = transform.lossyScale;
            break;
        case "Rotate":
            type = transform.rotation.eulerAngles;
            break;
        case "Move":
            type = transform.position;
            break;
    }
    switch (manipulationInformation.Direction)
    {
        case 'x':
            type = new Vector3(
                transform.position.x + manipulationInformation.NumericalSign * ModificationIncrement,
                transform.position.y,
                transform.position.z);
            break;
        case 'y':
            type = new Vector3(
                transform.position.x,
                transform.position.y + manipulationInformation.NumericalSign * ModificationIncrement,
                transform.position.z);
            break;
        case 'z':
            type = new Vector3(
                transform.position.x,
                transform.position.y,
                transform.position.z + manipulationInformation.NumericalSign * ModificationIncrement);
            break;
    }
    return transform;
}

As with the code above, 'ManipulationInformation' contains three Vector3 fields corresponding to Unity's transform class (of scale, position, and rotation). I would like to be able to add and subtract these (hence the function here is overloading operator+). I would like to make 'type' into something that can hold a reference to one of transform's Vector3s so that I can simplify my code. (A surefire but ugly option would be to put a 'switch(manipulationInformation.Direction)' statement inside each case of the 'switch(manipulationInformation.ManipulationType)' statement; however, the amount of code increases exponentially with more case statements and not very readable.
I am wondering if there is a solution to this madness. Thanks to all in advance!
EDIT: I meant for 'type' to be a reference to one of transform's scale, rotation, and position fields. And make it so that a modification to type would also modify transform's field. However, I now understand that this is not necessary and my issue is due to something else. Thanks Kevin Gosse.
Comment: So every option within `manipulationInformation.ManipulationType` has the three (or more) options `manipulationInformation.Direction`? Than you *have* to do the same thing, however you should consider to plug everything you repeat into a method to reduce code-doubling. Or did I get you whrong, What options do you have when e.g. your `manipulationInformation.ManipulationType` equals `"Scale"`(btw. you´d better be off to use enums instead of strings)? You can scale into x-direction, you can rotate ion x-axis and move into x-direction, don´t you?
Comment: Why set `type` to a value depending on `ManipulationType` only to be overwritten by another switch statement?
Comment: You also seem to be overloading the `+` operator too much. The convention is to use `+` for translation, uniform scaling is performed by `*` between a Vector3 and a scalar, and rotation is performed by `*` between a Vector3 and a matrix.
Comment: Don't understand the purpose behind the code. As for modifying reference, you can always access the Vector3 properties of a transform and assign it a different value. So what's the question? Are you just looking for whether the code can be shortened?
Answer: I think you are overloading + too much. If you don't care about this, then continue reading.
You should probably do something like this:
Action<Transform, Vector3> action;
switch (manipulationInformation.ManipulationType)
{
    case "Scale":
        action = (t, v) => t.lossyScale = v;
        break;
    case "Rotate":
        action = (t, v) => t.rotation.eulerAngles = v;
        break;
    case "Move":
        action = (t, v) => t.position = v;
        break;
}

switch (manipulationInformation.Direction)
{
    case 'x':
        action(transform, new Vector3(
            transform.position.x + manipulationInformation.NumericalSign * ModificationIncrement,
            transform.position.y,
            transform.position.z));
        break;
    case 'y':
        action(transform, new Vector3(
            transform.position.x,
            transform.position.y + manipulationInformation.NumericalSign * ModificationIncrement,
            transform.position.z));
        break;
    case 'z':
        action(transform, new Vector3(
            transform.position.x,
            transform.position.y,
            transform.position.z + manipulationInformation.NumericalSign * ModificationIncrement));
        break;
}

Since transform is not a value type, it can be passed around, so you can do this with some delegate magic.
Comment: This is beautiful! I never thought of the possibility of using delegates to overcome this issue. Thank you.
Answer: Your method has two distinct parts: the actual computation, and the assignation. You can make your code much easier to read/maintain by extracting a method:
public static Transform operator +(Transform transform, ManipulationInformation manipulationInformation)
{
    var type = ApplyManipulation(manipulationInformation, transform.position);

    switch (manipulationInformation.ManipulationType)
    {
        case "Scale":
            transform.lossyScale = type;
            break;
        case "Rotate":
            transform.eulerAngles = type;
            break;
        case "Move":
            transform.position = type;
            break;
    }

    return transform;
}

private static Vector3 ApplyManipulation(ManipulationInformation manipulationInformation, Vector3 position)
{
    var offset = manipulationInformation.NumericalSign * ModificationIncrement;

    switch (manipulationInformation.Direction)
    {
        case 'x':
            return new Vector3(
                position.x + offset,
                position.y,
                position.z);
        case 'y':
            return new Vector3(
                position.x,
                position.y + offset,
                position.z);
        case 'z':
            return new Vector3(
                position.x,
                position.y,
                position.z + offset);
    }

    throw new InvalidOperationException("Unknown direction: " + manipulationInformation.Direction);
}

In fact, the ApplyManipulation method should be declared directly in the ManipulationInformation class. This is a code smell known as feature envy. From there, both types could evolve separately and your code would become:
public static Transform operator +(Transform transform, ManipulationInformation manipulationInformation)
{
    var type = manipulationInformation.Apply(transform.position, ModificationIncrement);

    switch (manipulationInformation.ManipulationType)
    {
        case "Scale":
            transform.lossyScale = type;
            break;
        case "Rotate":
            transform.eulerAngles = type;
            break;
        case "Move":
            transform.position = type;
            break;
    }

    return transform;
}

You could further reduce coupling by introducing a third type that knows how to apply a ManipulationInformation on a Transform (the whole switch (manipulationInformation.ManipulationType) code) but that would probably be overkill at that point.


How to write a list in one excel cell using python

Question: this is my list
list=['a','b','c']

when using this code
with open('commentafterlink.csv', 'w') as f:

     f.write("%s\n" % list)

it stores each token of list in a one cell but i need to store whole list in one cell.where is the problem?
Comment: look for `join()`
Answer: Can you try the following:
import xlwt
from xlwt import Workbook
# Workbook is created
wb = Workbook()

# add_sheet is used to create sheet.
sheet1 = wb.add_sheet('Sheet 1')
# sheet1.write(1, 0, ' '.join(list))
# if you want the output to be ['a','b','c']
sheet1.write(1, 0, str(list))
wb.save('xlwt example.xls')

Output:
Answer: Using join():
lst=['a','b','c']
with open('commentafterlink.csv', 'w') as f:
 f.write("%s\n" % "".join(lst))

OUTPUT:

EDIT:
Using repr():
import xlsxwriter

lst=['a','b','c']                                        # avoid using list keyword
workbook = xlsxwriter.Workbook('commentafterlink.xlsx')  # create/read the file
worksheet = workbook.add_worksheet()                     # adding a worksheet
worksheet.write('A1', repr(lst))                         # write repr(lst) to cell A1
workbook.close()                                         # close the file

OUTPUT:
Comment: output should be :  ['a','b','c']  not abc
Answer: 1) You are not writing an Excel file, but a CSV file (that Excel knows how to import).
2) You are writing to the CSV file as if it was a text file, without respecting the semantics of CSV. CSV means "comma-separated values". If it contains the text ['a','b','c'], it will be interpreted as three columns: ['a' and 'b' and 'c']. You would need to quote the value in order to do it right; the default quote in CSV is a double quote. So if you write "['a','b','c']", this would be imported into Excel as one cell. However,
3) You are writing CSV file by hand, which means it is very easy to get the format wrong (e.g. forget to escape something that needs to be escaped). In general, whenever you are writing a file with an established format, it is worth checking if the format has a library that knows how to handle it. Python natively knows how to write CSV files using the csv module, and it knows how to write Excel files using packages you can install using pip, such as xlwt.
Here is how you write a CSV file correctly:
my_list = ['a', 'b', 'c']

import csv
with open('commentafterlink.csv', 'w') as w:
    writer = csv.writer(w)
    writer.writerow([str(my_list)])

Note: It is a Bad Thing to overwrite Python's built-in variables, such as list.
(I see another answerer has already provided you the Excel-specific solution using xlwt.)


How to print correct path to file in .tpl.php?

Question: <img src="<?php print($base_path . drupal_get_path('theme', 'bartik')); ?>images/some-image.png">

The above code works only if you're in the homepage. If you go to any inner page, it looks for image inside the current URL, not just base URL.
So, it prints the image if you're under www.address.com but if you're under www.address.com/page, it doesn't print the image, because now it's looking for it inside e.g. www.address.com/page/sites/all/themes/bartik/images/some-image.png the problem is, it includes the /page/ part.
In source, the image URL doesn't include the full path (which is the problem I believe?), only the sites/all/themes/bartik/images/some-image.png part.
Answer: It appears $base_path is empty, which would suggest your code isn't in page.tpl.php (where that var is commonly available, having been added in template_preprocess_page()).
To make it available to your current template, implement a preprocess hook like the following, which is for a region.tpl.php template file:
function MYTHEME_preprocess_region(&$vars) {
  $vars['base_path'] = base_path();
}


jQuery - Make tooltip get 2 img alts

Question: Let's say I want to use images in my table headers.
Every image has assigned alt to it.
How can I make get this jQuery code to show tooltip with alt of row and column?(Row:Column format)
At this moment it looks like this:
http://jsfiddle.net/G38nx/33/
Code:
$('td').each(function () {
    var myIndex = $(this).index() + 1;
    var myTitle = $(this).closest('tr').find('th').text();
    var myTitle2 = $(this).closest('td').find('th').text();

    myTitle2 += $('td:first-child th:nth-child(' + myIndex + ')').children("img").attr("alt");
    $(this).attr('title', myTitle2);
    myTitle += ":";
    myTitle += $('tr:first-child th:nth-child(' + myIndex + ')').children("img").attr("alt");
    $(this).attr('title', myTitle);

    $(this).tooltip({
        show: false,
        hide: false
    });
});

Comment: You shouldn't use  in the whole table, only for the header row. That makes both styling and JavaScript easier. One could include the  and  elements also. Furthermore, the  are missing closing tags. But you did a good job trying yourself :)
Answer: What about this :
$('td').each(function () {
    var myIndex = $(this).index() + 1;

    //I took the first sibling th, and took its alt attribute
    var myTitle += $(this).siblings('th').children("img").attr("alt");
    myTitle += ":";
    myTitle += $('tr:first-child th:nth-child(' + myIndex + ')').children("img").attr("alt");
    $(this).attr('title', myTitle);

    $(this).tooltip({
        show: false,
        hide: false
    });
});

Check this Fiddle for a working example!
Comment: @LaveLoos Thanks for the feedback! You'd better post your comment on the question, as it's more about the question itself, plus the OP will be notified of your comment ;)
Comment: You're right, fixed that. The 'nice solution' is still for you though :)
Answer: Ok, easiest way to do this is have your title element blank.
Have content already generated on the page inside a hidden div.
Then when you initialize tool-tip in jQuery provide id of hidden help content.
Step 1

Show tool tip over this element

Step 2

What ever the content you want to be shown as tool tip

Step 3
$( "#x" ).tooltip({ track: true, content:function() {  return $( '#y' ).html(); } });

jQuery - Make tooltip get 2 img alts


How can i pause my code until a toplevel window is destroyed?

Question: So: I try to add Error-Masseges to my code. Each of those i want to display in a separate tkinter Toplevel window. So far so good.
But for this i need to pause my code after the Error-Window was created and wait until the user presses the "okay" button in the Error-Window to continue. Only then the code is allowed to go on.
The creation of the Error-Window i have problems with is within the mainloop of another tkinter window. Latter can not be destroyed without huge problems. Does anyone have a solution for me? Am i maybe committing a sin against the python-god? Can i pause a mainloop?
I tried wait_window(win) (btw: what does it do? It doesn't seem to work as i understood it. Isn't it supposed to be waiting for the given window to be destroyed?)
Also wait() didn't work for me.
My coding senses tell me it has something to do with the mainloop within a mainloop. The code regarding is unfortunately way to long to post it here and a recreation with a sample would be a huge trouble. I hope my description is specific enough.
I also tried to research, but for some reason noone seems to have the exact same problem. There are similar but no solution helped me.
If a sample is REALLY needed please, let me know or downvote my question then i will try to make the core problem as short as possible.
Answer: First, you shouldn't be calling mainloop more than once. Also, you shouldn't create more than one instance of Tk. It's not clear if you're doing that or not.
To wait until a window is destroyed you can use the wait_window method. If you're creating an error dialog, you also probably want to do a grab. That means you want all events to funnel into that widget so that the user can't interact with other widgets until they acknowledge the dialog.
To do a grab, call the grab_set method. The grab will automatically be released when the window is destroyed.
The following example illustrates this technique. Notice that you can click the button in the main window only if the dialog isn't shown. Once the dialog has been shown, the function that creates it won't return until the dialog window has been destroyed.
When you create a window in this way, the dialog is considered to be a modal dialog. ie: it enters a mode where nothing else happens until the window is destroyed.
import tkinter as tk

def show_error(message="Danger Will Robinson!"):
    toplevel = tk.Toplevel(root)
    message = tk.Label(toplevel, text=message, bd=2, relief="groove")
    button = tk.Button(toplevel, text="Ok", command=toplevel.destroy)

    button.pack(side="bottom")
    message.pack(side="top", fill="both", expand=True, ipadx=10, ipady=10, padx=10, pady=10)

    print("waiting for window to be destroyed...")
    toplevel.grab_set()
    toplevel.wait_window()
    print("done waiting")

root = tk.Tk()
button = tk.Button(text="Click me", command=show_error)

button.pack(padx=20, pady=20)

tk.mainloop()


Allow either password or private key SSH authentication

Question: I set the lines PasswordAuthentication yes and PubkeyAuthentication yes in /etc/ssh/sshd_config. I also disabled root login for security purposes. I can now SSH with a user's password without specifying my private key. However I am now unable to deploy over ssh to my server from a script because I would need to specify the password. Therefore I would like the option to ssh into my server without a password by just specifying the private key. However I am always being asked for the password, even if I pass the private key to the -i option. How can I set this up?
Please note that this is not a passphrase associated with the private key, but rather the password associated with the user. It's the password created with the passwd command.
Comment: Please look in your log file, obviously you have something misconfigured.
Comment: @NickW Can you please explain?
Comment: If it is a passwordless private key, you will not get a password prompt, unless you either 1. created a private key with a password or 2. have wrong permissions on a file, or put a carriage return in the public key, or one of many things the log will tell you about quite quickly.
Comment: @NickW I really don't think it's the passphrase attached to the private key but rather the password that is associated with the user account. It's the password that was created by running the `passwd` command.
Comment: When you used ssh-keygen, did you put a password in? If not, just look at /var/log/secure (or the log for sshd on your system) it will have a fairly descriptive error message.
Comment: @NickW the key was created by Amazon Web Services. I don't think they put a passphrase in it.
Comment: Alright, after a quick glance through their documentation it seems to be passwordless. Now log into your server and check that log file out, it will tell you exactly why it doesn't like the private key.
Comment: @NickW I think John below figured it out.
Answer: If the SSH key isn't passphrase locked, the most likely problem is permissions on the destination user's ~/.ssh directory or ~/.ssh/authorized_keys (or ~/.ssh/authorized_keys2) file. I usually set those 600 and 644 respectively, and things work for me.
Comment: NEVER set ~/.ssh or any contents to 777. That's bad juju. You should have a /root/.ssh directory and a /root/.ssh/authorized_keys file - if SSH'ing as root works, copy the authorized_keys file to /home/$USER/.ssh/, make sure the permissions are the same, and you should be good to go.
Comment: Yeah, I think this is it. The `.ssh` folder is actually only in the `root` user's home and not in the user's home that I'm using for SSH. The `.ssh` folder has 700 right now so that would explain the password. Would you recommend changing it to 777 since I disabled root ssh, or should I instead change the owner of the directory to the new user and make it 700?
Comment: If you're going to log in as a user, that user needs to have a .ssh/ directory, and an authorized_keys file with the permissions that John suggested. The authorized keys file needs to contain the contents of the public part of the key.
Comment: @NickW Ok so I can just copy the `authorized_keys` file from the root directory?
Comment: Yeah, just chown it to the new user, and chmod it 644.
Comment: @John I think that if you 777 anything in the ssh directory you will get no end of errors from sshd.
Comment: @John Yeah I realized that right after I said that, it was a bad idea haha
Comment: This worked for me, but I needed 700 and 644 respectively. (the directory needed +x)


How to compute $\iint\frac {\mathrm dx\mathrm dy}{\sqrt {x^{2}-3y^{2}}}$, $\ x^{2}+y^{2}\leq 4x-3$?

Question: Question

$$\iint \dfrac {\mathrm dx\mathrm dy}{\sqrt {x^{2}-3y^{2}}},\quad x^{2}+y^{2}\leq 4x-3$$
Hint: use polar coordinates.

My Answer
$\left( x-2\right) ^{2}+y^{2}\leq 1$ then $C(2,0) , r=1$
$$\iint \dfrac {r\,\mathrm dr\mathrm d\theta }{r\sqrt {\cos ^{2}\theta -3\sin ^{2}\theta }}\Longrightarrow\int\dfrac {-\mathrm d\theta }{\sqrt {\left(1/2\right) ^{2}-\left( \cos \theta \right) ^{2}}}=-\sin^{-1} \left( 2\cos \theta \right)$$
boundary $0$ and $1$ for $r$ ? boundary $0$ and $2\pi$ for $\theta$?
Is my answer along with boundaries correct?
Comment: Please recall that if the OP is solved you can evaluate to accept an answer among the given, more details here https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work
Answer: Yes the boundary are correct but we need to assume

$x=2+r\cos \theta$

in order to have a correct parametrization for the circle.
Answer: Hint: Try with
\begin{cases}
x=2+r\cos\theta,\\
y=r\sin\theta.
\end{cases}
where $0\leq\theta\leq2\pi$, and $0\leq r\leq1$.
Comment: i tried and i realize my fault .However its too complicated inside of root. any suggestion for me @user 108128
Comment: @FMath Your hint was using polar coordinates, but I think you should use another substitution.
Comment: i agree but my teacher said use polar coordinates.@user108128
Comment: Another polar coordinates substitution is $x=r\cos$, $y=r\sin$ then $$\int_{-\pi/6}^{\pi/6}\int_{\cos t-\sqrt{4\cos^2t+3}}^{\cos t+\sqrt{4\cos^2t+3}}\cdots$$ I think this might be simple but not sure, try it if you want!
Comment: it looks very hard but i'll try@user 108128


Help proving statement in Lee's Introduction to Riemannian Manifolds about smooth curves into manifolds with nonempty boundary.

Question: The statement appears on page 33 of the second edition of Professor Lee's Introduction to Riemannian Manifolds. It is in the section on Lengths and Distances in Riemannian manifolds, but I think the statement may be generally true even if there is no Riemannian metric given for the manifold. Here is the relevant paragraph:
"Without further qualification, a curve in $M$ always means a parameterized curve, that is, a continuous map $\gamma\colon I\to M$, where $I\subseteq\mathbb{R}$ is some interval. ... To say that $\gamma$ is a smooth curve is to say that it is smooth as a map from the manifold (with boundary) $I$ to $M$. If $I$ has one or two endpoints and $M$ has empty boundary, then $\gamma$ is smooth if and only if it extends to a smooth curve defined on some open interval containing $I$. (If $\partial M\neq\varnothing$, then smoothness of $\gamma$ has to be interpreted as meaning that each coordinate representation of $\gamma$ has a smooth extension to an open interval.)"
I believe I have a correct proof of the statement for the case when $M$ has empty boundary. It is the parenthetical statement that follows, about the case when the boundary of $M$ is nonempty, that has me stymied. I have sketched a proof of one direction of that statement, namely the "if" direction. It is the "only if" direction that I can't get a handle on.
That is, I assume that $\gamma$ is smooth, $(U,\phi)$ is a smooth chart for $I$,
$(V,\psi)$ is a smooth chart for $M$, and $\gamma(U)\subseteq V$. I set
$\hat{\gamma}=\psi\circ\gamma\circ\phi^{-1}\colon\phi(U)\to\psi(V)$. By definition, $\hat{\gamma}$ (which is a coordinate representation of $\gamma$) is smooth, and I need to find an open interval $J$ which contains $\phi(U)$ and a smooth map $\Gamma\colon J\to\mathbf{R}^n$ such that
$\Gamma|_{\phi(U)}=\hat{\gamma}$. Here, I have assumed that $\dim M=n$. I tried to work on a simpler version of this problem, so I assumed first that $\phi(U)$ was open in
$\mathbb{R}$ (it could be open in the half-space instead). Then a plausible candidate for $J$ is $(\inf\phi(U),\sup\phi(U))$. But how would I define $\Gamma$ so as to match $\hat{\gamma}$? I know $\phi(U)$ is a countable collection of disjoint open intervals, but I haven't been able to figure out how to use something like a partition of unity to glue the restrictions of $\hat{\gamma}$ to each interval in the collection together to make $\Gamma$. That is mostly because I haven't come up with a reasonable  open cover for $J$. Also complicating things is that an interval which appears in $\phi(U)$ might actually have been flipped by $\phi$ compared to the interval it came from in $I$. For example, if $(-1,1)\subseteq I$, $\phi$ might multiply it by $-1$ but not do that to other nearby subintervals.
Can someone please offer some suggestions on how to go about proving the parenthetical statement.
Comment: Sorry, I just noticed this question. The whole issue of whether a coordinate representation can be extended to an interval is a red herring. I realize now that it's much easier to treat this case by embedding $M$ in a smooth manifold $\widetilde M$ without boundary and extending $\gamma$ itself as a map into $\widetilde M$. I've added this to my [list of corrections](https://sites.math.washington.edu/~lee/Books/RM/).
Answer: The condition

If $\partial M\neq\varnothing$, then smoothness of $\gamma$ has to be interpreted as meaning that each coordinate representation of $\gamma$ has a smooth extension to an open interval

is inadequate. It has to be replaced by

If $\partial M\neq\varnothing$, then smoothness of $\gamma$ has to be interpreted as meaning that each coordinate representation $\hat \gamma : \phi(U) \to \psi(V)$ of $\gamma$ has a smooth extension to an open subset $V \subset \mathbb R$ containing $\phi(U)$.

Let us recall the definition of a smooth map $f :A \to \mathbb R^k$ on an arbitrary subset $A \subset \mathbb R^n$ given in Appendix A (Review of Smooth Manifolds) p. 374 :

First, we note that when $U $is an open subset of $\mathbb R^n$, a map $F  : U \to \mathbb R^k$ is said to be smooth (or of class $C^\infty$) if all of its component functions have continuous partial derivatives of all orders. More generally, if the domain $U$ is an arbitrary subset of $\mathbb R^n$, not necessarily open (such as a relatively open subset of $\mathbb R^n_+$), then $F$ is said to be smooth if for each $x  \in U$, $F$ has a smooth
extension to a neighborhood of $x$ in $\mathbb R^n$.

Also have a look to p. 20 and p. 428 of [John M. Lee, Introduction to Smooth Manifolds, 2nd ed., Graduate Texts in Mathematics, vol. 218, Springer, New York, 2013].
Let us emphasize that the above requirement ($F$ has a smooth extension to a neighborhood of $x$) may be a bit misleading. It means that there exists an open neigborhood $W$ of $x$ in $\mathbb R^n$ and a smooth map $F_x : W \to \mathbb R^k$ such that $F_x \mid_{U \cap W} = F \mid_{U \cap W}$. It is therefore only relevant for points $x$ which do not belong to the topological interior of $U$ in $\mathbb R^n$.
Now consider your coordinate representation $\hat \gamma$. The chart $(\psi,V)$ maps $V$ to an open subset $V' \subset \mathbb R^k_+$. This set is open in $\mathbb R^k$ if $M$ has no boundary or $V$ is contained in the interior of $M$. Anyway, we regard $\hat \gamma$ as a map into $\mathbb R^k$.
$U$ is an open subset of $I$ which is mapped by $\phi$ to an open subset $U' = \phi(U) \subset \mathbb R_+$. This set is either open in $\mathbb R$ or contains $0 \in \mathbb R_+$. The above smooth extension condition is only relevant for $x = 0$ provided $0 \in U'$. In this case the definition of smooth says that there exists an open neighborhood $W$ of $0$ in $\mathbb R$ and a smooth  $\gamma^* : W \to \mathbb R^k$ such that $\gamma^* \mid_{U' \cap W} = \hat \gamma \mid_{U' \cap W}$. Then $\hat \gamma$ and $\gamma^* \mid_{W \cap (-\infty,0]}$ can be pasted to a smooth $\bar \gamma : U' \cup (W \cap (-\infty,0]) \to \mathbb R^k$ which is an extension of $\bar \gamma$ to an open set containing $U'$.
Why is it impossible to require that $\hat \gamma$ has a smooth extension to an open interval? The reason is simple: The set $\hat\gamma^{-1}(\partial M)$ is in general not be an interval, but the disjoint union of open intervals and at most one interval of the form $[0,r)$. We certainly find a smooth map $\gamma^* : (-s,r) \to \mathbb R^k$ extending $\hat \gamma \mid_{[0,r)}$, but $(-s,r) \cup U'$ is not an interval.
Comment: Thanks for your reply. It would be an acceptable answer if we knew that $\phi(U)$ was some kind of interval. But as I mentioned in the post, all I know is that $\phi(U)$ is open in $\mathbb{R}$ or the half-space, which is why I mentioned that in the former case, it was a countable union of open intervals. There can be gaps between the intervals, and what you suggested does not provide neighborhoods of points in the gaps and smooth maps on those neighborhoods.
Comment: @JeffRubin You are right. See my update.
Comment: This looks right to me, so I will accept this answer. I guess it should really be its own question, but I'd love to see a counterexample. That is, a specific example of a smooth map $\gamma\colon I\to M$ on some interval $I$, and some specific charts $(U,\phi)$ for $I$ and $(V,\psi)$ for $M$ such that $\hat{\gamma}=\psi\circ\gamma\circ\phi^{-1}\colon\phi(U)\to\mathbb{R}^n$ has no smooth extension to an open interval containing $\phi(U)$.
Comment: @JeffRubin I think you should ask a new question.
Comment: I have one further comment on this. After reviewing, it appears to me that the change for the parenthetical statement that would be more in line with how this is used later in the text in Theorem 4.24, is that whenever a coordinate representation is on an interval, then it can be extended to a smooth map on a containing open interval. I can prove the statement with this change.
Comment: @JeffRubin You are right, it is easy to see that in the definition of a *smooth map* $f$ is sufficient to restrict to charts with connected domains such that $f(U) \subset V$.
Comment: @PaulFrost Hi professor, could I ask your assistance [here](https://math.stackexchange.com/questions/4463142/let-be-x-a-connected-linearly-ordered-topological-space-so-if-y-is-a-nonemp), please? Forgive the bother.
Comment: @AntonioMariaDiMauro It seems that your question has been answered by the comments of  C Squared .
Comment: @PaulFrost Okay, I am cheerful for this. However could I ask your assistance [here](https://math.stackexchange.com/questions/4464693/prove-that-these-four-definition-of-t-3-space-are-equivalent) now, please? Forgive the bother.
Comment: @PaulFrost I'm sure I'm on the verge of a solution, but unfortunately it seems my mind suddenly clouded so that I thought I'd seek assistance from someone more experienced than myself.


javascript, combining AND, OR in an if starement

Question: I would like my code to be able to do the following:
IF (value1 is less than -1 AND variable2 does not equal either 6 or 5) then...
So far I could get a single if and to work as follows;
if ( (value < -1 && (day !== 6)) )  sendEmail(value)

but as soon as I add in the second or it falls over. What am I doing wrong? I have tried it in a few different ways but below are a couple of examples that did not work.
if ( (value < -1 && (day !== 6 || 5)) )  sendEmail(value)

if ( (value < -1 && (day !== 6 || day !== 5)) )  sendEmail(value)

Comment: The last line of code is closest, but think about the logic: if `day` is 6, then it's not equal to 5; if it's 5, then it's not equal to 6.
Answer: Think about your logic. Basically what you want is:
IF (value1 is less than -1 AND variable2 is not equal to 6 AND variable2 is not equal to 5)

Therefore your if statement can be written as:
if (value < -1 && day != 6 && day != 5) sendEmail(value);

Comment: @AdamLambert, if this answer helped you, please do me a favor and accept it by clicking on the checkmark under the upvote count. That will mark this question as answered and will give both you and me some SO Rep.
Answer: if(value < -1 && day !== 6 && day !== 5)  sendEmail(value)

should do the trick.


What is the minimal polynomial of $a$ over $\Bbb K$?

Question: I am studying algebraic elements over a field. The context started with the following discussions $:$
Let $\Bbb K$ be a field. Let $A$ be a $\Bbb K$-algebra. An element $x \in A$ is called algebraic over $\Bbb K$ if the substitution homomorphism $$\varepsilon_x : \Bbb K[X] \longrightarrow A$$ defined by $F(X) \mapsto F(x)$ has a non-zero kernel i.e. $\exists$ some non-constant polynomial $F \in \Bbb K[X]$ such that $F(x)=0.$ Since $\Bbb K$ is a field, $\Bbb K[X]$ ( the polynomial ring over $\Bbb K$ ) is a PID. So $Ker\ (\varepsilon_x)$ being an ideal of $\Bbb K[X]$ is principal. Therefore $\exists$ a unique non-constant monic polynomial $\mu_x \in \Bbb K[X]$ such that $Ker\ (\varepsilon_x) = \left \langle \mu_x \right \rangle.$ $\mu_x$ is called the minimal polynomial of $x$ over $\Bbb K.$ So by the first isomorphism theorem $\exists$ a $\Bbb K$-algebra isomorphism between $\Bbb K[X]/\langle \mu_x \rangle$ and $\text {Im}\ (\varepsilon_x) = \Bbb K [x]$ i.e. $$\Bbb K[X]/\langle \mu_x \rangle \cong \Bbb K[x].$$ Since $\Bbb K$-algebra isomorphisms are also $\Bbb K$-vector space isomorphism so we can say that $$\text {Dim}_{\Bbb K} \left (\Bbb K[X] / \langle \mu_x \rangle \right ) =  \text{Dim}_{\Bbb K}\left (\Bbb K[x] \right ).$$  But we know that $$\text {Dim}_{\Bbb K} \left (\Bbb K[X] / \langle \mu_x \rangle \right ) = \text{deg} \left (\mu_x \right ).$$ So we have $$\text{Dim}_{\Bbb K} \left (\Bbb K[x] \right ) = \text{deg} \left (\mu_x \right ).$$
Now for any $x \in A,$ $\Bbb K[x]$ is a $\Bbb K$-subalgebra of $A.$ So in particular if $A$ is a finite dimensional $\Bbb K$-algebra then $\Bbb K[x]$ is also a finite dimensional $\Bbb K$-subalgebra of $A.$ Therefore for any $x \in A$ we have $$\text{Dim}_{\Bbb K} \left (\Bbb K[x] \right ) < \infty.$$ Therefore for any $x \in A$ $$\text {deg} \left (\mu_x \right) < \infty.$$
This shows that if $A$ is a finite dimensional $\Bbb K$-algebra then every element of $A$ is algebraic over $\Bbb K.$
Now $\Bbb K^n$ is a finite dimensional $\Bbb K$-algebra. Let $a=(a_1,a_2,\cdots,a_n) \in \Bbb K^n.$ Then by our previous discussions it is quite clear that $a$ should be algebraic over $\Bbb K.$ Then my question is $:$
How do I find out the minimal polynomial of $a$ over $\Bbb K$?
Any help will be highly appreciated. Thank you very much.
Comment: No, for a unital $K$-algebra $A$ I define $P(X) = \sum_{m=0}^M c_m X^m \in K[X], P(a)= \sum_{m=0}^M c_m a^m \in A$ if $A = K^n$ then $a=(a_1,a_2,\cdots,a_n), P(a) : = (P(a_1),P(a_2),\cdots, P(a_n))$. That $A$ is a unital $K$-algebra means that the map $P(X,Y) \mapsto P(a,b)$ is a ring homomorphism $K[X,Y] \to A$ which is the identity on $K$ for all $a\in A$.
Comment: I think there is no general algorithm to achieve this.
Comment: To me $\mathbb{K}^n$ is a vector space, not an algebra.  How are you defining multiplication on $\mathbb{K}^n?$  ... perhaps element-wise?  And, related, what is the image of $\mathbb{K}$ inside $\mathbb{K}^n?$
Comment: The minimal polynomial of $a \in $ the $K$-algebra $ K^n$ is just $\prod_{b\in \{ a_j\}} (X-b)$, more interesting is when we put another $K$-algebra structure on the $K$-vector space $K^n$, and when we look at the minimal polynomials of elements of $M_n(K)$ a $K$-algebra containing all the degree $\le n$ extensions of $K$
Comment: But @reuns how does an $n$-tuple $(a_1,a_2, \cdots , a_n)$ be a zero of a polynomial in one single variable $X$? It should satisfy a polynomial in $K[X_1,X_2, \cdots, X_n].$ Isn't it so?
Comment: If $P(X) \in K[X]$ and $a \in K^n$ then $P(a) = (P(a_1),\ldots,P(a_n)) \in K^n$ and it is $0\in K^n$ iff $P$ has all the $a_j$ in its roots.  The generalization is [Caley-Hamilton theorem](https://fr.wikipedia.org/wiki/Th%C3%A9or%C3%A8me_de_Cayley-Hamilton).
Comment: @Brian Moehring I am defining component wise scalar multiplication of the elements of $\Bbb K^n$ with the elements of the field $\Bbb K.$ Then that scalar multiplication is compatible with the addition and multiplication in $\Bbb K^n.$
Comment: Oh! I can see now @reuns. Thanks for your help.
Comment: I think that you define $P(a) : = (P(a_1),P(a_2),\cdots, P(a_n)).$ Am I right @reuns?
Comment: I meant $P(X) \mapsto P(a)$ for all $a \in A$
Comment: That's exactly what I have said @reuns in my first comment above. But the definition in my book is wrongly described then I guess. The domain of the map $\varepsilon_x$ is depending upon the dimension of $A$ as a vector space over $\Bbb K.$
Comment: @mathmaniac. Note that scalar multiplication is defined canonically on $\mathbb{K}^n,$ so that wasn't what I was talking about.  The problem is that multiplication of two elements of $\mathbb{K}^n$ is not canonically defined, nor is the injective map $\mathbb{K} \hookrightarrow \mathbb{K}^n,$ both of which are necessary to define $\mathbb{K}^n$ as a $\mathbb{K}$-algebra.
Comment: What do you mean by the statement "multiplication of two elements in $\Bbb K^n$ is not canonically defined" @Brian Moehring?
Comment: For instance $\mathbb{C} \cong \mathbb{R}^2$ as an $\mathbb{R}$-vector space with canonical ordered basis $1, i,$ but with respect to this basis $\mathbb{R} \hookrightarrow \mathbb{R}^2 : x \mapsto (x,0)$ and $(a,b)\cdot (c,d) = (ac-bd, ad+bc),$ which obviously imbues $\mathbb{R}^2$ with a different $\mathbb{R}$-algebra structure than had we defined $(a,b)\cdot(c,d) = (ac,bd)$ and $x \mapsto (x,x)$
Answer: If you put just the "direct product of unital rings" algebra structure on $K^n$, then the minimal polynomial is the minimal monic one that has each of the $a_i$ as root; this is so by definition, since the evaluation of the polynomial in $(a_1,\ldots,a_n)$ is just the $n$-tuple of evaluations in each of the $a_i$. As mentioned in one of the comments, this polynomial can be written as $\prod_{b\in\{ a_1,\ldots,a_n\}}(X-b)$ (its degree is the number of distinct values among the$~a_i$).
Comment: By the way, there is no reason to write "$\Bbb K$"; this is not any reserved meaning of the symbol $K$, as it is just being used as a variable to denote some field.


SELECT multiple values and order by relevance

Question: I have the following structure:
CREATE TABLE IF NOT EXISTS `user_subjects` (
  `user_subject_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `subject_id` int(11) NOT NULL,
  PRIMARY KEY (`user_subject_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

and I want to get the user_ids that has subject_id 1 or 2, for example, ordered by relevance. (edit: i meant by how many results it matches)
I've tryed this but it doesn't count the relevance. It returns relevance 1.
http://sqlfiddle.com/#!2/944ab8/2
For that example i wanted to get
user_id relevance
1       1
2       2

and the subject_id matched if it's possible.
Thanks
Comment: What do you mean by "relevance"?  What's that column supposed to return?  Are looking for the `COUNT` of `subject_id` rows?
Comment: `subject_id LIKE 2` will return `TRUE` (`1`) if `subject_id` is `2` and `FALSE` (`0`) otherwise.
Comment: yes, the count of `subject_id`
Comment: Ok.  Just so you know, "relevance" was the wrong word there.  If you wanted the count, then just say that.
Comment: i'm sorry, then :) my fault
Answer: Something like the following will I think do what you want, although I'm not entirely clear what you mean by "relevance"; this simply counts the number of rows that match both the user and have subject_id 1 or 2:
SELECT
  user_id,
  COUNT(subject_id) AS relevance
FROM
  `user_subjects`
WHERE
  subject_id IN (1, 2)
GROUP BY
  user_id
ORDER BY
  relevance DESC

(This is mysql-specific, I believe, because of the use of relevance in ORDER BY.)
Comment: Yes, this is what I ment. I used the wrong term there. Thanks! But is it possible to get the matched subject_ids too?
Comment: +1 Moving subject_id IN check to WHERE clause is good here I think!
Answer: Note sure I follow. Do you mean something like this:
SELECT user_id
     , SUM(CASE WHEN subject_id IN(1,2) THEN 1 ELSE 0 END)ttl
  FROM user_subjects
 GROUP
    BY user_id;

?
Comment: @AlexSorinDachin a bit long but: `GROUP_CONCAT(DISTINCT IF(subject_id IN (1,2), subject_id, NULL) ORDER BY subject_id) AS subject_ids`
Comment: Yes, that's exactly what I meant. Thank you! But is it possible to get the matched subject_ids too?
Comment: @AlexSorinDachin `GROUP_CONCAT(distinct subject_id) as subjectids`
Comment: @AlexSorinDachin Again, not sure what you mean!
Comment: @ebyrob that will return all the subject_ids a user has, but i need only the matched ones
Comment: So 'relevance' was a complete 'red herring'!
Comment: @strawberry Yea, sorry. I meant 'by relevance' since a user wants to get the most matched results first.
Answer: Well, you'll never get a relevance of 2, because (subject_id LIKE 1) + (subject_id LIKE 2) will return 1 at most.
Maybe you should rethink your query.


Como Obter as propriedade do Jquery validate

Question: Estou com uma duvida sobre o validate do Jquery. consigo usar ele normalmente. porem preciso de uma validação caso o usuário escolha uma opção no formulário "SELECT > OPTION", tenho duas opção, "SIM","NÃO". Se o usuário escolhe "SIM" vai aparecer outro campo para ele preencher-lo, mais ta ai minha duvida, não estou conseguindo muda o attributo do rules do campos que não era obrigatório, para TRUE, caso ele clique em cadastrar e ele não tenha digitado nesse campos que apareceu.
Alguém ai tem uma sugestão, mais quero continuar usando o Jquery validate:
Aqui esta o meu Codigo JQuery:

$('#form-visitantes').validate({
rules: {
nomecompleto: {required: true},
sexo: {required: true},
fone: {required: true},
email: {required: true},
foi_convidado: {required: false} // esse campos nao e obrigatorio, ele so aparece no formulario caso o usuario informe fui convidado
},
messages: {
nomecompleto: {required: 'Campo Obrigatório'},
sexo: {required: 'Campo Obrigatório'},
fone: {required: 'Campo Obrigatório'},
email: {required: 'Campo Obrigatório'},
foi_convidado: {required: 'Campo Obrigatório'}

},
submitHandler: function (form) {
var dados = $(form).serialize();
$.ajax({
    type: "POST",
    url: URL_POST,
    data: dados,
    dataType: 'JSON',
    success: function (data) {
if (data.retorno === true) {
$(".msg-result").html('
' + data.mensagem + '
');
    document.getElementById("form-visitantes").reset();
} else {
$(".msg-result").html('
' + data.mensagem + '
');
}
    }
});
return false;
},
errorClass: "text-danger",
errorElement: "span",
highlight: function (element, errorClass, validClass) {
$(element).parents('.control-group').addClass('text-danger');
},
unhighlight: function (element, errorClass, validClass) {
$(element).parents('.control-group').removeClass('text-danger');
$(element).parents('.control-group').addClass('success');
}
});
Comment: Bem vindo ao [pt.so]. Percebi que está criando múltiplas perguntas para um mesmo problema, quando isso na verdade não vai lhe ajudar a conseguir uma resposta mais depressa, ao invés disso leia o guia [ask] e o faça um [tour], para aprender um pouco mais sobre o funcionamento do site para assim aumentar suas chances de conseguir uma boa resposta.Veja algumas orientações que vão te ajudar: [Guia de sobrevivência do Stack Overflow em Português](https://pt.meta.stackoverflow.com/q/8045) ([versão curta](https://pt.meta.stackoverflow.com/q/8089/101)).
Comment: Quando quiser colocar uma pergunta em evidencia faça uma edição que ela automaticamente vai para o topo da lista.
Comment: Remova essa questão. Como as duas estão em evidencia pode acontecer de fecharem as duas
Comment: Does this answer your question? [Jquery validate (Rules)](https://pt.stackoverflow.com/questions/426899/jquery-validate-rules)
Answer: Use o método .rules() do Validate para remover ou adicionar o required ao campo. Você pode fazer isso com o método .change() do select.
Por exemplo, o código elemento.rules("remove", "required") remove o required do campo, já o elemento.rules("add", "required") readiciona o required.
Veja um exemplo:

$("[name='convidado']").change(function(){
   $("[name='foi_convidado']")
   .attr("type", this.value == "nao" ? "hidden" : "text")
   .rules(this.value == "nao" ? "remove" : "add", "required");

   if(this.value == "nao"){
      $("#foi_convidado-error").remove();
   }

});

$('#form-visitantes').validate({
   rules: {
      foi_convidado: {required: false} // esse campos nao e obrigatorio, ele so aparece no formulario caso o usuario informe fui convidado
   },
   messages: {
      foi_convidado: {required: 'Campo Obrigatório'}
   },
   submitHandler: function (form) {
      console.log("form enviado");
   }

});

<form id="form-visitantes">
   <select name="convidado">
      <option value="nao">Não</option>
      <option value="sim">Sim</option>
   </select>
   <input name="foi_convidado" type="hidden">

   <button>Enviar</button>
</form>
Comment: Muito Obrigado Sam, agora entendi!


Why is the logistic regression hypothesis seen as a probability function?

Question: Why is the logistic regression hypothesis seen as a probability function?
I understand that we use it to predict 0 or 1, but still, why a function (the hypothesis) that outputs numbers between 0 and 1 may be considered a probability function?
Is this a heuristic?
Comment: this post may be helpful. Check the accepted answer. http://stats.stackexchange.com/questions/229645/why-there-are-two-different-logistic-loss-formulation-notations
Answer: No, it's not merely a heuristic. It's quite deliberately intended to be a model for the conditional distribution of the response.
Logistic regression is a particular case of a generalized linear model (GLM), in this case for a process where the response variable is conditionally Bernoulli (or more generally, binomial).
A GLM includes a specification of a model for the conditional mean of the response. In the case of a Bernoulli variable, its conditional mean is the parameter $p_i$, which is explicitly the probability that the response, $Y_i$ is $1$. It is modeled in terms of one or more predictors. Here's the model for the mean for a single predictor, $x_i$:
$$P(Y_i=1|x_i)=\frac{\exp(\beta_0+\beta_1x_i)}{1+\exp(\beta_0+\beta_1x_i)}$$
So it is (intentionally) a model for the probability that the response is $1$, given the value of the predictors.
The form of the link function $\eta=\log(p/(1-p))$ (and its inverse $p=\exp(\eta)/(1+\exp(\eta))$) is no accident either -- the logit link (which is what makes it logistic regression) is the natural (or canonical) link function for a binomial response. Other choices of link function are possible (and they, too will be models for the probability of a 1). Other common choices for a binomial response are the probit and the complementary log-log but the logistic is by far the most common.
Comment: Correct me if I am wrong but the function should be a proper scoring rule. In such cases it will reflect the probability.
Comment: @Cagdas The criterion being optimized in estimation GLMs is likelihood (though MLE can be seen as a special case of optimal score estimation). Are you casting the modelling of Bernoulli variables as a forecasting problem here?


How to code a superclass field that accepts multiple subclasses?

Question: I want to have a superclass that will be inherited by subclasses.
Let's say I want the superclass mother to be inherited by child.a and child.b.
So I make these classes
mother:
class mother(osv.osv):

    _name           = "mother"

mother()

child.a:
class child_a(osv.osv):

    _name           = "child.a"
    _inherit        = "mother"

child_a()

child.b:
class child_b(osv.osv):

    _name           = "child.b"
    _inherit        = "mother"

child_b()

now let's say I have a class a that have a many2one connection to mother
class a(osv.osv):

    _name           = "a"
    _columns        = {
        'mother' : fields.many2one('mother', 'Mother'),
    }

a()

Does mother field accept both class child.a and child.b. If yes how to code the create and write methods. If not how do I achieve this in any other way? (field accepting multiple subclasses)
Answer: No, a many2one referencing mother can't address records of class.aor class.b.
The inheritance method used for class.a and class.b actually copies the mother features. They create two new independent tables, copy of mother, containing independent data sets.
This means that the classes are not interchangeable in any way.
Records in child.a are not present in motherand vice-versa.
What you describe can be achieved with delegation inheritance - you can think that as class.x having a mother class "embedded" in it, through a special many2one relation.
This way, when you create a new class.x record, a new mother record is also implicitly created.
But this works one way: creating a new mother record does not create a class.x record.
An example of delegation inheritance in the core modules is res.users: a User "embeds" a Partner. When a new user is created, a new Partner is also created  for it.
Many2one relations to Partners will also be able to reference the User embedded Partners.  But many2one relations to Users will not be able to reference Partners that are not Users.
Comment: From the example two `many2one` fields are added to the `mother` but it doesn't enforce the creation of `mother` for every time a child is created does it? Isn't it more reasonable to add a required `many2one mother` field to the child instead? I still don't understand the concept.
Comment: The trick is to not think about it as actual "object inheritance", just instead think of "copying a model". To be honest, that inheritance method is only useful to extend a class in place. To create a derived class you should really use delegation inheritance.
Comment: But both derived classes (child_a,child_b) won't fit into one `many2one mother field` in model `a` will they?
Comment: `child_a` and `child_b` records both create and have "embedded" a `mother` record. A Many2one to `mother` can reference it's records created by `child_a` and `child_b` although afaik won't have dot-notation access to their child specific fields.
Comment: I kinda get the idea now, but I'm still unsure. From your suggestion I think the idea is to give access to the child classes from the mother class. But doesn't that mean that I need to edit my mother class every time a new child class is created which defeats the purpose of having an abstraction in the first place. Can you give an example based on my classes just to make sure I get the idea right.
Comment: Yes it can be confusing, I tried to give a real example in the answer.
Comment: Thank you it has gotten clearer now, Now from the example how do I handle partner creation through user creation? How do I fill all the required fields of partner? And how do I show partner field in the view? Using a related field?


Erro ao configurar Doctrine + Zend

Question: Olá,
Estou tentando configurar o Doctrine ORM para trabalhar com o Zend Framework, e quando dou o comando 'bin/doctrine-module' aparece o seguinte erro:
            PHP Fatal error:  Uncaught exception 'Zend\ModuleManager\Exception\RuntimeException' with message 'Module (DoctrineORMModule) could not be initialized.' in /var/www/html/zf2/vendor/zendframework/zendframework/library/Zend/ModuleManager/ModuleManager.php:195
    Stack trace:
    #0 /var/www/html/zf2/vendor/zendframework/zendframework/library/Zend/ModuleManager/ModuleManager.php(169): Zend\ModuleManager\ModuleManager->loadModuleByName(Object(Zend\ModuleManager\ModuleEvent))
    #1 /var/www/html/zf2/vendor/zendframework/zendframework/library/Zend/ModuleManager/ModuleManager.php(96): Zend\ModuleManager\ModuleManager->loadModule('DoctrineORMModu...')
    #2 [internal function]: Zend\ModuleManager\ModuleManager->onLoadModules(Object(Zend\ModuleManager\ModuleEvent))
    #3 /var/www/html/zf2/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php(444): call_user_func(Array, Object(Zend\ModuleManager\ModuleEvent))
    #4 /var/www/html/zf2/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php(205): Zend\EventManage in /var/www/html/zf2/vendor/zendframework/zendframework/library/Zend/ModuleManager/ModuleManager.php on line 195

    Fatal error: Uncaught exception 'Zend\ModuleManager\Exception\RuntimeException' with message 'Module (DoctrineORMModule) could not be initialized.' in /var/www/html/zf2/vendor/zendframework/zendframework/library/Zend/ModuleManager/ModuleManager.php:195
    Stack trace:
    #0 /var/www/html/zf2/vendor/zendframework/zendframework/library/Zend/ModuleManager/ModuleManager.php(169): Zend\ModuleManager\ModuleManager->loadModuleByName(Object(Zend\ModuleManager\ModuleEvent))
    #1 /var/www/html/zf2/vendor/zendframework/zendframework/library/Zend/ModuleManager/ModuleManager.php(96): Zend\ModuleManager\ModuleManager->loadModule('DoctrineORMModu...')
    #2 [internal function]: Zend\ModuleManager\ModuleManager->onLoadModules(Object(Zend\ModuleManager\ModuleEvent))
    #3 /var/www/html/zf2/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php(444): call_user_func(Array, Object(Zend\ModuleManager\ModuleEvent))
    #4 /var/www/html/zf2/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php(205): Zend\EventManage in /var/www/html/zf2/vendor/zendframework/zendframework/library/Zend/ModuleManager/ModuleManager.php on line 195

Fiz o download dos modulos através do composer, segue o arquivo:
   {
    "name": "zendframework/skeleton-application",
    "description": "Skeleton Application for ZF2",
    "license": "BSD-3-Clause",
    "keywords": [
        "framework",
        "zf2"
    ],
    "homepage": "http://framework.zend.com/",
    "require": {
        "php": ">=5.3.3",
        "zendframework/zendframework": "~2.3"
    },

    "minimum-stability" : "dev",
    "require-dev" : {
        "doctrine/doctrine-module": "dev-master",
        "doctrine/data-fixtures": "dev-master"
    },

    "config" : {
        "bin-dir" : "bin"
    }
}

E a configuranção do autoload está da seguinte forma:
  <?php

    return array(
        'doctrine' => array(
            'connection' => array(
                'orm_default' => array(
                    'driverClass' => 'Doctrine\DBAL\Driver\PDOMysql\Driver',
                    'params' => array(
                        'host'      => 'localhost',
                        'port'      => '3306',
                        'user'      => 'root',
                        'password'  => '',
                        'dbname'    => 'zf2',
                        'driverOptions' => array(
                            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'"
                        )
                    )
                )
            )
        )
    );

Comment: Da uma olhada nesse blog http://requirecode.blogspot.com.br/2016/06/instalar-o-doctrine-2-no-zend-framework.html vc encontrara o que vc precisa sobre zf2 e doctrine 2
Answer: Faltou, no composer.json, colocar o pacote doctrine/doctrine-orm-module:
"require": {
    "doctrine/doctrine-orm-module": "dev-master",
    "doctrine/doctrine-module": "dev-master",
    "doctrine/data-fixtures": "dev-master"
},

Além disso, como acredito que você vá usar os pacotes na sua aplicação em produção (e não apenas em desenvolvimento), coloquei-os no bloco require do composer.json.

Erro ao configurar Doctrine + Zend


Div flutuante não está funcionando direito

Question:
Preciso criar uma div flutuante no canto esquerdo do site. No entanto, ela está no meio do site e só vai acompanhar a rolagem de um certo ponto até outro. Como na imagem ilustrando, a div flutuante tem que ir do inicio do conteúdo até o final dele, parando antes da "barra".
Eu testei alguns códigos que achei pela internet mas nenhum funcionou direito, então eu meio que tentei fazer uns ajustes próprios.
Estou utilizando este código jQuery:
 var cartaz = SC(".cartaz-flutuante");
        SC(window).scroll(function(){
            var topo_cartaz = cartaz.offset().top;
            var y_fixo = 40;
            if (topo_cartaz < 40) {
                cartaz.animate({
                    top: y_fixo+SC(document).scrollTop()+"px"
                    },{duration:500,queue:false}
                );
            }
        });

A altura de '40" é apenas uma margem para dar a div, para não ficar totalmente encostada.
E aquele "if" eu tentei fazer para quando a altura da pagina ficar menor que a margem, o efeito de deslize da div começa a funcionar... Só que não está funcionando... E se eu tirar o if, até funciona, mas dai fica doidão e a div flutuante some se eu der um scroll total do site.
Comment: poderia colocar um exemplo no JsFiddle?
Comment: Se você alinhar o box conteúdo a direita e colocar a div flutuante como position: fixed, não resolve?
Comment: A estrutura do html\css é bem básica, como no desenho. A div que deve ser flutuante está "float left" e o conteúdo "float right". A div já está em absolute, o que posso fazer é deixar como "fixed", dai sim ela acompanha o scroll.. o problema é que não tem efeito, e preciso controlar o limite de movimento, já que ela fica fixa no site como um todo, indo do header até o footer, e não somente aonde quero.
Comment: Peguei a sugestão do @FredDutra e tentei criar código próprio. Pode ser visualizado aqui: http://jsfiddle.net/rmugb3j0/ mas não funcionou! HAHA Não sei por que. Mesmo assim dá para ter uma noção de como está meu código. A div flutuante desliza com a página e para no final da div do conteúdo, como programado. O problema é que quando dou scroll pra cima, a div não volta a acompanhar.. Como faço?
Answer: Existe alguns plugins JQUERY que pode servir para sua necessidade:
http://someweblog.com/demo/hcsticky/
http://dropthebit.com/demos/stickyfloat/stickyfloat.html
Comment: Poisé, mas o meu site já está com bastante plugin e não queria adicionar mais um. Pelo visto vou ter que usar mesmo, rsrs. Obrigado, vou dar uma olhada nesses links.
Comment: Peguei a sugestão do @FredDutra e tentei criar código próprio. Pode ser visualizado aqui: http://jsfiddle.net/rmugb3j0/ mas não funcionou! HAHA Não sei por que. Mesmo assim dá para ter uma noção de como está meu código. A div flutuante desliza com a página e para no final da div do conteúdo, como programado. O problema é que quando dou scroll pra cima, a div não volta a acompanhar.. Como faço?
Answer: Acredito que haja uma possibilidade de fazer isso sem a adição de Plugins.
HTML

Conteúdo da div

Conteúdo da div

Conteúdo da div

Esta div é estática

Conteúdo da div

Conteúdo da div

Conteúdo da div

CSS
body {margin: 0; padding: 0}
.conteudo{width: 100%; height: 300px; margin-bottom: 12px;}
#fixa_temporaria{width: 300px;  background: black; color: white; padding: 6px; position: relative; bottom: 0px; left: 0px;}

JS
var sticky_offset;
$(document).ready(function() {

    var original_position_offset = $('#sticky_for_a_while').offset();
    sticky_offset = original_position_offset.top;
    $('#fixa_temporaria').css('position', 'fixed');

});

$(window).scroll(function () {
    var sticky_height = $('#fixa_temporaria').outerHeight();
    var where_scroll = $(window).scrollTop();
    var window_height = $(window).height();

    if((where_scroll + window_height) > sticky_offset) {
        $('#fixa_temporaria').css('position', 'relative');
    }

    if((where_scroll + window_height) < (sticky_offset + sticky_height))  {
        $('#fixa_temporaria').css('position', 'fixed');
    }

});

Veja se isso funciona.. não testei ainda.
Dica: evite usar plugins, eles pesam, dão problemas com frequência e você não tem controle total sobre eles.
Comment: Exatamente. O site já tem bastante plugin e não queria usar mais um para algo simples. Ainda não testei, mas assim que der tempo, eu testo e comento novamente. Obrigado :D
Comment: Peguei a sugestão do @FredDutra e tentei criar código próprio. Pode ser visualizado aqui: http://jsfiddle.net/rmugb3j0/ mas não funcionou! HAHA Não sei por que. Mesmo assim dá para ter uma noção de como está meu código. A div flutuante desliza com a página e para no final da div do conteúdo, como programado. O problema é que quando dou scroll pra cima, a div não volta a acompanhar.. Como faço?
Answer: O que você está fazendo de errado é utilizar a propriedade position:absolute, utilizando o position setado como absolute o float não funciona.
Comment: Bah, agora não consigo mais testar usando meu modelo antigo. Acabei utilizando um plugin mesmo. Valeu.


How to get a footnote to appear in a bookpart title

Question: I have been struggling to get this to work. I have the following code:
<code>\language "english"
\book {
    \header {
        title = "Footnote Test"
    }

    \markuplist\table-of-contents
    \bookpart {
        \header {
            title = \markup \line {
    "Tests"
    \footnote "*"
    \concat {
        "*See test appendix in " \with-link #'appendix "Appendix A" } }
        }

        \tocItem tests "Tests"

        \score {
         \header {
           piece = "Test No. 1"
         }
         \new PianoStaff <<
           \new Staff \relative {
               \tocItem tests.testOne "Test No. 1"
             c'4 d e f |
             g a b c \bar "|." |
           }
           \new Staff \relative {
             \clef "bass"
             c4 b a g |
             f e d c |
           }
        >>
      }

    }

    \bookpart {
        \header {
            title = "Appendix A: Test Appendix"
        }

        \tocItem appendix "Appendix A: Test Appendix"

        \score {
         \new PianoStaff <<
           \new Staff \relative {
               \key c\minor
             c'4 d ef f |
             g af b c \bar "|." |
           }
           \new Staff \relative {
               \key c\minor
             \clef "bass"
             c4 bf af g |
             f ef d c |
           }
        >>
      }

    }
}

</code>
When I look at the generated PDF, I can see the footnote mark is correctly added to the title:

But the footnote is not present at the bottom of the page:

Am I notating this wrong? My code seems to follow the examples shown in the documentation for footnotes, but the footnote does not show up.
Answer: This is not caused by bookparts, but by the implementation of book titles and score titles. There is no real way around this, but what you can do is either to use a custom markup block instead of the title or to insert a "phantom" footnote directly at the beginning of the bookpart like this
<code>\markup \footnote \null \concat { "* See test appendix in " \with-link #'appendix "Appendix A" }</code>. The disadvantage of this is that it will add a little space between the bookpart title and the rest (the space is governed by the markup-markup-spacing).
Of course you could try to integrate such a phantom footnote into the table of contents or the first score, by which you'd be able to get past this small spacing problem.
Comment: @Dubl Glad I could help. You probably want a decent space under the title anyway.
Comment: Worked like a charm, thanks a lot! The extra space isn't too noticeable to me, so this looks good to me. I will mark this as the answer.


If I know the notes in a melody, how can I identify the scale that is being used?

Question: If I know the notes in a melody, how can I identify the scale that is being used?
Also, how do I find the higher octave notes in the same scale?
Here is an example piece:

I know the notes in the melody:

GBBB BABGA GBBB D+C+BAGA EAA GGGG F#E EAA BABAG
Sanu ek pal chain na aave BBBB BABGA Sanu ek pal chain na
  aave GBBB BABGA Sajna tere bina EAA GGGG F#E Sajna
  tere bina EAA GGGG  Dil jaane kyun ghabraave GABD+D+D+
  E+G+D+E+E+ Dil jaane kyun ghabraave GABD+D+D+ E+G+D+E+E+
  Sajna tere bina G+G+G+F#+F#+E+E+E+E+ D+B Sajna tere bina
  EAA GGGG
(from https://pianoenthalpy.blogspot.in/2018/02/sanu-ek-pal-chain-raid-rahat-fateh-ali.html)
Comment: Hey, welcome to the site. As it stands, this question is not a good fit for our format. It relies on an external link to make sense, which will be bad if the link goes away. The bigger problem is that it's very specific to a certain song, and won't be helpful to other people. Perhaps you can make your question more general? In fact, there are probably existing answers on this site that can help you. Maybe try some searching, and if you can't find an answer, updating this question to be less specific to that song?
Comment: Welcome. I've vtc because the question doesn't comply to policies on this site - analysing a particular song isn't much help to future visitors. Check the notes in the song, and the altered notes (# or b) will be a good clue to the scale used.
Comment: Rohan - on "how do I find the higher octave notes in the same scale?" - https://musicmotivated.com/guitar-and-bass-in-the-key-of-g/ should help, or if that's not useful, try searching for "g major scale guitar".
Comment: BTW I also searched and couldn't find a good answer to the 'general case' of this particular question - if we do find a helpful duplicate with a better answer than mine, this can always be pointed to it.
Comment: Where does the (erroneous) idea come from - that a song must only contain notes that are diatonic (from that key)???
Answer: Sometimes this can be quite a difficult thing to do; sometimes it's easier.
One thing we can try is identify the 'home' note that the song 'wants to go to', and then try to tell if the song sounds 'major' or 'minor'.
Often this might be a  common note in the piece, or a note that is sung at the end of lines.
In this case, we can see that 'G' is a common strong note in the piece. I also hear the piece as more 'Major' than 'minor' (some people would say that 'Major' is happy and 'minor' is sad, though it's more complicated than that!).
From this method, with your example, my guess would be that the key is G major, and that I could use notes from the G major scale.
Another method is look at the notes in the piece, and try to work out directly what key they fit in.
Here's a chart borrowed from this answer. (As Rockin Cowboy says, this chart is for Major Scales only. You can find similar charts on line for Minor Scales)

If we look at the notes in the piece, we can see only one 'sharp' - F#.
Looking at our table, we can see that agrees with our previous guess at the key - G major.
(It won't always be so easy, especially if you don't already have the notes written out with their enharmonically-correct names - but in this case, you do.)
So in your example case, we've used two methods, and both have given us the key/scale of G Major. Try it and see if it fits!
Comment: I played the same thing in C major using same notes and for F# i played the 4th fret D string and still it sounded like the song ,but my confusion is F# is not in C major ,then how come it's not sounding odd?
Comment: @Rohan sorry, I don't understand *"I played the same thing in C major using same notes"* - 'same notes' as what?
Comment: I played these notes in C major scale GBBB BABGA
GBBB D+C+BAGA
EAA GGGG F#E
                        as I have mentioned in the link.Although F# is not in C maj scale but I played the 4th fret of D string along with the given notes in a flow and still it's sounding fine.How come ?Since F# is not even in C major
Comment: @Rohan OK - so *what* was it that you played in *C* major? The song, and those notes, are all in G major.
Comment: @Rohan - a bit late - but a song doesn't only have to contain notes from a given key. Check out *modulation*.