Puppet install of Openstack: Could not find resource 'Package[dnsmasq-base]Package[dnsmasq-utils]' for relationship on 'Package[neutron-dhcp-agent]'

Question: ebug: Executing '/etc/puppet/etckeeper-commit-pre'
debug: catalog supports formats: b64_zlib_yaml dot pson raw yaml; using pson
err: Could not retrieve catalog from remote server: Error 400 on SERVER: Could not find resource 'Package[dnsmasq-base]Package[dnsmasq-utils]' for relationship on 'Package[neutron-dhcp-agent]' on node controller6.ec2.internal
warning: Not using cache on failed catalog
err: Could not retrieve catalog; skipping run

I must be missing something obvious, I have the packages dnsmasq, dnsmasq-base, and dnsmasq-utils installed on my Ubuntu 12.04 LTS server yet puppet is unable to find them. I'm running sudo puppet so I don't think this would be a permissions issue. Disabling the requirement in my params.pp let the installation continue (but it got hung up on a separate issue so I can't tell you if it would have worked had it finished). I've also tried with v3.2 and 3.3 of neutron, and the rest of the modules have the versions required of them by openstack. Lastly, if I disable neutron in the openstack all.pp I can get a working install of Openstack functioning (minus networking).
Hoping someone here has a hint or two for me, thanks for reading.
Edit
Wanted to add that I have since manually installed the neutron-dhcp-agent package in hopes of fixing this problem but have been unsuccessful.
Edit 2
   $dnsmasq_packages   = ['dnsmasq-base', 'dnsmasq-utils']

Line 105 in /etc/puppet/modules/neutron/manifests/params.pp
If I comment out the packages (replace with []) then it will continue past the point it errors out at.
Edit 3
I believe the problem originates here, /etc/puppet/modules/neutron/manifests/agents/dhcp.pp Any suggestions on how I should try to fix this? I'm going to put two checks instead of one and see how that goes.
include neutron::params

      Neutron_config<||>            ~> Service['neutron-dhcp-service']

 Neutron_dhcp_agent_config<||> ~> Service['neutron-dhcp-service']

  case $dhcp_driver {
    /\.Dnsmasq/: {
      Package[$::neutron::params::dnsmasq_packages] -> Package<| title == 'neutron-dhcp-agent' |>
      ensure_packages($::neutron::params::dnsmasq_packages)
    }
    default: {
      fail("Unsupported dhcp_driver ${dhcp_driver}")
    }
  }

Comment: Could also be a bug in puppet where its' behavior is different between versions.  It certainly wouldn't be the first time...
Comment: That seems like a flaw in the module that it's trying to compile into a catalog for the node; which specific module are you using?
Comment: I haven't ever tried this installer, but it's listing two packages as a single resource.  Syntax error where the required packages are listed, perhaps a missing semi-colon?
Comment: Thanks for the reply, here is a link to the module https://forge.puppetlabs.com/puppetlabs/neutron , pertinent files include ./neutron/spec/classes/neutron_agents_dhcp_spec.rb and ./neutron/manifests/params.pp:105
Comment: @yoonix I tried passing the packages one at time (each) and the install worked. Is this just a limitation of puppet? I find it difficult to believe that they would code something that simply doesn't work, that 2,754 people have downloaded, and that I would be the first to encounter the issue. I must be doing something wrong...
Comment: Thanks to both of your for your comments, I went ahead and modified the code and submitted a [pull request](https://github.com/philippedorman/puppet-neutron/commit/b09c4198cd7f0ddee1cbcf118d5e72810bb7da21), it fixed my problem, we'll see where it goes from here.
Answer: To fix the problem I followed the suggestions in the comments and split
$dnsmasq_packages   = ['dnsmasq-base', 'dnsmasq-utils']

into two lines, you can see the changes here.
For the sake of having everything in one place here are the changes:
manifests/agents/dhcp.pp
Starts on line 85
    case $dhcp_driver {
      /\.Dnsmasq/: {
 -      Package[$::neutron::params::dnsmasq_packages] -> Package<| title == 'neutron-dhcp-agent' |>
 -      ensure_packages($::neutron::params::dnsmasq_packages)
 +      Package[$::neutron::params::dnsmasq-base_package] -> Package<| title == 'neutron-dhcp-agent' |>
 +      Package[$::neutron::params::dnsmasq-utils_package] -> Package<| title == 'neutron-dhcp-agent' |>
 +      ensure_packages($::neutron::params::dnsmasq-base_package)
 +      ensure_packages($::neutron::params::dnsmasq-utils_package)
      }
      default: {
        fail("Unsupported dhcp_driver ${dhcp_driver}")

manifests/params.pp
Starts on line 93
 $metadata_agent_package = 'neutron-metadata-agent'
  $metadata_agent_service = 'neutron-metadata-agent'

 -    $dnsmasq_packages   = ['dnsmasq-base', 'dnsmasq-utils']
 +    $dnsmasq-base_package = ['dnsmasq-base']
 +    $dnsmasq-utils_package = ['dnsmasq-utils']

      $isc_dhcp_packages  = ['isc-dhcp-server']

Edit
Although the above fixed my problem while running Puppet 2.7.11, I recently upgraded to version 3.5.1 and the problem disappeared. So two potential solutions if you ever run into this :)


Guitar amplifier speaker replacement - different connector size

Question: I want to change the speaker on my Bugera v5 Infinium amp. The current speaker (a Turbosound) is apparently not too bad compared to the one used on the previous model of the V5, but I've found it buzzes at high volume and decided to install a better one.
I sent off for a Jensen C8R speaker, which I read was a good replacement. It arrived yesterday, but I have a problem with installing it.
The connectors on the cable that goes from the back of my amp to the speaker, and the connectors on the original speaker look like this:

However, the connectors on the new speaker look like this:

...so one of them is too wide for the connectors on the amp cable.
I have never changed a speaker before so I have no idea about what the standard sizes are. I just wanted to ask what would be the best solution for connecting the new speaker to my amp. If I need to buy a new cable that goes from the back of the amp to the new speaker, what exactly is that type of cable called? I've searched in Google but can't find anything that looks like the appropriate type.
Thanks for any help.
Answer: The speaker wire that runs from your amp to the speaker is a two conductor wire meaning that it has a side for the positive and negative terminal on the Speaker.  The objective is to supply the electrical current to the terminals.  To do that you need a solid contact.  The existing connectors have a female terminal that conveniently slides over the male terminals of the original speaker. The original design (with two different size terminals) made it impossible to accidentally connect the positive wire to the negative terminal and vice versa.  But as you have discovered, the replacement speaker has two terminals that are the same size.
I have good news.  First, the new speaker does label the positive and negative terminal with a + for positive and - for negative.  So you should have no trouble connecting it properly.  You should note that the new speaker has the positive and negative terminals on opposite sides than the original speaker (they are flip flopped).
Second, you won't need a new speaker wire (or cable).  You simply need a new connector.  If there is an electronics shop or auto parts store near where you live, you can take the speaker in and they can help you find the correct connector.  You will then need to cut the original connector off by cutting the wire as close to the connector as possible.  If there is not enough slack left after cutting the wire, you can use a splice sold at the same electronics store, to add a new piece of wire as an extension.  They make splices that you simply insert the two wires you wish to join into and clamp them with pliers.  A photo of the speaker wire will aid in determining what gauge wire you need to make an extension if needed.
If you don't want to cut the speaker wire to change the connector, you could buy a male blade terminal that fits the existing connector and a female connector that fits the new speaker and clamp them on either end of a short jumper wire of the appropriate gauge.  The picture below will show you the type terminals that you want.  You can order them online from an electrical supply company if you can determine what size - and if there is not an electronics or auto parts store near you.

If you or your friend have access to a soldering iron, instead of using the connector, you could solder the wire to the speaker terminal, but this would make future speaker replacement slightly less convenient.
Another thing to try, it prying the connector that is too small apart carefully with perhaps a dull knife blade and some pliers.  Then try to reshape it to fit the new connector and clamp it on with pliers and add some electrical tape for good measure.
Any of the suggestions above will work.  All you really need to do is provide good contact between the terminal and the speaker wire to make an electrical connection and be sure it is secure enough that it does not vibrate loose inside your cabinet.
Good luck.
Comment: Thanks very much, Rockin Cowboy and Tim for your replies. Of the various options mentioned, I thought that reshaping the smaller connector to fit the wider terminal could be the easiest (and cheapest) way to do it. I gave it a try using a small screwdriver and...fortunately it worked like a charm! Took literally less than a couple of minutes to reshape it so it fitted snugly on the wider terminal. Switched the amp back on and perfect. That has saved me a lot of hassle and some money too. Cheers!
Comment: PS. I don't know if you can put images in comments but here's a link to a pic of the finished job: http://postimg.org/image/vr4j9mtsr/ ...I didn't use any tape as it fitted pretty tight.
Comment: Good work @Aaron
Comment: Jolly good!   That's just what I was about to suggest.   Does it sound better?  Or was it something else rattling :-)
Answer: There are different sizes of spade connectors, so one solution would be to change the connector on the amp wire. However, to do this it could be crimped, or soldered properly. If it's soldering, then you might as well cut the offending connector off and solder the wire direct to the speaker. It's a better job, done properly, as the speaker may well not get changed again, ever. The important thing is to get the positive and negative the right way round - pos. is red, neg. blue or black. If you never have another speaker plugged in as well, it actually won't affect anything. Solder on!


Office 2016 O365 "Something went wrong we couldn't start your program"

Question: I have used days trying to find out what is causing this.
We have a Citrix environment that is now moving over to Office 365. Have installed Office 2016 O365 on many other Citrix environments without much issue. But in this one I'm getting an error when a user tries to start Office.

I can not find any error codes anywhere, not in the error itself, not in event viewer.
I have tried the most things suggested by other forums without any resolution.
Tried repair, reinstall, done a SFC /scannow
Done a manual uninstall with deletions of registry keys, folders, tasks and services. Nothing seems to help.
There are no antivirus enabled, and also tried disabling firewall.
Install configuration:
<code><Configuration>
    <Add OfficeClientEdition="32" Channel="Current">
        <Product ID="O365ProPlusRetail">
            <Language ID="en-us"/>
            <Language ID="nb-no"/>
        </Product>
        <Product ID="VisioProRetail">
            <Language ID="nb-no"/>
            <Language ID="en-us"/>
        </Product>
        <Product ID="ProjectProRetail">
            <Language ID="nb-no"/>
            <Language ID="en-us"/>
        </Product>
    </Add>
    <Display Level="None" AcceptEULA="TRUE"/>
    <Logging Level="Standard" Path="%windir%\Logs"/>
    <Property Name="SharedComputerLicensing" Value="1"/>
</Configuration>
</code>
But have tried with many other install configurations with the same result.
This is office version 16.0.7369.2038
But I have also tried with Office 2013 O365 with the same result.
Here is my latest install logg if that helps: http://pastebin.com/Npd7vwy9
Please help me find out what is causing this, I cant find anything more to try.
Thank you in advance for any help.
Comment: Can't help you. But have you tried the official Microsoft technical support (via phone)? If they can't solve it within 1-2 hours, ask them to escalate the issue and they will usually get you in touch with an engineer. They always solved my issues. Support is free for Office 365 customers.
Comment: That may be the next step. But I know it is an issue with my environment since I have no issues on the other. So I think Microsoft just will blow it off with that.
Answer: After many many hours of research I found out that a GPO with security settings to the start menu caused this. (Not with the help of microsoft that I escalated the case to) I rebuild the GPO step by step to find out when it failed. I still have no idea why it needed access to the start menu.
"%AllUsersProfile%\Microsoft\Windows\Start Menu"
But now it works again, and I'm happy.
Maybe it can help others.
Hate that we get NO indication what so ever what is wrong when Office 365 wont start.


FirebaseAuthInvalidCredentialsException when using "One account per email address"

Question:
... if you don't allow multiple accounts with the same email
  address, a user cannot create a new account that signs in using a
  Google Account with the email address firstname.lastname@example.com if there already is
  an account that signs in using the email address email@example.com and a
  password.

I was able to sign in with Google provider for the same email that was already registered via Email provider, so Google provider replaced Email provider and latter then fails to sign in with FirebaseAuthInvalidCredentialsException: The password is invalid or the user does not have a password..
Steps to reproduce:
Sign up with Email provider
-> Sign out
-> Sign in with Google provider
-> Sign out
Basically it should not allow to replace one provider with another and throw FirebaseAuthUserCollisionException: The email address is already in use by another account.
Some code that I use for sign in/sign out:
<code>  public void signUpEmail(String email, String password) {
    mFirebaseAuth.createUserWithEmailAndPassword(email, password)
        .addOnCompleteListener(this, task -> {
          if (!task.isSuccessful()) {
            Log.e("signUpWithEmail", task.getException());
          }
        });
  }

  private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    mFirebaseAuth.signInWithCredential(credential)
        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
          @Override public void onComplete(@NonNull Task<AuthResult> task) {
          if (!task.isSuccessful()) {
            Log.e("signInWithCredential", task.getException());
          }
        }
    });
  }

  public void signInEmail(String email, String password) {
    mFirebaseAuth.signInWithEmailAndPassword(email, password)
        .addOnCompleteListener(this, task -> {
          if (!task.isSuccessful()) {
            Log.e("signInWithEmail", task.getException());
          }
      });
  }

  public void signOut() {
    Auth.GoogleSignInApi.signOut(mGoogleApiClient);
    mFirebaseAuth.signOut();
    startSignInActivity();
  }
</code>
Thank you!
Comment: A lot would probably depend on the code here. Anything minimal, but complete, that you can share?
Comment: Added some code and couple of clarifications.
Comment: for the quote you have from firebase can you show your reference. i cant find it on line
Answer: To optimize the login UI steps and enhance account security, Firebase Authentication has a concept of 'trusted provider', where the identity provider is also the email service provider. For example, Google is the trusted provider for @gmail.com addresses, Yahoo is the trusted provider for @yahoo.com addresses, and Microsoft for @outlook.com addresses.
In the "One Account per Email address" mode, Firebase Authentication  tries to link account based on email address. If a user logins from trusted provider, the user immediately signs into the account since we know the user owns the email address.
If there is an existing account with the same email address but created with other credentials (e.g. password or non-trusted provider), the previous credentials are removed for security reasons.
A phisher (who is not the email address owner) might create the initial account - removing the initial credential would prevent the phisher from accessing the account afterwards. The legit user can set up a password by going through the password reset flow, where she would need to prove she owns the email address.
Comment: I believe this explains why Google Sign In overwrites the email address provider credentials.
Comment: i dont see iOS having this behavior.  is it just android that does this ?
Comment: The behavior is the same across Anroid/iOS/Web.
Answer: Multiple accounts per email address will create a new user with a different uid for different providers using the same email.
To recreate:

Sign in with google email x@x
Sign in with facebook email x@x
Create email password account x@x

Now you'll get 3 different users.
If you use the strongly recommended single accounts per email, the 3 providers above would be within the same user (one uid).
When you first create the google account x@x and try to sign in with new facebook account with email x@x, you will get an error that linking is required to proceed. You will then have to sign in the first google user and link the new facebook user to it.
Comment: Thank you, the thing is that I was getting FirebaseAuthInvalidCredentialsException instead of linking required error so it was not clear what's wrong
Comment: I see, I understand your question now. I think in the one account per email, this may be intended. Typically linking would be triggered when you sign in with the same email using a different provider. However this is   a special case. Since Google emails are verified and email password providers in this case are not, you will sign in directly without linking to your email account. However, I will check if the password provider being deleted is also part of this intended behavior.
Comment: @bojeil It really deletes the password when you sign-in with Google. I get the security reasons behind that. The problem is that it's done silently. And you can't alert the user that his password will be deleted. As a workaround, I was thinking about changing my authentication to allow multiple accounts per email. But since every pair of email/sign-in-method will be considered a different account and thus have a different UID, I would have to use the user's email as the userID to store user data inside my Firestore. Would that cause any troube in some Firestore security rules cases?
Comment: Yes that would be a problem. The problem is someone could camp on your email. I can setup an account with your email and my password. I then wait for you to create your account (imagine it's a popular app). If my password remains on the account, then I have full access to your account. If you bypass this measure and allow access to both accounts via security rule (keying account by email), then the attacker will have access to the real user's data too.


Cannot assign value of type '()' to type '[customObject]' - while in a completion handler

Question: I'm trying to reload a collection view after the json data has been updated but am running into the error:

Cannot assign value of type '()' to type '[ChannelInfo]'

This is how I have the custom object 'ChannelInfo' setup:
class ChannelInfo: NSObject {

  var logo: String?
  var channelName: String?
  var id: NSNumber?

  init(logo: String, channelName: String , id: NSNumber) {

    self.logo = logo
    self.channelName = channelName
    self.id = id
  }

  init(resDictionary: [String:Any]) {

    logo = resDictionary["artwork_608x342"] as? String
    channelName = resDictionary["name"] as? String
    id = resDictionary["id"] as? NSNumber

  }

  static func updateAllChannels(completionHandler:@escaping (_ channels: [ChannelInfo]) -> Void){

    let nm = NetworkManager.sharedManager// singleton handles network connections and json parsing

    nm.getJSONData(urlExtension: "channels/all/0/50", completion: {
      data in

      var channels = [ChannelInfo]()

      if let jsonDictionary = nm.parseJSONFromData(data)
      {
        let resultsDictionaries = jsonDictionary["results"] as! [[String : Any]]
        for resultsDictionary in resultsDictionaries {// enumerate through dictionary
          let newChannel = ChannelInfo(resDictionary: resultsDictionary)
          channels.append(newChannel)
        }
      }
      completionHandler(channels)

    })
  }
}

This is how I reload the collection view after the json objects have been updated:
 var channelArray: [ChannelInfo] = []

      override func viewDidLoad() {

        channelArray = ChannelInfo.updateAllChannels(completionHandler: { _ in

        self.channelCollectionView.reloadData()
        })//Error happens here starting with 'channelArray'
    }

I get the feeling I may be missing a step, any help is appreciated.
Comment: Typically this message means you're assigning a function/closure to something that should be a class/struct type. Double check your code and option click your variables to ensure when you add anything to your array, it's of the type you expect. It may also help to clear your derived data and re run.
Comment: As another note, as far as guidelines for Swift syntax, try to be more robust in naming conventions, `let nm` should be `let networkManager` or something robust and contextually relevant. You shouldn't simplify anything that way. Just overall good coding habits and it follows the Swift API guidelines (don't abbreviate).
Comment: So were you thinking of telling us _which line_ gets this error?
Comment: Whoops, I updated the code with the error, it happens in the viewDidLoad where channalArray = ...
Comment: Okay, well, the mistake is very simple and easy to explain. What I can't explain is what you think you're doing. :( But I'll explain the error...
Answer: Okay, let's take this one step at a time. You are saying
ChannelInfo.updateAllChannels...

So let's look at how that updateAllChannels method is declared:
static func updateAllChannels(
    completionHandler:@escaping (_ channels: [ChannelInfo]) -> Void){

So this a static function that returns no result.
But what you are actually saying is:
channelArray = ChannelInfo.updateAllChannels...

But we have just established that updateAllChannels returns no result. So there is nothing there for you to assign to channelArray. The whole notion of assignment here makes no sense. And the compiler is telling you so. You can't have this assignment channelArray =. Delete that part.

I think (but don't quote me) that your larger problem is that you are ignoring the value returned to the completion handler. You have this:
ChannelInfo.updateAllChannels(completionHandler: { _ in
    self.channelCollectionView.reloadData()
})

See the _ in at the end of the first line? I think that's your whole issue. updateAllChannels is handing you back the channels as the parameter and you are throwing them away. Instead, I think you want something like this:
ChannelInfo.updateAllChannels(completionHandler: { channels in
    channelArray = channels
    self.channelCollectionView.reloadData()
})

Comment: I think I see what you mean.  But how can I call the function "updateAllChannels" so I can reload the collection view with the new json data?
Comment: That is what you _are_ doing, isn't it? You are calling `updateAllChannels` along with a completion handler that calls `reloadData`. So you _are_ reloading the collection view.
Comment: I am but the error : Cannot assign value of type '()' to type '[ChannelInfo]' is occurring
Comment: But I told you what to do about that. Delete `channelArray =`. You can't say that.
Comment: It looks like I did a poor job of explaining why I did the channelArray =..., I'm trying to update the local channelArray by calling the updateAllChannels function.  The local channelArray is connected to what is shown in the collection view, if it's not updated the collection view is blank.
Comment: But I told you how to fix that too.
Comment: essentially I'm trying to make the channelArray to be equal to the [ChannelInfo] the updateAllChannels returns in its completion handler
Comment: oh, I didn't see the 2nd part of your answer, I'll try that out
Comment: More than trying it, think about what I'm telling you in my answer.
Comment: That did it! Thanks for your help and patience!


How to obtain number of entries in ELF's symbol table?

Question: Consider standard hello world program in C compiled using GCC without any switches. As readelf -s says, it contains 64 symbols. It says also that .symtab section is 1024 bytes long. However each symbol table entry has 18 bytes, so how it is possible it contains 64 entries? It should be 56 entries. I'm constructing my own program which reads symbol table and it does not see those "missing" entries as it reads till section end. How readelf knows how long to read?
Answer: As one can see in elf.h, symbol entry structure looks like that:
typedef struct elf32_sym {
  Elf32_Word    st_name;
  Elf32_Addr    st_value;
  Elf32_Word    st_size;
  unsigned char st_info;
  unsigned char st_other;
  Elf32_Half    st_shndx;
} Elf32_Sym;

Elf32_Word and Elf32_Addr are 32 bit values, `Elf32_Half' is 16 bit, chars are 8 bit. That means that size of structure is 16 not 18 bytes. Therefore 1024 bytes long section gives exactly 64 entries.
Answer: The entries are aligned to each other and padded with blanks, therefore the size mismatch. Check out this mailthread for a similar discussion.
As for your code, I suggest to check out the source for readelf, especially the function process_symbol_table() in binutils/readelf.c.
Comment: Maybe I misunderstood something, but if entries were anyhow padded, would a lesser number of them be contained in 1024 bytes? I do not see any padding, because by reading entries one directly after another I get exactly the same results as 56 first entries reported by readelf. And if I read some more I will also have good results. The problem is: how would I know where to end? Size reported in `.symtab` section header is 1024 bytes and standard says about this value "This member gives the section's size in bytes."
Answer: The file size of an ELF data type can differ from the size of its in-memory representation.
You can use the elf32_fsize() and elf64_fsize() functions in libelf to retrieve the file size of an ELF data type.


Pointing MX at mail server where domain isn't hosted?

Question: I am working on a system where we have Moodle software on one domain (I'll call it moodlehost.com) which is making a LOGIN connection to a SMTP server on another domain (I'll call it smtphost.com). I was brought in to work on the Moodle side of things, but I've ended up going some DNS work too, though I'm not an expert on DNS or server admin.
I have the Moodle software on moodlehost.com logging into the SMTP server on smtphost.com, with SPF on smtphost.com configured to approve email from the moodlehost.com IP. It's working nicely and passing all spam-filter checks with flying colors. Note: The MX for smtphost.com is a mail server which I'll call underlyingsmtp.com.
** Edit per request from Tim below: To establish a connection to the SMTP server from Moodle, I type in smtphost.com with port 587. However, the MX record for smtphost.com points to a different mail server, underlyingsmtp.com. (Now that you ask about it, I recall that the MX is only for INCOMING mail, right? So the MX record for smtphost.com would be irrelevant to outgoing mail sent through smtphost.com? In that case, my question is the same: Why would I point the MX record for moodlehost.com at the same address as the MX record on smtphost.com?)
The system admin who runs the system I'm working on wants me to set MX records on moodlehost.com so they point to underlyingsmtp.com, even though moodlehost.com doesn't exist on that server and any incoming mail @moodlehost.com bounces as a result. His explanation is "Mixing the sends is (mostly) where a backlisting can possibly occur. All or nothing is best with forwarded mail, that's all."
Again, I'm not a server guy, but this doesn't make any sense to me. As soon as moodlehost.com hands off the outgoing mail to the SMTP server on smtphost.com it's out of the picture, and the outgoing emails are all passing SPF, DKIM, and DMARC. I don't see how pointing the moodlehost.com MX at underlyingsmtp.com helps, and it actually seems like it might look suspicious if we're pointing MX at a mail server where we don't have an account so any incoming mail bounces.
Could anyone help me understand if pointing the MX at underlyingsmtp.com makes sense, and if so, why? Thanks very much for your time.
** Edit: We don't anticipate having any incoming mail to moodlehost.com, but if we do it certainly can't and won't be handled by underlyingsmtp.com. The server that HAS been handling incoming mail is moodlehost.com. It's the only one that would do so. If we point the MX records elsewhere, mail will simply bounce.
My question is this: If I have a script on site A making an SMTP connection to server B in order to send mail, is there any reason why site A's MX records would also need to point to server B?
Comment: I think you need to really work out what server handles your incoming mail. MX records are for incoming email only, but you also need to consider SPF regarding outgoing email.
Comment: Your question confuses me. Please edit your question to make the relationship between smtphost.com and underlyingsmtp.com more clear. Email and web hosting are completely independent.
Comment: Tim, thanks for requesting clarification. I've edited it above. Now that you asked, I believe the MX record pointing to what I called (incorrectly?) underlyingsmtp.com would be irrelevant? At any rate, hopefully my edit above clarifies things.
Comment: Not confident enough for an 'answer', but: my gut instinct is the same as yours.  There's no formal reason I know of why the MX needs to be the same as the server(s) from which outgoing mail originates, and several reasons why it wouldn't be.  I am, as always, happy to be corrected though :)
Comment: Tim: We don't anticipate having any incoming mail to moodlehost.com, but if we do it certainly can't and won't be handled by underlyingsmtp.com. The server that HAS been handling incoming mail is moodlehost.com. It's the only one that would do so. If we point the MX records elsewhere, mail will simply bounce.
Comment: I'm still confused. I think perhaps you need to explain this to someone in person, doesn't matter if they understand it or not, as it'll help you get it straight in your head and identify the core problem. Right now you have six verbose paragraphs and no clear question. Until there's a clear question we probably can't help much.
Comment: Tim, thanks for your patience as I try to explain this clearly. I summarized my question in bold text above. Clear enough?
Answer: Core question: If I have a script on site A making an SMTP connection to server B in order to send mail, is there any reason why site A's MX records would also need to point to server B?
No. MX records specify the server that handles incoming email for an individual domain. Any other domain is irrelevant, including domains that send to it.
Comment: Tim: Thank you again. One last question, if I may, before I mark this answered. The concern that the system admin expressed was about blacklisting, i.e. that spam filters would object to having the moodlehost.com MX record pointing to moodlehost.com while a script at moodlehost.com was sending out email through an SMTP server at another domain. Is there any reason to think that would look suspicious and get us blacklisted?
Comment: That's a valid concern, but it's unrelated to MX records. For that you need to look at [Sender Policy Framework](https://en.wikipedia.org/wiki/Sender_Policy_Framework). Basically you set up a DNS record that specifies which servers can send email on behalf of the domain.
Comment: Right, I have SPF set up and emails are passing SPF checks. Thank again for your time on this.
Comment: No problem. Sometimes half the challenge is working out what the question is.


Confusion on modes

Question: I'm a bit confused about the modes. I'm learning them by ear through this app, where the app explains what to listen for. For instance: dorian has 2b (flats), and lydian has 1# (sharp).
The thing I'm confused about: does lydian always have 1# in it? or dorian 2b? Doesn't this depend upon which major scale and mode? Or is the fixed amount of flats and sharps only applying if all modes are starting from C?
Comment: Note that it may look like a confusing approach to learn modes starting from the same note (C in your case), as they are derived from the major scale, just starting from a different note. But actually musically it's a good approach as it teaches you how they sound different starting with the same note
Comment: Take a look at my answer on this related question, it might be helpful to you: https://music.stackexchange.com/questions/110215/i-am-confused-about-modes-can-someone-explain-it-in-these-terms/110232?noredirect=1#comment239038_110232
Comment: @Kaddath  Agreed, but I'd suggest getting used to the sound of the modes in one key (say, C major) as well.
Comment: @ScottWallace yes it's useful too, I use it sometimes to change mode for a short time while staying in the same scale. It's more natural in my case because I play bass which has evenly spaced notes and strings (a mode pattern stays the same across the fretboard), while the inverse needs some work. It may be the contrary on other instruments, I don't know
Comment: @Kaddath - no, it's similar on other instruments, depending on how they're tuned.  The patterns pertain to all.
Answer: It's common to describe modes (or any seven-note scales) by how they compare to the major scale- major is sort of the "default" scale in western music and music theory.
Lydian has one sharp added to the parallel major scale.  It could be described as 1-2-3-#4-5-6-7.
Dorian has two flats added to the parallel major scale.  It could be described as 1-2-b3-4-5-6-b7.
You're right to think that if you start with a major scale with 3 flats (Eb major) and add the two flats to make Eb dorian, you end up with 5 flats.  Or, if you added a sharp to make it lydian, you're returning the Ab to A natural- so the scale has 2 flats.
Comment: @9769953 a parallel minor is not a minor third away from the major scale, parallel means they share the same root note. The minor scale a minor third below a major scale is called the relative minor, the answer's use of parallel is the correct!
Comment: @OwenM Thanks. Then it is (or was, now) just my lack of knowledge about this idiom and use of parallel.
Comment: With "parallel major scale", you mean equivalent major scale here (they're not equivalent either, but parallel makes me think of parallel minor scale, which is a minor third away from the major scale. Here, the major and Lydian scales are a perfect unison apart, which confused me a bit).
Comment: @9769953 yup, the terms are all a bit vague and easy to mix up!
Answer: I find it helpful to think of the pitches as "raised" and "lowered" to avoid confusion. So Lydian, for example, has one raised pitch compared to major. The actual note name could be natural or sharp (or even double sharp), but it will still be "raised" in comparison to major.
Some concrete examples for Major and Lydian:

C Major / C Lydian
C D E   F    G A B C
C D E   F#   G A B C

C# Major / C# Lydian
C# D# E#   F#   G# A# B# C#
C# D# E#   Fx   G# A# B# C#

Db Major / Db Lydian
Db Eb F   Gb   Ab Bb C Db
Db Eb F   G    Ab Bb C Db

In the three Lydian scales shown, the changed pitch can be sharp (C Lydian), double-sharp (C# Lydian), or natural (Db Lydian), but it's still raised from its position in the corresponding major scale.
Comment: @mathlander Good catch. I actually left it out on purpose, because Fb major is so exceedingly rare.
Comment: I think you forgot a double flat raised to a single flat. (Fb major vs Fb Lydian)
Comment: So is C# major... (Even in classical music, which usually cares a lot about enharmonicity, Beethoven chose to use Db major for Moonlight Sonata Mvt 2 and Chopin used Db major for the middle section of Fantaisie Impromptu!)
Comment: Also, if you really care about how common something is, you should use F major for your last example.
Comment: @mathlander You're walking a fine line between offering constructive suggestions and attacking me personally.
Answer: Being told by the app that a mode 'has one sharp', or 'has two flats' in itself is pretty useless. Unless it also highlights which number notes are affected.
It's not like 'there's a major key with one sharp', - which we all recognise as key G. And that sharp is the sharpened leading note, compared with the natural (F).
It's of paramount importance, therefore, to designate which note/s gets the sharp/flat - in comparison with the basic major scale.
So Lydian (with one sharp - that is vague) is the same as the major scale, BUT its 4th is sharpened. Mixolydian has one flat, BUT that is its 7th note, flattened when compared with its parallel major scale. G A B C D E F, compared with G A  B C D E F♯. But even that's confusing - we just read that Mixolydian has one flat - there's not a flat in sight. It's the 7th note that's been flattened, producing F♮!
I'd hesitate to use the site or app that describes modes that way - I think it's quite confusing. There are far better ways in which to get to understand modes.
Answer: Here's what the other answers miss:

It's unnecessarily complicated to think of modes as scales that you build.
Modes, like most other scales, indicate tonal relationships. Unlike other scales, in addition to establishing tonal relationships like tonal centers, modes also indicate tonal parentage.

Think of modes as essentially rotations of a major scale. The formula for each mode is derived from its relationship to its parent scale. Understanding the mode names and how they relate to the parent scale helps us understand why the formulas are built the way they are.
Let's see it in action:
Ionian (Major): C D E F G A B (1 2 3 4 5 6 7)
Now if we rotate this scale and go from "D" to "D", we get:
D E F G A B C
Cool, "D" is our tonal center now, but it's not "D major", in fact, we don't want it to be "D major" because we want to use the language of "C major" but with "D" as our tonal center.
So if we look at what's different between "D major" and this scale, we see that we're missing the "F#" and "C#".
This gives us "D Dorian" with a formula of 1 2 b3 4 5 6 b7, with the "b3" & "b7" representing "lowered" notes, in this case, "F", which would be "F#", and "C", which would be "C#" in D major. These are scale degrees that we altered from "D major" to fit our language of "C major".
Now let's rotate the same scale but starting on "F":
F G A B C D E
So, "F" is our tonal center but we're continuing to use the language of "C Major". Well, relative to "F Major", there is one note different, "B", which should be "Bb". So, we represent the formula as:
1 2 3 #4 5 6 7
to indicate that the 4th degree has been raised. Again, "F" is our tonal center, but keeping the language of "C major".
In order of scale degree the modes are:

Ionian
Dorian (b3 & b7 for parent scale)
Phrygian (b2, b3, b6, b7 for parent scale)
Lydian (#4 for parent scale)
Mixolydian (b7 for parent scale)
Aeolian (b3, b6, b7 for parent scale)
Locrian (b2, b3, b5, b6, b7 for parent scale)

Because all major scales in 12-EDO equal-temperament are all built using tetrachords, these formulas work for all rotations of all keys.
Hope that helps!
Comment: In highschool, my teacher taught us to memorize the modes like this: "I Did Pot Leave Me Alone Lady"
Comment: @JacobIRR - that's odd. 'I don't play like my aunt Lou' makes more sense.
Answer: All modes contain the same repeating sequence of 7 pitch classes.  The only difference is where in the sequence you start.

do-re-mi-fa-sol-la-ti-do = Ionian (major)
re-mi-fa-sol-la-ti-do-re = Dorian
mi-fa-sol-la-ti-do-re-mi = Phrygian
fa-sol-la-ti-do-re-mi-fa = Lydian
sol-la-ti-do-re-mi-fa-sol = Mixolydian
la-ti-do-re-mi-fa-sol-la = Aeolian (natural minor)
ti-do-re-mi-fa-sol-la-ti = Locrian

Personally, I think that the traditional names of the modes are a needless complication imposed by academic types who still buy into the silly idea that speaking in Greek makes one sound "smarter".  I prefer to just call them do-mode, re-mode, etc.  Nevertheless, since that terminology seems to be "confusing" to some people, I will use the Greek names in this answer.
Now, let's assign each note a number from 0 to 11 based on the usual convention of twelve equal semitones in an octave: do=0, re=2, mi=4, fa=5, sol=7, la=9, ti=11.  (That's one semitone for the mi-fa and ti-do intervals, and two semitones for the others.)

Ionian (do) mode = 0-2-4-5-7-9-11-0
Dorian (re) mode = 2-4-5-7-9-11-0-2
Phrygian (mi) mode = 4-5-7-9-11-0-2-4
Lydian (fa) mode = 5-7-9-11-0-2-4-5
Mixolydian (sol) mode = 7-9-11-0-2-4-5-7
Aeolian (la) mode = 9-11-0-2-4-5-7-9
Locrian (ti) mode = 11-0-2-4-5-7-9-11

By subtracting the number assigned to the starting note or "tonic", and adding 12 (one octave) to any number that goes negative, we can derive the notes of each scale as a sequence of semitones from the tonic.

Ionian = 0-2-4-5-7-9-11-0
Dorian = 0-2-3-5-7-9-10-0
Phrygian = 0-1-3-5-7-8-10-0
Lydian = 0-2-4-6-7-9-11-0
Mixolydian = 0-2-4-5-7-9-10-0
Aeolian = 0-2-3-5-7-8-10-0
Locrian= 0-1-3-5-6-8-10-0

You may prefer to refer to notes by letters instead of numbers, though.  So let's assign the number "0" to the ever-popular tonic of C.  Recall that 0=C, 2=D, 4=E, 5=F, 7=G, 9=A, and 11=B.  The five "black key" notes (1, 3, 6, 8, 10) will need to use sharps or flats as appropriate.

C Ionian scale = C-D-E-F-G-A-B-C
C Dorian scale = C-D-E♭-F-G-A-B♭-C
C Phygian scale = C-D♭-E♭-F-G-A♭-B♭-C
C Lydian scale = C-D-E-F♯-G-A-B-C
C Mixolydian scale = C-D-E-F-G-A-B♭-C
C Aeolian scale = C-D-E♭-F-G-A♭-B♭-C
C Locrian scale = C-D♭-E♭-F-G♭-A♭-B♭-C

The mapping of numbers to letters is context-sensitive: Note 6 is "F♯" in the Lydian scale, but "G♭" in the Locrian scale.  This is needed in order to satisfy the requirement that each note in a scale use a unique letter.

For instance: dorian [re-mode] has 2b (flats), and lydian [fa-mode] has 1# (sharp).

This is indeed the case for scales starting on C.  As you can see from my lists of notes above: C Dorian has two flats (E♭ and B♭) and C Lydian has one sharp (F♯).
But as you suspected, this only applies if you're starting from C.  Let's try starting from E instead.  Then 0=E, 1=F, 3=G, 5=A, 7=B, 8=C, and 10=D, so:

E Ionian scale = E-F♯-G♯-A-B-C♯-D♯-E
E Dorian scale = E-F♯-G-A-B-C♯-D-E
E Phyrgian scale = E-F-G-A-B-C-D-E
E Lydian scale = E-F♯-G♯-A♯-B-C♯-D♯-E
E Mixolydian scale = E-F♯-G♯-A-B-C♯-D-E
E Aeolian scale = E-F♯-G-A-B-C-D-E
E Locrian scale = E-F-G-A-B♭-C-D-E

E Dorian now has two sharps, and E Lydian has five sharps.  If you compare the E scales to the corresponding C scales, you see that they all have exactly four more sharps or four fewer flats than the C-based counterpart.
Comment: Objection and downvote withdrawn and replaced with upvote.
Comment: @JoãoMendes: Fine, I've edited my answer to use the traditional arbitrary Greek words for the modes.

Confusion on modes


header() redirect doesn't work

Question: I can't get the Script working. I want a Javascript alert that confirms an action and then a redirect back to my Page. This isn't working:
echo "";
mail("email@example.com", "Subject", "Hallo, lorem impsum.");
mail("firstname.lastname@example.com", "Subject", "Hallo, lorem impsum.");
header('Location: ../../wishlist.php');`

Comment: That's not how PHP works. You need to learn about the server/client relationship.
Comment: runepiper, please "accept" an answer below.
Comment: Define "isn't working". What is or is not happening.
Comment: You are not clear about interaction of javascript to PHP here.  Are you sending email in response to an AJAX call?  If not, I am not sure why you would perform any messaging via javascript, as by the time javascript is written to the page and executed, your headers have already been sent to the browser.  Why not simply output the message on the page you are redirecting to?
Comment: *Um...* why 2x `mail(...)` ? Remove one. *Plus*, outputting before header; no go.
Comment: If you want to use JS *and* redirect, you can always use `` instead of `header()` - It's a quick fix.
Comment: JohnConde the redirect is not working. Everything else is working fine.
MikeBrant Sorry I didn't get your Idea.
@Fred-ii- Because I want to notify two person. I will try your HTML Redirect.
Comment: The HTML redirect will work. @runepiper PHP does not allow to output before `header()`
Comment: Please don't post your solution within the question.  Post your solution below as an answer and then "accept" it as soon as you're allowed.
Comment: Since the OP used [`my comment`](http://stackoverflow.com/questions/22514027/header-redirect-doesnt-work#comment34256364_22514027) as his/her solution, I should be posting it as an answer then (?) in order to close the question. @Sparky
Comment: @Fred-ii-, it doesn't matter as long as the question is not edited to post the answer within.  Only the "answers" section is for posting answers.  So post yours too.  Maybe the OP will accept it.  Maybe you'll get up-votes.  Whatever... you have enough rep to know how this site works.
Comment: Agreed. The upvotes are ok but that's not what I'm about. @Sparky I just want to close it properly.
Answer: You cant output anything before the header call. From the docs:

Remember that header() must be called before any actual output is
  sent, either by normal HTML tags, blank lines in a file, or from PHP.

echo "";

Answer: It has already been stated that you cannot output before header(), so I won't repeat it.
(To close the question)
OP posted in an edit which was later modified by Sparky:
"UPDATE: Ok for my Problem this did work for me:
echo "<meta http-equiv=\"refresh\" content=\"0;URL=../../wishlist.php\">";

I've used it instead of the header and after the alert."
as the solution provided by my comment:
"If you want to use JS and redirect, you can always use <META http-equiv="refresh" content="5;URL=http://www.example.com"> instead of header() - It's a quick fix."
<META http-equiv="refresh" content="5;URL=http://www.example.com">

In your case as you posted in your question earlier, use:
echo "<meta http-equiv=\"refresh\" content=\"0;URL=../../wishlist.php\">";

header() redirect doesn't work


SQL Server How to Utilize Pivot in this difficult situation

Question: I've been reading a lot of posts on here trying to figure out how to use this pivot function and have not had any luck. Either some of the explanations included something unnecessary to me or made it too difficult for to understand because I only recently started teaching myself SQL.
I need to figure out how to Group my dates into one if possible and turn P1, P2, P3... into columns. Making P1-10 into their each individual column is what is most important.
This is what the original SQL Server looks like.. + many other columns that are irrelevant for what I'm trying to do.
<code>+-------------+------------+---------------------+
| StationName | Start_Time | Time                |
+-------------+------------+---------------------+
| P1          | 15         | 2018-06-21 13:37:34 |
+-------------+------------+---------------------+
| P3          | 69         | 2018-06-21 12:33:55 |
+-------------+------------+---------------------+
| P4          | 52         | 2018-06-21 13:42:34 |
+-------------+------------+---------------------+
| P1          | 18         | 2018-06-21 10:37:34 |
+-------------+------------+---------------------+
| P9          | 78         | 2018-06-21 6:37:34  |
+-------------+------------+---------------------+

This is what I currently have

SELECT Cast(Start_Time AS DATE) AS Date,
StationName,
sum(time) AS "Daily Downtime"
FROM A6K_Events
Where StationName Like 'P%'
GROUP BY Cast(Start_Time AS DATE), StationName
Order By Date DESC

+------------+-------------+----------------+
| Date       | StationName | Daily Downtime |
+------------+-------------+----------------+
| 2018-06-21 | P1          | 33             |
+------------+-------------+----------------+
| 2018-06-21 | P3          | 62             |
+------------+-------------+----------------+
| 2018-06-21 | P8          | 1              |
+------------+-------------+----------------+
| 2018-06-21 | P9          | 78             |
+------------+-------------+----------------+
| 2018-06-20 | P1          | 69             |
+------------+-------------+----------------+
| 2018-06-19 | P1          | 52             |
+------------+-------------+----------------+

This is what I would like to have:
+------------+----+----+----+----+----+----+----+----+----+-----+
| Date       | P1 | P2 | P3 | P4 | P5 | P6 | P7 | P8 | P9 | P10 |
+------------+----+----+----+----+----+----+----+----+----+-----+
| 2018-06-21 | 33 |    | 62 |    |    |    |    | 1  | 78 |     |
+------------+----+----+----+----+----+----+----+----+----+-----+
| 2018-06-20 | 69 |    |    |    |    |    |    |    |    |     |
+------------+----+----+----+----+----+----+----+----+----+-----+
| 2018-06-19 | 52 |    |    |    |    |    |    |    |    |     |
+------------+----+----+----+----+----+----+----+----+----+-----+
</code>
The Numbers filled in would be the Daily Downtime value for that process that day. The end result will be recorded live and contain many dates and various down times.
Thanks for the Help in advance
Edited to add text tables and removed images
Comment: Please do not use images for input/output samples. Use text tables instead; there are great websites that can create them for you. Just one [example](https://senseful.github.io/text-table/)
Comment: Thank you! Sorry about that this is my first post. I will work on doing that.
Answer: You can accomplish the output with the following pivot statement.
<code>SELECT * FROM(
SELECT CAST([Start_Date] AS DATE) as [DATE],SUM(TIME) AS [Daily DownTime],STATIONNAME FROM A6K_Events Where StationName Like 'P%' GROUP BY [start_date],STATIONNAME
) AS S
PIVOT(sum([Daily DownTime]) FOR STATIONNAME IN([P1],[P2],[P3],[P4],[P5],[P6],[P7],[P8],[P9],[P10])) AS PT
</code>
http://rextester.com/BAXY34111
Comment: I have now added text tables and my current code if that would be more useful in answering the question
Comment: I'm still unable to figure this out i keep getting no column name 'Date'
Comment: Ah i see original column is start_date not date updated.
Comment: Any suggestions? I feel like im not even close to getting it right and have been working on this for a long time
Comment: Yes the issue was I did not start with the column named "Start_date" I went off the table, in your query the field is "Start_date" aliased to [Date]. So I corrected and redid the rextester.
Comment: The original column is Start_Time and I tried to join them together so they are grouped together by each day. There is also no downtime column, it is called time. I replace downtime with time though and it still says no column named 'time' when there is. So I'm still very confused. If you need any more information for helping me solve this let me know. Thank you.
Comment: I added what the original SQL server looks like towards the top of my OP
Comment: I'm now extremely close to solving this my only issue is that it is not grouping the rows into individual days instead its is showing times as well but the rest looks excellent!
Comment: If you want to remove the timestamp just use Cast([Start_Date] as Date) I added to my code snip above.
Comment: It works like a charm. I can't thank you enough for the help haha. Thank you so much.


Multiple Inheritance: same variable name

Question: class A
{
   protected:
    string word;
};

class B
{
   protected:
    string word;
};

class Derived: public A, public B
{

};

How would the accessibility of the variable word be affected in Derived? How would I resolve it?
Comment: Note that apart from the good answers below, it is always a good policy to avoid this kind of name clashes as much as possible.
Answer: It will be ambiguous, and you'll get a compilation error saying that.
You'll need to use the right scope to use it:
 class Derived: public A, public B
{
    Derived()
    {
        A::word = "A!";
        B::word = "B!!";
    }
};

Answer: You can use the using keyword to tell the compiler which version to use:
class Derived : public A, public B
{
protected:
    using A::word;
};

This tells the compiler that the Derived class has a protected member word, which will be an alias to A::word. Then whenever you use the unqualified identifier word in the Derived class, it will mean A::word. If you want to use B::word you have to fully qualify the scope.
Comment: `using A::word` in a full sentence would be: "Compiler, when I talk about `word` in the following clause, I really mean `A::word`"
Comment: Don't you have to say what has to be "used" for A::word? or is `using A::word` alone really enough?
Comment: @Zaibis That's enough really, it makes `Derived::word` an alias of `A::word`, basically.
Comment: I'm beliving you, I just asked as I'm not that used to c++ as I'm with C. ;)
Answer: Your class Derived will have two variables, B::word and A::word Outside of Derived you can access them like this (if you change their access to public):
Derived c;
c.A::word = "hi";
c.B::word = "happy";

Attempting to access c.word will lead to an error, since there is no field with the name word, but only A::word and B::word.
Inside Derived they behave like regular fields, again, with the names A::var and B::var also mentioned in other answers.
Answer: When accessing word in the class of Derived, you had to declare
class Derived: public A, public B
{
    Derived()
    {
       A::word = X;
       //or
       B::word = x;
    }
};


How to redirect user in profile dependency of type?

Question: I have some types of users. How to redirect user to profile dependency of account type?
After succesfull authorization I need to check Auth::user()->type and redirect to specified controller url.
I tried to use middleware for that:
class RedirectIfAuthenticated
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->check()) {

            if(Auth::user()->type == "1"){
                return redirect('/center');
            }

           if(Auth::user()->type == "2"){
               return redirect('/doctor');
           }
        }

        return $next($request);
    }
}

But where to call this middleware once?
Comment: Is there a reason you are writing it as middleware?
Answer: You can define custom middleware for a specific route by doing this:
Route::get('admin/profile', function () {
    //
})->middleware('custom');

However, in this case since you just need to redirect the user after they login, I would recommend putting the logic at the end of your login method:
public function login(Request $request)
{
    // handle authentication and return $user object if authenticated

    if ($user->type == "1") {
        return redirect('/center');
    } else if ($user->type == "2") {
        return redirect('/doctor');
    }

    // set default redirect if necessary
}

Comment: But it will work every time when I request this routing. So it will be loop redirect
Comment: @Blablacar that's why I would suggest adding the code to the controller method that authenticates your users. then it will only be run when a user logs in.


How to get non primary key value when entities are in mapping?

Question: AssignCoScholastic.java
@Entity
    @Table(name="assignCoScholastic")
    public class AssignCoScholastic
    {
        @Id
        @GeneratedValue(strategy=GenerationType.AUTO)
        private int assginCoScholasticId;
        @ManyToOne
        @JoinColumn(name="assignClassId")
        private AssignClass assignClass;
        @ManyToOne
        @JoinColumn(name="coscholasticId")
        private CoScholastic coscholastic;
        @ManyToOne
        @JoinColumn(name="subCoScholasticId")
        private SubCoScholasticActivity subCoScholasticActivity;
        private String year;
        @ManyToOne
        @JoinColumn(name="school_id")
        private SchoolModel schoolModel;

CoScholastic.java
@Entity
@Table(name="coscholastic")
public class CoScholastic {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int coScholasticId;
    @Column(name="Coscholastic_Name")
    private String coscholasticName;
    // Getters and Setters

Implementation:
@Override
    public List<Object[]> listOfAssignCoScholastics(int assiginedClass, int schoolId, String year) {
        Session session=sessionFactory.openSession();
        session.beginTransaction();
        List<Object[]> listOfAssignCoScholastics=new ArrayList<Object[]>();
        try
        {
        Criteria criteria=session.createCriteria(AssignCoScholastic.class);
        criteria.setProjection(Projections.property("coscholastic.coScholasticId"));
        criteria.setProjection(Projections.property("coscholastic.coscholasticName"));
        criteria.add(Restrictions.eq("assignClass.assignID", assiginedClass));
        criteria.add(Restrictions.eq("schoolModel.school_id", schoolId));
        criteria.add(Restrictions.like("year", year));
        listOfAssignCoScholastics=criteria.list();
        session.getTransaction().commit();
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            session.close();
            sessionFactory.close();
        }
        return listOfAssignCoScholastics;
    }

I am trying to execute above code and getting below exception.
What is the org.hibernate.QueryException: could not resolve property: and how to resolve it??
Exception:
org.hibernate.QueryException: could not resolve property: coscholastic.coscholasticName of: com.slv.model.AssignCoScholastic
at org.hibernate.persister.entity.AbstractPropertyMapping.propertyException(AbstractPropertyMapping.java:81)
at org.hibernate.persister.entity.AbstractPropertyMapping.toType(AbstractPropertyMapping.java:75)
at org.hibernate.persister.entity.AbstractEntityPersister.toType(AbstractEntityPersister.java:1465)
at org.hibernate.loader.criteria.CriteriaQueryTranslator.getType(CriteriaQueryTranslator.java:547)
at org.hibernate.criterion.PropertyProjection.getTypes(PropertyProjection.java:60)
at org.hibernate.loader.criteria.CriteriaQueryTranslator.getProjectedTypes(CriteriaQueryTranslator.java:362)
at org.hibernate.loader.criteria.CriteriaJoinWalker.<init>(CriteriaJoinWalker.java:100)
at org.hibernate.loader.criteria.CriteriaJoinWalker.<init>(CriteriaJoinWalker.java:82)
at org.hibernate.loader.criteria.CriteriaLoader.<init>(CriteriaLoader.java:92)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1697)
at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:347)
at com.slv.daoimpl.RegistrationDaoImpl.listOfAssignCoScholastics(RegistrationDaoImpl.java:1907)
at com.slv.controller.SchoolController.loadAssignCoscholastic(SchoolController.java:920)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

Answer: You need to tell hibernate which class property you need. it's like a join you write in your sql quires.
Try this way,
Criteria criteria=session.createCriteria(AssignCoScholastic.class,"assignCoScholastic");
criteria.createAlias("assignCoScholastic.coscholastic", "coscholastic");
criteria.createAlias("assignCoScholastic.assignClass", "assignClass");
criteria.createAlias("assignCoScholastic.schoolModel", "schoolModel");
criteria.setProjection(Projections.property("coscholastic.coScholasticId"));
criteria.setProjection(Projections.property("coscholastic.coscholasticName"));
criteria.add(Restrictions.eq("assignClass.assignID", assiginedClass));
criteria.add(Restrictions.eq("schoolModel.school_id", schoolId));//school_id is the property in class schoolModel
criteria.add(Restrictions.like("assignCoScholastic.year", year));

Hear classAliasHavingYear is the alias created for class having year attribute.
your rest of the code...
Comment: I used above code but im getting only Name but not id, its returning Name column only
Comment: year attribute is from which class..?
Comment: year attribut is from AssignCoScholastic.java
Answer:     Criteria criteria=session.createCriteria(AssignCoScholastic.class,"assignCoScholastic");
    criteria.createAlias("assignCoScholastic.coscholastic", "coscholasticss")
    .setProjection(Projections.distinct(Projections.projectionList()
    .add(Projections.property("coscholasticss.coScholasticId"))
    .add(Projections.property("coscholasticss.coscholasticName"))));
    criteria.add(Restrictions.eq("assignClass.assignID", assiginedClass));
    criteria.add(Restrictions.eq("schoolModel.school_id", schoolId));
    criteria.add(Restrictions.like("year", year));


Spring boot session management - why are there two instances of sessionRegistry?

Question: I am trying to implement a 'force logout' functionality in my Spring Boot app (for example, after an admin disables a user account).
I followed the steps as specified in various tutorials to get access to the session registry, in order to expire the session of a user (baeldung step 6 and verbose version on myyurt; also related SO).
However, after registering the SessionRegistryImpl as a @Bean, when using the debugger, I see there are 2 different instances in the dependency injection mechanism:

one sessionRegistry instance is used by Spring Security at login and logout and holds the principals and sessions as expected. The screenshot below was taken after a login - I had a breakpoint in the registerNewSession() method. Notice the id and the maps with already logged in users.

the other sessionRegistry instance is only given to my own SessionManager class which requires SessionRegistry as a dependency and calls getAllPrincipals(). Notice the id is different and the maps are empty (I called getAllPrincipals() after I logged in multiple times and took the first screenshot)

Class where I register the sessionRegistry bean (I removed the unnecessary code and left only my custom filters, in case it might have something to do with Springs auto-configurations):
<code>@EnableWebSecurity
class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public static HttpSessionEventPublisher httpSessionEventPublisher() {
        return new HttpSessionEventPublisher();
    }

    @Bean
    public static SessionRegistry sessionRegistry() {
        return new SessionRegistryImpl();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
            .addFilterBefore(myFirstFilter, UsernamePasswordAuthenticationFilter.class)
            .addFilterAfter(mySecondFilter, FilterSecurityInterceptor.class)
            .formLogin() // skipping details
            .and()
            .x509() // skipping details
            .and()
            .logout()
                .invalidateHttpSession(true)
                .permitAll()
            .and()
            .authorizeRequests() // skipping details
            .and()
            .sessionManagement()
                .invalidSessionUrl("/login")
                .enableSessionUrlRewriting(false)
                .maximumSessions(-1)
                    .maxSessionsPreventsLogin(false)
                    .sessionRegistry(sessionRegistry())
                    .expiredUrl("/login?expire");
    }
}
</code>
Class where I consumer the sessionRegistry dependency:
<code>@Component
class DefaultSessionManager implements SessionManager {
    private final SessionRegistry sessionRegistry;

    @Autowired public DefaultSessionManager(SessionRegistry sessionRegistry) {
        this.sessionRegistry = sessionRegistry;
    }

    public void expireUserSessions(String username) {
        for (Object principal : sessionRegistry.getAllPrincipals()) {
            // do stuff, but won't enter because the list is empty
        }
    }
}
</code>
If it helps, I looked up the beans setup with the Actuator /beans endpoint, and this is what it returns
<code>        {
            "bean": "defaultSessionManager",
            "aliases":
            [
            ],
            "scope": "singleton",
            "type": "com.foo.bar.DefaultSessionManager",
            "resource": // file path
            "dependencies":
            [
                "sessionRegistry"
            ]
        },

        {
            "bean": "httpSessionEventPublisher",
            "aliases":
            [
            ],
            "scope": "singleton",
            "type": "org.springframework.security.web.session.HttpSessionEventPublisher",
            "resource": "class path resource [com/foo/bar/SecurityConfig.class]",
            "dependencies":
            [
            ]
        },
        {
            "bean": "sessionRegistry",
            "aliases":
            [
            ],
            "scope": "singleton",
            "type": "org.springframework.security.core.session.SessionRegistryImpl",
            "resource": "class path resource [com/foo/bar/SecurityConfig.class]",
            "dependencies":
            [
            ]
        },
</code>
How can there be two different instances in the DI system if all are declared as Singleton?
Do you have any tips on what might be wrong?
I'm using spring-boot-starter-parent 1.5.2.RELEASE, which uses Spring Security 4.2.2.RELEASE.
Comment: I don't know if it's related, but the methods which are annotated with `@Bean`, don't need to be `static`. Since Spring works with proxies etc. in configuration classes, this could be a probem, but i'm not sure. Maybe try with removing the static keywords.
Comment: I met problems like this in Spring. Can you show objects, which refer to SessionRegistries? In my case there are was to context in application.
Comment: Actually i think the static keywords are the problem, because in your configuration where you call `.sessionRegistry(sessionRegistry())` it then directly calls the static method instead of going through the Spring proxy which would get the bean from the application context. That means, for your security configuration you create a new instance instead of getting the bean from the application context.
Comment: thanks, @dunni, that was it. I removed the static field and it works now... I haven't thought of that. If you want, please post this as an answer and I'll accept it. Cheers!
Answer: The problem are the static keywords on your <code>@Bean</code> annotated methods. In your configuration where you call
<code>.sessionRegistry(sessionRegistry())
</code>
it directly calls the static method instead of going through the Spring proxy which would get the bean from the application context. That means, for your security configuration you create a new instance instead of getting the bean from the application context. With non static methods, direct method calls within the same calls are intercepted by Spring, which then checks if the bean already exists in the application context, and if yes the bean will be returned.
Comment: A general rule of thumb (nothing official, just from my side): Static and Spring usually don't play nice together.
Comment: Thanks, the [docs](https://stackoverflow.com/a/14943106/2261315) aren't very helpful on this one. But I will keep in mind for the future. A lot of magic happening there.


advanced json-schema multiple rules per property

Question: I'm wondering if you can have multiple rules for a property.  All the examples seem to suggest you can't.
So I'd like to have something like:
"properties": {
  "track": {
   "type": "string",
   "pattern": "(exclusive)"
  },
  "track": {
   "type": "string",
   "pattern": "(featuring)"
  }
}

I know the obvious thing to do in this example would be to have pattern be to have "(exclusive)|(featuring)", but i guess i'd want to know which rule failed. Equally I might want more complex patterns later down the line which might not be solved by a |.
Answer: You can combine schemas with the allOf, anyOf, and oneOf keywords. Each of these keywords takes an array of schemas and does what it says it does. allOf is valid if all of the schemas are valid. anyOf is valid if any of the schemas are valid. oneOf is valid if exactly one of the schemas are valid.
Here's one approach your problem.
{
  "type": "object",
  "properties": {
    "track": {
      "anyOf": [
        {
          "type": "string",
          "pattern": "(exclusive)"
        },
        {
          "type": "string",
          "pattern": "(featuring)"
        }
      ]
    }
  }
}

Comment: Oha, nice one and might be handier than my list of dictionary solution depending on the context.


Krull dimension of a quotient by a system of parameters

Question: Let $(A,\frak m)$ be a local Noetherian ring and let $x_1,\dots,x_d$ be a system of parameters, i.e. ${\frak m}=(x_1,\dots,x_d)$. Then
$$\dim A/(x_1,\dots,x_i)=d-i$$ for each $i=1,\dots,d$.
I know just a few basic facts about dimension theory. I think I can prove the inequality $\le$ via Krull's Hauptidealsatz in this way: the maximal ideal of $A/(x_1,\dots,x_i)$ is $$\mathfrak m_i:= (\overline{x_{i+1}},\dots,\overline{x_d}).$$ So it must be $\mathrm{ht}(\mathfrak m_i)\le d-i$.
But how to prove the other inequality? I think I should do it by induction, but I cannot understand how to begin. So, if what I said so far is right (is it?), my question is: how can I prove that
$$\dim A/(x_1)\ge d-1?$$
Thank you very much,
Miles
Answer: Your proof for the 1st part is not true:
$x_1,\dots,x_d$ being system of parameters does not mean ${\frak m}=(x_1,\dots,x_d),$ So $(\overline{x_{i+1}},\dots,\overline{x_d})$ isn't necessarily the maximal ideal of $A/(x_1,\dots,x_i).$
For complete proof of this, see  "PROPOSITION 15.22" of the book "Steps in Commutative Algebra" By "R. Y. Sharp" (pages $297,298$). Search the book by google, if you dont have access to it.
Comment: I will read it carefully, thank you.
Comment: I have seen now for the first time what you mean. I am sorry for my blindness.
Comment: you are welcome


POP3 clients delete messages from the Google apps server

Question: I set up Google Apps for my domain to let them handle my email. The control panel of the account has a setting that indicates what happens to an email once it is retrieved via POP3.
When messages are accessed with POP is set to Keep copy in inbox.
Once my mail client retrieves the message, I can see still see it if I log on via the web-interface (that's good). However, if I am using another POP3 client to connect to the same account - the mailbox is empty. In other words, as soon as a client gets a message, it becomes unavailable for other mail clients.
Regular GMail accounts don't behave that way - I can receive the same email on all of my email clients, and it is kept on the server too.
Is there a setting I can rely on to make Google Apps behave like GMail?
Comment: How about asking Google Support? And why not using IMAP as it is designed for what you want?
Comment: Google support for a free account? Hmm... how?

I did check their FAQs and verified the scenarios described in all the comments received, so far I have no actual answer to this. Everything people mention has been double-checked.

I switched one of my clients to IMAP, that is a workaround that works.  But I'm still puzzled by the POP3 behaviour.
Answer: Yes there are settings you should check in the Email options at Google Apps.
There is a very good explanation at Google Support.
Comment: This is not the case, the option is already set to _Keep copy in inbox_, yet this keeps happening.
Answer: Your other POP3 Client is not checked to leave messages on the server. Once it downloads the messages, it is removing them. This is not a setting on GMail but rather your actual client.
Comment: There is a setting in Gmail. See my link!
Comment: Correct. Which means that they have it set up properly since the first POP3 Mail Client is not removing the emails. However the second POP3 Mail client is removing the emails. For example, Outlook's setting looks like http://www.msoutlook.info/pictures/removefromserver.png
Comment: I am aware of the fact that my email client may be the culprit, but I assure you it is set to _leave messages on the server_. This applies to both clients I am using.


Object escapes the window in pygame . How to prevent it from doing so?

Question: So, I am python beginner and wanted to create a space invader game. But I'm facing an issue.
The player object escapes the pygame window if I press the left arrow key or the right arrow key for a longer duration of time.
Here's my code -
import pygame
pygame.init()

window = pygame.display.set_mode((1200,800))
pygame.display.set_caption('RESCUE THE SPACESHIP')

close = False

spaceship_velocity = 0
spaceship_X = 550
spaceship_Y = 670

spacehip_img = pygame.image.load('spaceship.png')

while not close:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            quit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                spaceship_velocity -= 1
            if event.key == pygame.K_RIGHT:
                spaceship_velocity += 1

    #Doesn't seems to work
    if spaceship_X < -25:
        spaceship_X == -25
    if spaceship_X > 1125:
        spaceship_X == 1125

    spaceship_X = spaceship_X + spaceship_velocity
    print(spaceship_X)

    window.fill((255,255,255))
    window.blit(spacehip_img , (spaceship_X , spaceship_Y))
    pygame.display.update()

Before asking this question I've tried this but it doesn't seems to restrict the spaceship within the window
if spaceship_X < -25:
    spaceship_X == -25
if spaceship_X > 1125:
    spaceship_X == 1125

Any ideas how to fix it up?
Comment: `spaceship_X == -25` -> `spaceship_X =-25` and `spaceship_X == 1125` -> `spaceship_X = 1125`
Answer: Try moving the position check after spaceship_X = spaceship_X + spaceship_velocity, and perhaps change it to:
screen_rect = screen.get_rect()
if spaceship_X < screen_rect.left:
    spaceship_X = screen_rect.left
if spaceship_X > screen_rect.right - spaceship_width:
    spaceship_X = screen_rect.right - spaceship_width

Make sure to use the single equals operator = (for assignment), not the double equals operator == (check for equality). And you will need to add a spaceship_width variable or constant, representing the width of the spaceship in pixels.

An alternative solution would be to switch to using a rect for the spaceship's dimensions, and then do:
spaceship.rect = spaceship.rect.clamp(screen.get_rect())

Answer: I CHANGED
==

TO
=

AND IT WORKED PERFECTLY FOR ME
BEFORE
if spaceship_X < -25:
    spaceship_X == -25
if spaceship_X > 1125:
    spaceship_X == 1125

AFTER
if spaceship_X < -25:
    spaceship_X = -25
if spaceship_X > 1125:
    spaceship_X = 1125


Ngnix static site with one PHP alias/rewrite

Question: I have a static site Angular site and I want to have the path /deploy run a php the php script /var/www/app/deploy/deploy.php. I have tried a rewrite rule and having no luck.
What is the proper way to do this?
php.conf
index index.php index.html index.htm;

location ~ \.php$ {
    try_files $uri =404;
    fastcgi_intercept_errors on;
    fastcgi_index  index.php;
    include        fastcgi_params;
    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    fastcgi_pass   php-fpm;
}

vhost.conf
server {
    listen       80;
    server_name  app.com;
    root         /var/www/app/;
    include      /etc/nginx/default.d/php.conf;

    location / {
        root /var/www/app/frontend/dist;
        try_files $uri $uri/ /index.html =404;
        rewrite ^/deploy /var/www/app/deploy/deploy.php;
    }
}

Answer: Your rewrite statement needs a URI as the target and not the pathname. You should use:
rewrite ^/deploy /deploy/deploy.php last;

See this document for details.
Rather than use a rewrite statement in the location / block, you might consider the slightly cleaner option of moving it into an exact match location block:
location = /deploy {
    rewrite ^ /deploy/deploy.php last;
}

See this document for details.
Comment: That was it! And thanks for the suggestion - much cleaner!


CodeIgniter 404 page routes on SuSe

Question: I'm trying to upload my web to a server, and this is Suse 13. I've got an Apache2.4 installed and PHP 5.6. In Windows the same web is working great, but not on Suse. If I write on the direction bar http://myip/myweb/index.php/ControllerName/MethodName it works, but the routing is not working.
I've got my controller file with a capital letter Controller.php, inside, the class name is Controller and the method is "method", in lower case. In routes.php I've got:
$route['default_controller'] = 'controller';
$route['bar/foo'] = 'controller/method';

My config.php file:
$config['base_url'] = 'http://myip/myweb/';
$config['index_page'] = ''; //I can see the index page correctly
$config['uri_protocol'] = 'REQUEST_URI';

And finally, my .htaccess file:
RewriteEngine On
ServerSignature Off

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php?/$1 [L]

RewriteCond %{REQUEST_URI} ^application.*
RewriteRule ^(.*)$ /index.php?/$1 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?
 </IfModule>

<IfModule !mod_rewrite.c>
ErrorDocument 404 /index.php
</IfModule>

<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE model/vnd.collada+xml
# remove browser bugs
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
Header append Vary User-Agent
</IfModule>

I need help, I don't know what to do...
Thank you!
EDIT:
Enabled modules in apache:
actions alias auth_basic authn_file authz_host authz_groupfile authz_user autoindex cgi dir env expires include log_config mime negotiation setenvif ssl socache_shmcb userdir php5 reqtimeout authn_core authz_core version man rewrite

Answer: People, if you are wondering what the f*** is wrong, you have to know that in the Apache configuration file you have to add AllowOverride All!!!
http://enarion.net/web/htaccess/mod_rewrite-on-suse/

CodeIgniter 404 page routes on SuSe


V has a linearly independent subset S = {s1, ... , sk} & basis β = {b1, ... ,bn}. Why is {s1, ... , sk, b1, ... , bn} a spanning set of V?

Question: I know that for the linearly independent subset S, for λ1s1 + λ2s2 + .. + λksk = 0, the coefficients λ1 = λ2 = .. = λk = 0. I also know that for the basis β, the vectors b1, .. , bn are linearly independent and also span(β) = V. However, I do not know how to link both ideas that I know to conclude that the set {s1, .. ,sk, b1, .. ,bn} is a spanning set for V. Thanks!
Comment: Since $\beta$ spans $V$, any $v \in V$ can be written as $v = a_1b_1 + \cdots + a_nb_n + 0s_1 + \cdots + 0s_k$.
Answer: Since $\beta$ is a basis, $\operatorname{span}(\beta)=V$. So, since $S\cup\beta\supset\beta$, $\operatorname{span}(S\cup\beta)=V$.
Answer: A spanning set remains a spanning set when further vectors are added.


iOS 8 Code working on iPhone 5s but not iPhone 5

Question: After testing my spritekit game on the iPhone 5s simulator all the time I finally tried to run it on the iPhone 5 simulator. Unfortunately I get an error as soon as I do the first touch that I don't understand. My touchesBegan function calls my addCoin function (see below)
The error is somewhere in this code-block. If I comment out this part of the code everything else works fine:
func addCoin()
{
    var coin:SKSpriteNode = SKSpriteNode(texture: coinFrames[0])
    coin.size.width = 50
    coin.size.height = 50
    coin.physicsBody = SKPhysicsBody(circleOfRadius: coin.size.height / 2)
    coin.physicsBody?.dynamic = false
    coin.physicsBody?.allowsRotation = false
    coin.physicsBody?.categoryBitMask = coinCategory
    coin.physicsBody?.contactTestBitMask = playerCategory

    var positionX:CGFloat = CGFloat(Int(arc4random()) % Int(500)) + CGFloat(70.0)
    var positionY:CGFloat = CGFloat(Int(arc4random()) % Int(1007)) + CGFloat(63.0)

    coin.position = CGPointMake(positionX, positionY)
    coin.runAction(SKAction.repeatActionForever(SKAction.animateWithTextures(coinFrames, timePerFrame: 0.1, resize:false, restore:true)))

    self.addChild(coin)
}

Here is the error that occurs. If I comment out this line, the next one gives an error...

Like I said, iPhone 5s works perfectly...
What could be wrong with my code?
xCode 6 beta 6 & iOS 8 beta 7
Thanks in advance
Answer: The debugger is misleading you. The real problem is arc4random, which will return an UInt32 on both iPhone 5 and 5s. But as iPhone 5 is a 32-bit device, the Int(arc4random()) will cause an overflow if the random number is big enough.
Instead of using Int(arc4random()), you can try to replace it by using arc4random_uniform. Maybe the code below will do the trick for you.
var positionX: CGFloat = CGFloat(arc4random_uniform(500)) + CGFloat(70.0)
var positionY: CGFloat = CGFloat(arc4random_uniform(1007)) + CGFloat(63.0)


Como exibir um alert e limpar campos com asp classico?

Question: Como faço para exibir um alert e limpar os campos textbox em asp classico ?
Estou começando a mexer com asp classico agora, estou perdido, só sei asp.net.
Consigo usar algo de asp.net ?
Answer: Não tem como exibir um alert ou limpar controles com asp, utilize javascript para isso. O máximo que você pode fazer é inserir o código javascript na página com asp, mais ou menos assim:
<% response.write("") %>

Para limpar um textbox:
<% response.write("") %>

Se quiser limpar todos os textboxes da página, pode criar uma função javascript assim:

E chamá-la com asp assim:
<% Response.Write("") %>


Ball headed foul but stopped before it gets there - is it still fair?

Question: Scenario: a ground ball is hit towards third base and bounces left towards foul territory.
Suppose the third baseman grabs the ball while he is standing in fair territory before the ball gets to 3rd base and before the ball touches the ground in foul territory.
Is it a fair ball?
Answer: This is a fair ball, the ball never touches foul territory, so therefore it can't be a foul ball.
MLB Rules State:

A  FOUL  BALL  is  a  batted  ball  that  settles  on  foul  territory
  between home and first base, or between home and third base, or that
  bounds past first or third base on or over foul territory, or that first falls on foul territory beyond first or third base, or that, while on or over foul territory, touches the person of an umpire or player, or any object foreign to the natural ground.
A foul fly shall be judged according to the relative position of the
  ball and the foul line, including the foul pole, and not as to whether the
  infielder is on foul or fair territory at the time he touches the ball.

(Foul Ball) Comment:
    A batted ball not touched by a fielder, which hits the pitcher's rubber and rebounds into foul territory, between home and first, or between home and third base is a foul ball. If a fly ball lands in the infield between home and first base, or home and third base, and then bounces to foul territory without touching a player or umpire and before passing first or third base, it is a foul ball; or if the ball settles on foul territory or is touched by a player on foul territory, it is a foul ball. If a fly ball lands on or beyond first or third base and then bounces to foul territory, it is a fair hit.  (Fair Ball (Comment))
Answer: Adding to @New-To-IT's great answer, you need to note that whether a ball is foul or not entirely depends on the position of a ball. For example,

If a ball is completely out of the foul line, it is a foul ball whether it is caught or not. Before it crosses the line and is caught by an infielder, it is not a foul ball.
If a ball crosses it and comes back inside the foul line into fair territory, it is not a foul ball.

Therefore, it doesn't matter where a player stands when catching a ball. The only thing that matters is where the ball is.
Comment: #2 is a good point; this is why fielders shadowing a slow roller that is headed foul will pick the ball up as soon as it rolls foul.
Answer: Wrong, a ball becomes a foul ball immediately upon hitting a fence, backstop, net, umpire, or player while over foul territory before 1st or 3rd base. It matters where the ball is when it is touched until it passes 1st or 3rd base.


Probability Integral Transforms (Not getting U(0,1))

Question: I am trying to transform my GARCH standardized residuals to PITs in order to use them in a copula. The following code has been so far applied:
gjr_garch = arch_model(log_r['DAX'].dropna(), mean='AR', lags=8, vol='garch', p=1, o=1, q=1, dist='t')
dax_test = gjr_garch.fit()
dax_test.summary()
dax_dof = dax_test.tvalues['nu']
dax_sigma = dax_test.conditional_volatility
dax_innovations = dax_test.resid / dax_test.conditional_volatility
dax_innovations_std = (dax_innovations - np.mean(dax_innovations)) / np.std(dax_innovations)

sns.distplot(dax_innovations_std.dropna(), hist=True,fit=stats.norm)

Next, I just take the CDF of the standardized innovations with their respective d.o.f. estimated by the GARCH model.
dax_uni = t.cdf(dax_innovations_std, dax_dof)

I convert them to pd.Series just so I can dropna()
dax_uni = pd.Series(data=dax_uni)
sns.distplot(dax_uni.dropna(), bins=20, fit=stats.uniform, kde=False)

In fact, I've done this for not only GJR-GARCH but also for AR-TARCH AR-EGARCH models with AR means ranging from 0 to 10. None of the Probability Integral Transforms pass the Kolmogorov-Smirnov test for Unif(0,1).
Any ideas why can't I get uniformly distributed probability transforms?
Answer: This is because your model is not perfect. Models are always mispecified and, consequently, the (estimated) residuals do not perfectly resemble a normal or t distribution. Thus, transforming the residuals using a t or normal distribution would not lead to a uniform sample, as it happens when you transform $F^{-1}\circ G$ (not the identity function) instead of $F^{-1}\circ F$ (the identity function).
Comment: I was thinking the same however, even thought the model is not perfect, it still estimates the degrees of freedom pretty accurately doesn't it? Doesn't this mean that even though the model is imperfect, the empirical distribution is pretty much fit by the t-distribution with the estimated d.o.f. and, as such, should result in Unif(0,1) PITs?
Comment: @SergejShteriev The fact that you can estimate the parameters accurately does not mean that the model is good. This happens because the estimator is consistent, but it only converges to the model that better resembles the true distribution of the data. If you simulate from an asymmetric model but you fit an symmetric model, you will get accurate estimates with large samples, but you will never be able to resemble the asymmetry of the data as your model is symmetric. The same happens with other characteristics such as multimodality, heavy tails, or more complex ones such as heteroscedasticity.
Comment: What would you recommend for me to do to get more accurate PITs? I am guessing I'd have to model the heavy tails somehow?
Comment: @SergejShteriev The problem seem to be a bit in the mid range of the sample, probably some repeated observations. Thus, using an exponential power distribution instead of $t$ may help. However, this model may not be implemented in your software. However, the problem might go beyond the choice of the distribution of the residual errors as it may be the presence of heteroscedasticity or mispecification of the autoregressive part, or the linearity, and etcetera. Parametric model selection is an art. I wish you luck and have fun trying to find a good model for your data!
Comment: Thank you very much for the useful comments! I'll give a shot with a GDE (it is actually available in arch_models()) and see if I get somewhat more precise results. In regards to the heteroscedasticity however, isn't the covariance HAC in the arch_models as stated on the bottom of the summary table?