JBoss 7.1 Deployment Error using HSQL 2.2.9 as Datasource

Question: Since a few Hours I am trying to find some bug I produced on my Java EE-Program. It uses an HSQLDB Datasource. When the Server (JBoss 7.1.1 final) starts, the Database can be found and all needed Tables are created correctly. But at the end ob the deployment I got following error:
21:36:43,502 ERROR [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 2) {"JBAS014653: Composite operation failed and was rolled back. Steps that failed:" => {"Operation step-2" => {"JBAS014771: Services with missing/unavailable dependencies" => ["jboss.persistenceunit.\"BusinessLogic.jar#BusinessLogic\"jboss.naming.context.java.DefaultDSMissing[jboss.persistenceunit.\"BusinessLogic.jar#BusinessLogic\"jboss.naming.context.java.DefaultDS]"]}}}

DefaultDS is my Datasource. Except from my standalone.xml:
<datasource jta="true" jndi-name="java:jboss/DefaultDS" pool-name="DefaultDS"      enabled="true" use-java-context="true" use-ccm="true">
    <connection-url>jdbc:hsqldb:${jboss.server.data.dir}${/}localDB</connection-url>
    <driver>hsqldb</driver>
    <security>
        <user-name>sa</user-name>
        <password></password>
    </security>
    <pool>
        <prefill>false</prefill>
        <use-strict-min>false</use-strict-min>
        <flush-strategy>FailingConnectionOnly</flush-strategy>
    </pool>
    <security>
        <user-name>sa</user-name>
    </security>
</datasource>

I connect to this Database using JPA and my persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="BusinessLogic">

    <jta-data-source>java:/DefaultDS</jta-data-source>
    <properties>
        <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>

        <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
        <property name="hibernate.format_sql" value="false" />
        <property name="hibernate.show_sql" value="false" />
    </properties>

</persistence-unit>
</persistence>

As I said, at the Start of the Server JPA is creating all Tables correctly, so I assume the JDBC Driver is okay and the Database is working.
Answer: Try this
In your persistence.xml try changing
java:/DefaultDS
to
java:jboss/DefaultDS
Answer: You are using two different JNDI names for your datasource in your standalone.xml and in your persistence.xml files. Try giving both the exact same name, e.g. java:/jdbc/DefaultDS and try again.


confusion in public and private key

Question: in Encryption and decryption same key is use to to convert plan text to cipher and cipher to plan text. so why in public key cryptograpy method sender Encrypt using receiver public key and receiver decrypt using his own private key ?
Answer: What you initially refer to is symmetric encryption (shared key), which allows 2 entities to communicate securely based on a single shared key that is only known to the two entities.  This key can be exchanged several ways, but can't be publicized for obvious reasons.
Asymmetric encryption (public/private key) allows 2 entities to communicate securely as follows:
If one party wants to accept secure (encrypted) information, they need a key that isn't visible to the world (private), but they also have to be able to provide a key to anyone who wants to send encrypted information (public).
So I can give my public key out to the whole world and know the data is secure since only I have the private key, therefore I'm the only one who can decrypt it.
See Asymmetric Encryption in this Microsoft article: http://support.microsoft.com/kb/246071
Comment: You may want to point out that the type of encryption the asker is implying is referred to as symmetric encryption, as a point of comparison.
Answer: Because it wouldn't be secure the other way around, or feasible either. Only the recipient has his private key, so nobody else can use it.

confusion in public and private key


Create a model from the result of sql statement with entity Framework

Question: In the current environment I am working on, I was confronted with a not very trustful database. Where I have, among all the shannannigans, tables without keys, fields in wrong sizes, very bad separation and relation in tables, and et cettera.
Well, they asked me to make a query in that database, and I can't create a view for such. Nor I have writing access what-so-ever to such DB.
Is it possible to use Entity to parse the result of a query and populate a list of that model?
I know how to do it with nhibernate, and manually, but, is it possible to do it in EF?
Thanks
Answer: You simply need to put the SELECT you would have put in your view right into the ExecuteQuery as described in this previous post and do your data validation like you want.
Comment: That is exactly what I've needed! Thanks


Updating customer details

Question: I have a website which stores customer details, name, address, contact etc. A customer can update their own details via a form. What are the best practices for implementing this?
Do I just use an UPDATE statement over the existing data, or do I have old and new details?
It got me thinking, say if using a webiste such as amazon when a customer updates their details. What if the details are not correct? Do amazon have a record of the old details as a backup?
Such as a customer could live at 999 Fake Street. Also what if a problem occurs and the customer cannot be contacted because of the new updated details given? For example the customer receives a service and avoid paying.
Should I just update customers information, or should I move the old data into another table then update?
Hope I haven't asked too much of an obvious question, thanks.
Comment: Are you asking how to keep a history of user profile changes, or how to make sure they enter the correct information?  It sounds like your question is more along the lines of ensuring the user enters correct information, which is more of a interface design question than a data question.
Comment: Am asking abit of both really, is it ok to just update customers details or should I make a backup before allowing them to do so.
Answer: Add a field to your customer table InfoDate or something similar.  Then you can access the data via a view that only shows  you the record for each customer where the InfoDate is  the max value for that customer.
You keep all your data without a complicated process of migrating to another table for archiving, and you can access historical data easily by directly querying the table instead of the view.
Comment: Thanks, is  there an actual need to store the data before being updated? Data protection Act states "not kept longer than necessary", it wouldn't be necessary unless i'm actually using it?
Comment: There probably is not a need to store EVERY entry for every customer.  You could make the case that you need at least 1 historical record per customer in case of an error.  If a customer mis-keys some information, having an option to go back is good.  I'm not a UK legal expert, though, just making a suggestion for your data model.
Answer: Elliott,  the database design you are seeking must be based on business rules.  The DBA at facebook, twitter, amazon or Mom's Pizza did not dedtermine how many old addresses to keep.  Ask the BA for the rule on address.  If the answer is "keep only a current address"  then implement the UPDATE statement you mentioned in the question.  If the BA give you a blank stare then insert new rows for every update and display the latest chrono record and NEVER delete anything.
When the DB A recieves a complete set of business rules only then should the design begin.

Updating customer details


ThreeJS How to set the position of the OrbitControls

Question: I'm storing the position of the OrbitControls using .getAzimuthalAngle() and .getPolarAngle() and at a later date I want to be able to set getAzimuthalAngle and getPolarAngle but with slightly different values.
The reason I'm using getAzimuthalAngle and getPolarAngle is because I need to work out the percentage of the rotation, e.g. if's 180° that would be 50%. As in the background I'm setting the position of a 2D map to mirror the same location. I've got it working one way, but as I can't set the position of the OrbitControls, I'm a stuck..
Answer: I've managed to hack a solution in by duplicating the OrbitControl Update function and setting theta and phi values directly (rather than in increments as the update function)
<code>this.setPhiTheta = function(t, p) {
    var position = this.object.position;

    offset.copy( position ).sub( this.target );

    // rotate offset to "y-axis-is-up" space
    offset.applyQuaternion( quat );

    // angle from z-axis around y-axis

    theta = Math.atan2( offset.x, offset.z );

    // angle from y-axis

    phi = Math.atan2( Math.sqrt( offset.x * offset.x + offset.z * offset.z ), offset.y );

    if ( this.autoRotate && state === STATE.NONE ) {

        this.rotateLeft( getAutoRotationAngle() );

    }

    /*theta = 3.105;
    phi = 1.48;*/
    theta = t;
    phi = p
    //console.log("theta " + theta)
    // restrict theta to be between desired limits
    theta = Math.max( this.minAzimuthAngle, Math.min( this.maxAzimuthAngle, theta ) );

    // restrict phi to be between desired limits
    phi = Math.max( this.minPolarAngle, Math.min( this.maxPolarAngle, phi ) );

    // restrict phi to be betwee EPS and PI-EPS
    phi = Math.max( EPS, Math.min( Math.PI - EPS, phi ) );

    var radius = offset.length() * scale;

    // restrict radius to be between desired limits
    radius = Math.max( this.minDistance, Math.min( this.maxDistance, radius ) );

    // move target to panned location
    this.target.add( pan );

    offset.x = radius * Math.sin( phi ) * Math.sin( theta );
    offset.y = radius * Math.cos( phi );
    offset.z = radius * Math.sin( phi ) * Math.cos( theta );

    // rotate offset back to "camera-up-vector-is-up" space
    offset.applyQuaternion( quatInverse );

    position.copy( this.target ).add( offset );

    this.object.lookAt( this.target );

    //thetaDelta /= 1.2;
    //phiDelta /= 1.2;
    scale = 1;
    pan.set( 0, 0, 0 );

    // update condition is:
    // min(camera displacement, camera rotation in radians)^2 > EPS
    // using small-angle approximation cos(x/2) = 1 - x^2 / 8

    if ( lastPosition.distanceToSquared( this.object.position ) > EPS
        || 8 * (1 - lastQuaternion.dot(this.object.quaternion)) > EPS ) {

        this.dispatchEvent( changeEvent );

        lastPosition.copy( this.object.position );
        lastQuaternion.copy (this.object.quaternion );

    }
}
</code>
Comment: However this doesn't animate, which is fine for the moment but will need to find a way in a couple of days


Plugging linear operators into polynomials and their factors.

Question: Plugging operators into polynomials has always been pretty tricky for me.
Let $V$ be a vector space over $\mathbb F$ and let $D(x)=(x-a_1)^{m_1}(x-a_2)^{m_2} \dots (x-a_k)^{m_k}$. If it is given that $D(T)=0$, what can we say about $ker(T-a_1id), \dots, ker(T-a_kid)$?
And what about $ker(T-a_1id)^{m_1}, \dots, ker(T-a_kid)^{m_k}$?
Since it's hard for me to jump from plugging scalars into polynomials to plugging operators, I immediately think it means $T=a_1id$ or $T=a_2id$ or $\dots$ or $T=a_kid$ but that is not true I think.
Can we determine then anything else about the kernels of $T-a_iid$? About their dimensions? or anything else?
Comment: Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer.
Answer: We have
$$V=ker(T-a_1id)^{m_1} \oplus \dots \oplus ker(T-a_kid)^{m_k}.$$
Comment: Thank you! Sorry for the ambiguous question. Could you elaborate why that's true?


Passenger permission denied accessing .htaccess

Question: I just finished migrating my Redmine install and after testing it with webrick all went fine and the site worked really well with http://localhost:3000
Next, i installed and configured mod_passenger, added a separate virtual host and basically just copied the configuration from the previous server. Since the app's absolute path did not change i assumed it would work right off the bat but that wasn't true and apparently passenger is not accessing the right directory. Here is what comes up in the error log for that virtual host:
Permission denied: /srv/redmine/.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable

Here are the configuration files:
Virtual Host
<VirtualHost *:80>
        ServerName redmine
        DocumentRoot /srv/redmine/public
        ErrorLog /var/log/apache2/redmine_error.log
        RailsEnv production
        PassengerRoot /srv/redmine/public

        <Directory /srv/redmine/public>
                Options Indexes FollowSymLinks
                AllowOverride all
                Order allow,deny
                allow from all

                RailsBaseURI /
                PassengerResolveSymlinksInDocumentRoot on
        </Directory>
</VirtualHost>

Passenger Config File
<IfModule mod_passenger.c>
  PassengerRoot /usr
  PassengerRuby /usr/bin/ruby

  PassengerDefaultUser www-data
  # Below are some lines to tweak mod-passenger.
  # This keeps some Ruby processes running,
  # but the average response time is a lot lower
  # on low-traffic sites.
  RailsSpawnMethod smart
  PassengerPoolIdleTime 3000
  RailsAppSpawnerIdleTime 0
  PassengerMaxRequests 1000
</IfModule>

Any ideas why (according to the error) Passenger is trying to find the .htaccess in the /srv/redmine/ whereas it should have been looking in /srv/redmine/public/ ?
I should also note that the public/ directory under was chmodded 755 recursively
Thanks in advance!
Answer: It's not only checking /srv/redmine/.htaccess, it's also checking /srv/.htaccess and /.htaccess.  Apache will stat those locations for every request if AllowOverride is enabled - it's just only logging that one since it exists but isn't accessible to the user Apache's running as.  See here.
The fact that it's attempting to open an .htaccess file that it can't open should have no bearing on whether the application function, though.  What problems is the application having other than that warning?
Comment: yes indeed! I chmodded that file correctly and now i get the real passenger error: i was missing a gem required by passenger, once installed all went like a brease! thanks a lot!


How to avoid CKeditor to change the HTML code?

Question: I want to add code like

 to make the whole block as a link, but after saving it getting changed to

. I am using CKeditor module, have done changes in config/text-format/filter HTML to disable the Limit allowed HTML tag. In short I want that editor do not do anything with HTML code.
Answer: I know that this is not the answer to your problem (which is annoying) but personally I would avoid putting a
 inside a  tag. It is normally not allowed to put a "block" type of tag inside an "inline" type of tag.
So you could do the following:
Your stuff

and then add a CSS rule:
a.block,
a.block > span {
  display: block;
}

This way you are HTML valid and CKEditor should not try to correct it.
Comment: Having the link inside a paragraph is not a problem. I made this quick codepen example to show you: http://codepen.io/patacra/pen/WrNjwz
Comment: Actually i ended up to this stage, in search of finding how to make a enrite drupal block clickable. I want to make some block on the front page and entire block has to be clickable, i did not find that solution, I i thought to make 4 seprate  in body and cover that  using  so entire block gets clickable. But the issue is that, CKeditor is not allowing and in plain drupal body(without CKeditor) also it is not giving the output which we get while making the plain html doc and open in browser.
Comment: I tried your code also but it is converting to ` Your stuff  `
Comment: Well, it seems that you are trying to create some HTML code which is perhaps not the kind of text that an ordinary user would insert into a node body or a static block.

I would create a module and implement the block hook if you need to do something very custom. Wysiwyg editors are mainly for simple text input.

If not, isn't it possible to create a new input format (kind of full HTML) and affect no Wysiwyg editor to this format?
Comment: Yes, might be if i give the real world example, I want to make a block like any Adsense, when you hover the cursor over that block it shows the pointer and when you click it it direct to the url. Will make the new text format and will try.
Comment: This is very good, might be I can change my requirement of achieving it with block and instead can go just with the paragraph with link which looks as block. as you shown..Thanks
Answer: go to:
/admin/config/content/ckeditor/edit/Advanced (for Filter HTML)
/admin/config/content/ckeditor/edit/Full (for Full HTML)
Then under Advanced Content Filter, select disabled.

If the above does not do it, depending on which one you are using (filter or full html) You need to go to
/admin/config/content/formats/filtered_html
OR
/admin/config/content/formats/full_html
Uncheck the correct faulty and chopped off html box.
Comment: Hi, I did both of things, but issue is the same. Even  also tried the to disable the Limit allowed HTML tags, but no help, I am using filtered one. Thank though for answer.
Comment: **WOW**, looks like it's not possible, I've tried everything that I could think of. CKEditor keeps auto converting it to `` ridiculous.
Comment: Ya, it looks like..


What is the difference between type I error and type II error in default or non-default case?

Question: What is the difference between type I error and type II error in forecasting default of a company? For example, I can set null hypothesis to be "The company will default next year", or I can set it to be "The company will not default next year", so my type I and type II error will be vice versa in this case. Can I set the null hypothesis as I want, or how should I decide what is the null hypothesis?
Answer: In general, you want to reject the null hypothesis so you set it as the case you want to avoid. When reading $p$-values and probabilities, it's easier to interpret the levels you want to define as showing stronger evidence against the null hypothesis, but it is up to what you consider the outcome you want to avoid or show.
In your example, I'd write:
$H_0$: "The company will default next year"
$H_1$: "The company will not default next year"
Type I error : Forecasting $H_1$ when $H_0$ is true, also called a false positive
Type II error : Forecasting $H_0$ (or more precisely failing to reject $H_0$) when $H_1$ is true, also called a false negative
You may see here for another example.


Is it possible to separate limits of multivariable functions in such a manner?

Question: If we have a function like this:
$\lim_{(x,y) \to (1,0)}\frac{y \ln y}{x}$
Can we separate it like so, separating the variables?
$\lim_{(x,y) \to (1,0)}\frac{y \ln y}{x} = \lim_{x \to 1}\frac{1}{x} \cdot \lim_{y \to 0} \frac{ln y}{\frac{1}{y}}$
Is this valid?  I can apply L'Hopitals rule now, to get the answer L=0
Comment: Yes. But before the edit it wasn't right since $\lim_{y\to0}\ln y$ didn't exist.
Comment: You can separate it like this, but L'Hopials cannot be formally applied even though it will give the right result.
Comment: @NikolayGromov If we can't use L'Hopitals in this limit, is it acceptable to create another limit of the exact same function in terms of another variable and use L'Hopitals rule on that, concluding the limit is 0?
Answer: Notice the limits can be separated if & only if they individually exist
$$\lim_{(x, y)\to (1, 0)}\frac{y\ln y}{x}=\lim_{(x, y)\to (1, 0)}\frac{\ln y}{\frac{1}{y}}\cdot \lim_{(x, y)\to (1, 0)}\frac{1}{x}$$
$$=\lim_{(x, y)\to (1, 0)}\frac{\ln y}{\frac{1}{y}}\cdot (1)=\lim_{(x, y)\to (1, 0)}\frac{\ln y}{\frac{1}{y}}$$ Applying L'Hospital's rule for $\frac{\infty}{\infty}$ form  $$=\lim_{(x, y)\to (1, 0)}\frac{\frac{1}{y}}{\frac{-1}{y^2}}$$
$$=-\lim_{(x, y)\to (1, 0)}(y)=0$$


C# String.Format replaces escaped quotes into "

Question: I'm trying to format a String using the String.Format function, but my double quotes keep getting replaced by the HTML safe version of this (").
Needless to say this is not the result I would expect.
My current code looks like this
string String= String.Format("{0}: {{ name: \"{1}\"}}", node.Category, node.Name);
// Output ==> SomeCategory: { name: "SomeName" }

I've tried replacing the " by actual quotes in the output, but that also didn't work.Is there some voodoo I can use to fix this?
Thanks in advance!
Comment: Please show a little code around this because the problem is not caused by the `format` call.
Comment: @Willem As commented under your answer,  I am currently using this.
Comment: This String is put in a List which is passed using Razor's ViewBag. In the view, I iterate through the List and display the strings.
Comment: Try using the `@Html.Raw( ... )` helper to display the string.
Answer: This is not caused by String.Format(), more likely it is caused by whatever you use to view the data, or by something that happens before you view the data.
Judging from your format string it looks like you're trying to create a JSON string to return (possibly from a service). There is a big chance something will HTML encode your string on it's way to the client. The problem lays there, not in your string formatting, and thus trying to fix it there will not work.
Comment: That would explain a lot (as I couldn't find this particular problem in any other StackOverflow issue and the format function shouldn't replace special characters).

The problem lays in what you already suggested, the view. Razor's display will automatically encode the HTML. Using the Html.Raw() function disables this and doesn't replace the quotes.
Answer: Try to use HTML decode and encode
That way you can turn them in actual quotes.
HttpUtility.HtmlDecode
Source: http://msdn.microsoft.com/en-us/library/aa332854%28v=vs.71%29.aspx
Stackoverflow source: " instead sign of quote (")
Comment: If replacing the `"` does not work, this will not work either.


Sample selection bias and logistic regression

Question: I am struggling with possible sample selection bias at the moment, and I was wondering whether someone has a methodological tip or possibly knows of fancy statistical/econometric tools I could use to solve this issue.
The context is as follows: I am studying the effects of cultural risk attitudes on the engagement in some risky behaviour. To do so, I am developing a logistic regression model using various socioeconomic characteristics of immigrants in a country and their countries of origin. The focus on immigrants in the same country is needed to isolate purely cultural effects from institutional and economic factors (which is why we do not simply employ a panel-data analysis of different countries). However, (economic) immigrants are known to be less risk averse than their cultural counterparts in their motherland. Leading to a self-selection into our sample. This could bias the estimated cultural effect upwards when naively applying logistic regression.
The main problem I have is the following. Suppose we had data on both the immigrants as well as the people who decided to not emigrate, then we could employ a tobit like regression model to take this self-selection effect into account. Sadly we have no observations about the people who stay home so this is no option. We also have no data on reasons of migration, so we are unable to filter economic migrants out of our sample.
Any help or tips would be greatly appreciated!
Answer: Welcome, Pokemonfan!
Are you able to make your conclusions conditional on the self-selection bias implied by emigration and acknowledge that generalization beyond that context is speculative, but not wholly without merit? If so, then there is nothing to worry about.
If you require the ability to generalize beyond the immigrant subgroup of a country, then you certainly would need data from non-emigrants. If you can't get the most relevant data, you might try to correlated behaviors through some intermediate variables that couple "cultural risk attitudes" to observables like fraction of assets in stocks vs. riskless investments or mean-time in a job or entrepreneurial rates (new business account openings per 1000), but then you would need to have that data from the home country. Likewise, if you could correlate through immigrants from another country whose non-emigree data is available, then that could be a pathway from observables here to observables there. If the correlations are weak as often happens in the social science, and if you need a chain of such weak correlations, then you are probably better off by amending your analysis with the dependent clause given that they came to America.
How is a limiting conditional statement still worthwhile? Conditional statements are better received by reviewers than unconditional ones, and that speculative generalizations of conditional statements are perfectly employable as Bayesian priors . . . conditional on the assumption that no better priors exist, naturally.
Comment: Thanks for your answer! It is interesting that you suggest to use intermediate variables like entrepreneurial rates and information on investments as we had the idea to quantify cultural risk attitudes by such information in the first place, However, say that we use those variables in a logistic regression, then we would still overestimate their coefficients due to the self-selection. Ideally, I'd want to be able to generalise beyond the immigrant subgroup, but if there's no other way I could deal with this selection effect I will have to limit myself.


How do I train my musical ear. (Not sure how to phrase this question.)

Question: I'm singing in a church for fun (I've only had a few lessons). I can sing great when i'm singing along to someone else who is on key and sounds great such as listening to like Beyonce or Sam Smith on the radio, but if I turn the music off I can't tell if I'm on key or not.
Also if someone sings with me it throws me off because for some reason I can't sing by myself I have to match the person, it's almost subconscious. Like all four of us are singing. The key of the song is too low and I am awkwardly going between singing it low but (I can't sing low and loud) and singing the key high to match everyone.
I am slowly getting somewhat better about this but harmonizing is still difficult. I can't listen to someone sing and just harmonize right off of them like other people can, because like I said, I have to sing along to them. Also, they can't harmonize to me because if I am singing low, and they start singing a higher key I naturally move up in the same key as them. I can't stop it either. I can alleviate it by covering my ears but it isn't sustainable. Any help would be greatly appreciated.
Comment: By low and high, do you mean jumping up and down an octave?
By harmonizing, do you mean like what the Andrews Sisters did?
(Just making sure that we understand exactly what you're asking.)
Answer: For starters, apart from the ubiquitous 'get yourself a teacher', sing along with tracks that are within your range, and gradually, over a number of sessions, keep turning the sound down, until it's barely audible. Then some more, but only for short periods - maybe start with a couple of lines, then increase, so when the music comes back, you'll tell if you're still in pitch. It may take several weeks or months, but it's worth a go. It'll also check your timing - but for now, tap a foot, sway, or whatever you like to keep in time.
It sounds like your range needs a little work, too, so keep singing those low and high notes more and more. Being an octave out isn't a problem, and as long as you're aware of it, it's a good sign.
Can't tell from the phrasing of your question whether you had lessons previously, or you've just started, so only had a few, but your teacher will be able to help with this. Also, trying to play an instrument will help differentiate pitches.Say, on piano/guitar, you play C-E-G-A, and sing it back, with or without playing again, then increase the notes, and try again. Try to record all that you do, as a reference to improvement, as well as listening to what you're doing. Quality of reproduction isn't foremost, yet, so any old recorder will do. Chances are your phone will do a fair job.
Answer: One thing to clarify, the concept of harmonizing (to a melody), i.e. singing a different melody line, lower or higher than a given main melody, but still able to "fit well" with that given melody, is NOT the same as singing in a different key, whether higher or lower. It means both the main melody and and that different melody line you are singing (the harmony) are both in the same key, but are in intervals apart (usually diatonic), instead of unison or an octave apart.
If you'd like to work on being able to sing a harmony to any given melody, my suggestion is to really work on audiation, first be really familiar with the scale degrees of ALL major keys, eg. in the key of G how do you pitch the 5th of it (which is the D). Next is work on diatonic intervals. For all my students who want to start on harmonization, my advise is to start on diatonic thirds above the melody. For e.g. in C major, the diatonic 3rds above will be "E F G A B C D E". Try playing the C major scale and sing these notes above, train your ears (and your voice) to be comfortable and familiar with the sounds of these diatonic intervals. You can then skip the notes around and try on arpeggios or any short phrases, e.g. you've a phrase "C G F D E C", you sing "E B A F G E". That should help build your foundation to sing in harmony. Cheers!! :)
Answer: I think you should practice ear training and establishing a key in your mind. Practicing some scales and arpeggios will go a long way to helping you establish a sense of key. Practice them using solfege or letter names or numbers. Play a note and then practice going up and down and returning to the same note you played. Once you have scales try arpeggios. The Do Re Mi song from Sound of Music is a great example of solfege. Try singing each part while thinking the starting note in your head.
Answer: It appears to me that you are taking your pitch cue from whoever you are singing with. Try instead learning to read your choir parts from the written page. When  you have learned to read the parts, then you can practice them in solitude or with others and become well enough versed in the part that it becomes more natural to sing. In addition, if you can play the part on an instrument, hearing it can reinforce your confidence that you are on pitch and in key. Another approach might be to listen to harmonized vocals like acapella choirs and try to work out each part separately. I learned by tearing apart the Everly Brothers vocal parts and learning them separately.


Creating simple web page associating image with excel column

Question: I have an excel page with columns such as:
Col Col2 Col3
abc  1    3
def  4    5
hgi  9    5
and so on.
And I have various images in a folder with file names corresponding to 'Col' i.e. abc.jpg, def.jpg, etc.
I want to create a webpage with asks for a string from a user, searches it in Col1, then displays corresponding Col2, Col3, and the image corresponding to that Col1.
NOW, I'm not asking for what to do, but I just want to know HOW will I do this? What all tools/scripts/languages/software do I need to know to implement a system like this? I'll get to learning that straight away.
I have very little experience in web development hence a very noob-ish question.
Thanks a lot guys!
Answer: If you want to have the user enter the information on the Webpage itself, I would recommend JavaScript. JavaScript is a good enough language to do the stuff you want to do. For accessing Excel, you could always export the Excel file as a CSV (Comma Separated Values) or another format and read into your JavaScript. You can read a file in your JavaScript code using this link, for example.
Comment: The linked code is absolutely bogus. There are no `fopen`, `flength`, `fread` functions in any JavaScript implementation I know, even less in browsers.
Comment: Thanks for the answer.

Just another thing, is Javascript required to do this advanced-level? For someone who hasn't done Javascript before, how long would it take to learn till this level?
Hope the question isn't too specific. Just give your best approximation.


Removing class from last clicked event in React

Question: I have a Navbar with tabs, and I want to make a function called onClick that gets the event, and adds a class to that tab "active". But, when I click another tab, it should remove a class from the previous tab and add it to that one.
Sample of my code:
const [clickedTab, setClickedTab] = useState(true);

function Click() {

  if (clickedTab === true) {
    console.log(clickedTab);
    tab.classList.add("active");
  }
  else {
    console.log("Error!");
  }

}

Answer: In React use the model (via useState() in this case) to make changes to the view.
Set the activeId of the tab in the state, and if the tab's id is equal to activeId pass set it's active to true. The tab itself can add/remove the className.

const { useState } = React;

const Tab = ({ id, active, setActive }) => (
  <li
    className={`tab ${active ? 'active' : ''}`}
    onClick={() => setActive(id)}
    >
    {id}

);

const Example = ({ tabs }) =>  {
  const [activeId, setActive] = useState();

  return (

    {tabs.map(id => (
      <Tab
        key={id}
        id={id}
        setActive={setActive}
        active={id === activeId}
      />
    ))}

  );
}

const tabs = [1, 2, 3, 4];

ReactDOM.render(
  <Example tabs={tabs} />,
  root
);
.tabs {
  display: flex;
  list-style: none;
}

.tab {
  height: 1em;
  width: 2em;
  border: 1px solid red;
  text-align: center;
  cursor: pointer;
}

.active {
  background: red;
}

Comment: This is useful but I don't know how can I combine this with my code because beside adding className and removing it, it must also route pages.
I have 4 links and here is the example of one of them:
**
Home
              **
Comment: If you're using react router look at [NavLink](https://reactrouter.com/web/api/NavLink)
Answer: Here is a simple example so you can get the idea; we hold current active element id in a state then based on that we decide what class name it should have; no need to use classList's add or remove

function Header () {
  const [active, setActive] = React.useState();
  return (

setActive(1)}
       >a

setActive(2)}
       >b

setActive(3)}
       >c

  );
}

ReactDOM.render( , app );
.red{background:red}.blue{background:blue}li{color:#fff;width:30px}

Comment: Can I somehow shorten that and remove repetition but combine it with this example:
**
 setActive(1)}>Home
              ** ?


Context.User is Nothing ONLY when trying to debug

Question: I have a project that I have upgraded from .NET 1.1 to .NET 4.0.  The project uses Windows Authentication (internal Intranet webpage).  I setup Windows Authentication in IIS 7.5 (running Windows 7) following the steps laid out in this article.
http://www.iis.net/ConfigReference/system.webServer/security/authentication/windowsAuthentication
I can now build the project.  I can open the project by opening IE and typing in the URL on localhost.  However, if I try to debug the project it throws an NullReferenceException on this line in the Application_AuthenticateRequest in Global.asax.
<code>dt = oDBLookup.GetPIMSUserRoles(Context.User.Identity.Name)
</code>
If I set a breakpoint there I see that Context.User is Nothing.  If I set a breakpoint in the same place on the 1.1 project (different box, running IIS 6) it has my Windows Credentials.
Why would Context.User be Nothing ONLY when I am trying to run from the debugger in Visual Studio 2010 Professional, and not when I open the web project directly in IE?
Thanks in advance.
Comment: So I deleted the solution file (which had been upgraded), created a new one in VS 2010 and the problem disappeared.  I would put this as an answer but my reputation is below 100 so I can't answer my own question.
Comment: It might be that the VS is hosting the site when you run debug (F5), not IIS. Try attaching IE to the debugger and see if you get a value for Context.User.
Comment: Sorry, I knew that VS uses it's own Web server since 2005.  I can't see any settings in VS for Windows Authentication, though, and unlike some previous versions I don't see a use IIS option where the Use Default Web server is currently selected.
Comment: If you go to the project's properties, under the Web tab, there should be an option to Use Local IIS Web server.  Try setting that.  If you can't find it, try starting a browser, attaching it to the debugger and then hitting your page.
Answer: I deleted the solution file (which had been upgraded), created a new one in VS 2010 and the problem disappeared. I would put this as an answer but my reputation is below 100 so I can't answer my own question.


JSF 2.0 Spring Security 3 Weblogic 10.3.5 Jdeveloper

Question: I have trying examples of JSF 2.0, Spring Securty 3 with Jdeveloper and Weblogic server 10.3.5.
I get these exception
java.lang.NoClassDefFoundError: javax/faces/context/FacesContext
    at org.springframework.web.jsf.el.SpringBeanFacesELResolver.getWebApplicationContext(SpringBeanFacesELResolver.java:90)
    at org.springframework.web.jsf.el.SpringBeanFacesELResolver.getBeanFactory(SpringBeanFacesELResolver.java:79)
    at org.springframework.beans.factory.access.el.SpringBeanELResolver.getValue(SpringBeanELResolver.java:50)
    at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
    at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
    at org.jboss.el.parser.AstIdentifier.getValue(AstIdentifier.java:44)
    at org.jboss.el.parser.AstValue.getValue(AstValue.java:63)
    at org.jboss.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:186)
    at com.sun.faces.facelets.el.ELText$ELTextVariable.writeText(ELText.java:224)
    at com.sun.faces.facelets.el.ELText$ELTextComposite.writeText(ELText.java:148)
    at com.sun.faces.facelets.compiler.TextInstruction.write(TextInstruction.java:85)
    at com.sun.faces.facelets.compiler.UIInstructions.encodeBegin(UIInstructions.java:82)
    at com.sun.faces.facelets.compiler.UILeaf.encodeAll(UILeaf.java:183)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1655)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1655)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:399)
    at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:313)
    at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
    at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
    at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:300)
    at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:26)
    at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
    at oracle.security.jps.ee.http.JpsAbsFilter$1.run(JpsAbsFilter.java:111)
    at java.security.AccessController.doPrivileged(Native Method)
    at oracle.security.jps.util.JpsSubject.doAsPrivileged(JpsSubject.java:313)
    at oracle.security.jps.ee.util.JpsPlatformUtil.runJaasMode(JpsPlatformUtil.java:413)
    at oracle.security.jps.ee.http.JpsAbsFilter.runJaasMode(JpsAbsFilter.java:94)
    at oracle.security.jps.ee.http.JpsAbsFilter.doFilter(JpsAbsFilter.java:161)
    at oracle.security.jps.ee.http.JpsFilter.doFilter(JpsFilter.java:71)
    at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
    at oracle.dms.servlet.DMSServletFilter.doFilter(DMSServletFilter.java:136)
    at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
    at weblogic.servlet.internal.RequestEventsFilter.doFilter(RequestEventsFilter.java:27)
    at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
    at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3715)
    at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3681)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
    at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
    at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2277)
    at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2183)
    at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1454)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:209)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:178)
Please help me.
Answer: Finally, I got a solution. That is because, classloading problem with weblogic.
I created weblogic.xml in my project . After that, I wrote
<code> <container-descriptor>
    <prefer-web-inf-classes>true</prefer-web-inf-classes>
 </container-descriptor>.
</code>
Answer: Have you configure the JSF libraries with your project ?


Why integral is equal to zero

Question: I wonder why under assumption that w>>$\frac{1}{T}$ then $\int_{0}^{T} sin(wt)dt$ is approximately zero?
Since the integral should be like- $\frac{cos(wt)}{w}$ from $0$ to $T$ and after plugging the valued we will end up with :
$\frac{-cos(wT)+1}{w}$
Comment: The quantity $\frac{1-\cos(wT)}{w}$ has most likely been *neglected* because the characteristic time of the problem is $T$ and $\frac{1}{w}<>$ in the sense of limits. I also suggest to consider $T$ as fixed. So, the integral tends to zero as $w\to+\infty$ is what is meant by saying that the integral is almost zero when $w>>1/T$. This can be quantified if necessary (using the expression you have for the integral).
Comment: Physicists sometimes use the sloppy notion of an term to be "approximately zero" to express the fact that that term (possibly under certain conditions like parameters being very large or small) will become so small that it can be neglected compared to other relevant terms in - say - a sum. Maybe that is the case for your integral.
Answer: That's a notation commonly employed by physicists to say you need to take limits: the estimate is given by the $\varepsilon-\delta$ definition of the limit, in this case more like $M-\delta$:
\begin{equation}
\forall M >0\ \exists \delta=\delta(M)>0: wT>M\Rightarrow\frac{-cos(wT)+1}{w}<\delta
\end{equation}
that is, your approximation gets more and more precise as you get "closer" to $\infty$. In your example of $w=1$ and $T=1000$ you get something of order $1$ as the result of your integral. If you were in a laboratory trying to measure something relating to this formula and wanted something closer to zero, you would just need to set an higher $T$ or $w$ - that's what this formula is telling you.
Hope this helps. :-)
(Also, for computing the limit:
\begin{equation}
\frac{-cos(wT)+1}{w}=\frac{(-cos(wT)+1)}{wT}T
\end{equation}
even if I guess this wasn't really your problem)
Comment: Thanks. The only problem is what if T also is very large meaning $\frac{1-cos(wT}{wT}$ is very small due to $wT>>1$ but $T$ is also very big so still the result won't go to zero.

Why integral is equal to zero


Binding column fieldname to referenced object, DevExpress

Question: I have two classes:
public partial class EMPLOYER
{

    public int id { get; set; }
    public string name { get; set; }
    public string surname { get; set; }
    public int employer_func_id { get; set; }

    public virtual EMPLOYER_FUNC EMPLOYER_FUNC { get; set; }
}

and
public partial class EMPLOYER_FUNC
{
    public EMPLOYER_FUNC()
    {
        this.EMPLOYER = new HashSet<EMPLOYER>();
    }

    public int id { get; set; }
    public string func_name { get; set; }

    public virtual ICollection<EMPLOYER> EMPLOYER { get; set; }
}

for example it is my model. Now I write sql query. This query returns a list of EMPLOYER objects. In View I have gridcontrol where I have columns name, surname and func_name. Display name and surname are simple and it is not problem, but I can't display func_name. I try type EMPLOYER_FUNC.func_name to field name column in grid control but not work.. Do you know how can I do it? thanks a lot
Comment: http://www.devexpress.com/Support/Center/Question/Details/A579
Answer: Why not just create another property on the EMPLOYER class?
public string employer_func_name
{
    get { return EMPLOYER_FUNC.func_name; }
}

That's if I understood the question correctly.


Como enviar esse Header usando NUSoap PHP?

Question: Pessoal estou tentando autenticar num WS mas não estou conseguindo, eu consigo conectar e gerar um token, mas ao tentar fazer outras operacoes com token recebido não consigo preencher o header e validar a sessao, veja o trecho do herader:
<code>    <?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Header>
    <Autenticacao xmlns="servidoralvo.com.br/OperacoesPortador">
      <Token>string</Token>
    </Autenticacao>
  </soap:Header>
  <soap:Body>
    <CartoesPortador xmlns="servidoralvo.com.br/OperacoesPortador">
      <request>
        <DocumentoPortador>string</DocumentoPortador>
      </request>
    </CartoesPortador>
  </soap:Body>
</soap:Envelope>
</code>
Estou tentando o seguinte:
<code>$Header = '
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Header>
    <Autenticacao xmlns="servidoralvo.com.br/OperacoesPortador">
      <Token>' . $Token . '</Token>
    </Autenticacao>
  </soap:Header>
</soap:Envelope>';

$AHeader = $Client->setHeaders($Header);

$AParams = array();
$AParams["request"]["DocumentoPortador"] = "14238911996";

$Conexao = $Client->Call("CartoesPortador", array($AParams), '', '', true, true);

fPrintDebug($Conexao);
</code>
Ele dá erro de autenticação, mas não é o token, o erro esta na construção do header, pois esse mesmo token usando o Soap nativo do PHP funciona.
O detalhe é que no servidor que uso na web, não tem como habilitar o Soap nativo então tenho que usar o NuSoap PHP
Alguem teria uma dica do que pode ser?
Comment: Marcelo voce está querendo criar o wsdl direto do XML ? Por o certo usando NuSoap é usar o metodo configureWSDL que fica dentro do objeto $Soap_server... Se for isso me explica eu te mando um exemplo.
Comment: Veja só, eu fiz uns testes com o Soap nativo do PHP, mas ao colocar no servidor vi que lá não tem o Soap, o servidor usao um metodo de include, bem fui usar o metodo do servidor e deu uns paus porque está desatualizado, então pra não ter que ficar pedido pro provedor atualizar o servidor, estou tentando usar o nuSoap, eu consigo autenticar na boa, mas quando tendo usar as funções que requerem o Token ele não valida o cabeçalho... não estou sabendo como enviad a requisição completa, como coloquei no xml acima tenho que enviar o header e o body, mas pelo soap nao sei fazer.
Comment: Entendi cara no Nusoap não se cria o WSDL ou XML como está fazendo você cria um metodo e registra ele o XML é gerado pelo Nusoap nesse caso você precisa colocar o método que cria o token e registrar ele. Segue um CRUD que eu fiz com Nusoap, ainda preciso refatorar mas tenho certeza que vai te ajudar. https://github.com/satodu/Nusoap-sample. Depois que voce registrar basta entrar em http://localhost?wsdl
Comment: Vou postar uma resposta para ver se te ajuda
Answer: Primeiro voce cria um arquivo que vai conter suas instruçoes de SOAP como por exemplo server.php.
Dentro desse arquivo primeiro tem que ter isso
<code><?php
//Chama a lib
require_once "lib/nusoap.php";
//Starta o Objeto
$server = new soap_server();
//Diz que ele tem que criar um wsdl ou XML
$server->configureWSDL("registerWithToken", "registerWithToken");
</code>
Agora ainda nesse mesmo arquivo você vai registrar os métodos disponiveis no seu XML.
<code>$server->register("registerWithToken.generateToken",
    array("token" => "xsd:string"),
    array('return' => 'xsd:string'
    ),
    'urn:registerWithToken',
    'urn:registerWithToken',
    'rpc',
    'encoded',
    'Gera o token de login'
    );
</code>
Em a classe com o método.
<code>     class registerWithToken {
        public function generateToken() {
            ... Código que gera e retorna o Token ...
            }
     }
</code>
E colocar no final..
<code>$HTTP_RAW_POST_DATA = (isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : 'teste');
$server->service($HTTP_RAW_POST_DATA);
</code>
Nesse exemplo é apenas para um método segue um exemplo com mais métodos. E com mais informação.
Ele vai criar um registro de métodos assim -> http://papoinformal.com.br/prueba/2/new/server.php
E um XML assim ->
http://papoinformal.com.br/prueba/2/new/server.php?wsdl
O consumo pode ser feito de várias formas o exemplo que cria o arquivo acima é esse :
https://github.com/satodu/Nusoap-sample/blob/master/server.php
Comment: Hum... acho que fui infeliz no meu texto, me parece que entenderam que quero criar um servidor, mas na verdade só quero consumir um WS ja existente.
Comment: kkk.. Cara Soap Client é nativo tentou colocar assim
$client = new SoapClient('http://papoinformal.com.br/prueba/2/new/server.php?wsdl');

??
Comment: https://github.com/satodu/Nusoap-sample/blob/master/service.php Olha o consumo da outra via Nusoap
Comment: Pois é @Dom Soap é nativo, mas eu não sei o que acontece com alguns TIs... porque o cara não instala o Soap do PHP em um servidor num momento que todos usam? Não entendo... no servidor que estou usando simplesmente não tem o Soap Nativo... o cara deve ter os motivos dele. Tenho que usar NuSoap, :(
Comment: Olha esse segundo exemplo que coloquei o consumo via nusoap
Comment: Então @Dom, eu consigo consumir o WS o que não estou conseguindo é enviar o Header que é onde envio o Token, ai o servidor recusa.
Answer: Pessoal uma coisa simples que me consumiu muito tempo, mas do que eu vou consumir no WS rsrs, o header tem que ir assim:
<code>$Header = '<Autenticacao xmlns="' . PORTNAMES . '"><Token>' . $Token . '</Token></Autenticacao>';
</code>
Que coisa!
Comment: Ola @Marcelo, já que essa é a resposta para o seu problema, marque-a como correta/aceita ao clicar no "✅" que está ao lado dela, o que também marca a sua pergunta como resolvida.


Upper bound for the trace of product of two real symmetric matrices.

Question: For symmetric matrices $A,B$ $\in$ $\mathbb{R}_{2\times2}$, their eigenvalues are $\lambda_1$,$\lambda_2$ ($0\leq\lambda_1 \leq \lambda_2$) and $\mu_1$,$\mu_2$ ($0\leq\mu_1 \leq \mu_2$), respectively.
Prove
$tr(AB)$$\leq$$\lambda_1$$\mu_1$+$\lambda_2$$\mu_2$.
When I tried to prove it, it may be solved with complex calculation.
I think there is much more simple or more intuitive way. I think rearrangement inequality would be used.
Answer: Here's a way of doing things: we can write
$$
A = \lambda_1 x_1x_1^T + \lambda_2 x_2x_2^T\\
B = \mu_1 y_1y_1^T + \mu_2 y_2y_2^T
$$
where the $x_i$ and $y_i$ are unit vectors.  We then calculate
$$
\operatorname{Tr}(AB) =
\lambda_1 \mu_1 (x_1^Ty_1)^2 +
\lambda_1 \mu_2 (x_1^Ty_2)^2 +
\lambda_2 \mu_1 (x_2^Ty_1)^2 +
\lambda_2 \mu_2 (x_2^Ty_2)^2
$$
Now, define $t = (x_1^Ty_1)^2$.  We can rewrite the above as
$$
\operatorname{Tr}(AB) =
t \lambda_1 \mu_1  +
(1-t)\lambda_1 \mu_2  +
(1-t)\lambda_2 \mu_1 +
t\lambda_2 \mu_2 =\\
t [\lambda_1 \mu_1 + \lambda_2 \mu_2] +
(1-t)[\lambda_1\mu_2 + \lambda_2\mu_1]
$$
Where $0 \leq t \leq 1$.  It suffices to maximize this quantity.
Also, note that
$$
[\lambda_1 \mu_1 + \lambda_2 \mu_2] -
[\lambda_1\mu_2 + \lambda_2\mu_1] =
(\lambda_2 - \lambda_1)(\mu_2 - \mu_1) \geq 0
$$
Comment: $x_i$ and $y_i$ are eigenvector of A and B, right? Then, I am curious about any symmetric matrix is equal to summation of $\lambda_i$$x_i$$x_i^T$. I first encountered this property, today. Is this famous property?
Comment: Yes, $x_i$ and $y_i$ are eigenvectors.  This is one way of writing the spectral theorem.


Finding a function for a system of differential equations

Question: Given the system of linear differential equations:
$$ \dot{x}=-2x $$
$$\dot{y}=y $$
given that $0 < \mu<1$, show that $(x_{\mu}(t),y_{\mu}(t))^T$ is the solution of the given system with the initial values $x(0)=1$ and $y(0)=\mu$.
Prove that there exists a $\tau = \tau(\mu)$ such that $0<x_{\mu}(\tau)\leq 1$ and $y_{\mu}(\tau)=1$.
Find $\tau(\mu)$ and show that $x(\tau(\mu))={\mu}^2$.
APPROACH
This is an exam question that I can't seem to figure out what they exactly are asking. The question actually consisted of three parts, the first part being asking for a phase plane and the character of the origin which is easy to deduce that it's an unstable node. The second part is what you see above as my question.
I solved for the given systems and got $x(t)=c_1e^{-2t}$ and $y(t)=c_2e^t$. Using the given initial values I get $c_1=1$ and $c_2=\mu$.
However this is how far I get, I don't understand how I can prove the existence of the mentioned $\tau$ and also don't see any relevance between the first part of the question (not that it has to but I thought maybe I am missing something.)
Answer: You have found that $x_{\mu}(t) = e^{-2t}$ and $y_{\mu}(t) = \mu e^t$.
Let $\tau(\mu)= \frac 1 {\mu}$. Note that $\tau(\mu) > 0$ since $0 < \mu < 1$. Then
$y_{\mu}(\tau)=1$ tand $x_{\mu}(\tau)=\mu^2$ so $0 < x_{\mu}(\tau) < 1$.


Access userInfo dictionary in Swift

Question: I'm trying to access the userInfo dictionary in application:didReceiveRemoteNotification() so that I can choose a segue based on what kind of push was received/if any push was received. I've tried these two ways (some others too, I'm sure, I just can't remember at this point).
if let info = userInfo as? Dictionary<String,String> {
        var notificationType = info["notificationType"]
}

if let info: String = userInfo["notificationType"] as? String {
        //do stuff
}

I'm not getting any errors, I'm just not getting anything at all. If I print the userInfo dictionary, it only has one member, ["aps"], which contains the push message that gets displayed to the user, so even if I could just access this I could make a conditional using it.
I attempt to write to userData as per the Parse API:
let data = ["notificationType" : "coffee"]
push.setData(data)

So the one issue is that this doesn't seem to be setting anything, but the greater issue is that I can't get to any userInfo data.
How do you access this dictionary?
EDIT
some print statement results:
println(userInfo["aps"]) => {alert = "You've Been Invited To A Coffee Order";}

println(userInfo) => [aps: {alert = "You've Been Invited To A Coffee Order";}, type: coffee]

println(userInfo[0]) => nil

let info = userInfo as? Dictionary<String,String>
println(info) => nil

So it seems just the alert key is getting stuck in this 'aps' array? dictionary? I didn't create it, it's just automatically part of userInfo
Edit 2
Here's the code where I set the data and send the push. I send the data that appears in userInfo from here:
func notifyUserOfCoffeeOrder(){
    var uQuery:PFQuery = PFUser.query()
    uQuery.whereKey("username", equalTo: usernameLabel.text)

    var pushQuery:PFQuery = PFInstallation.query()
    pushQuery.whereKey("user", matchesQuery: uQuery)

    var push:PFPush = PFPush()
    push.setQuery(pushQuery)
    let data = ["type" : "coffee",
                "alert" : "You've Been Invited To A Coffee Order"]
    push.setData(data)
    push.sendPush(nil)
    println("push sent")

}

and here's the whole function from AppDelegate.swift, where I pull the received data out:
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
     NSNotificationCenter.defaultCenter().postNotificationName("getMessage", object: nil)

    if  let info = userInfo["type"] as? String {
        self.window = UIWindow(frame: UIScreen.mainScreen().bounds)

        var storyboard = UIStoryboard(name: "Main", bundle: nil)

        var initialViewController = storyboard.instantiateViewControllerWithIdentifier("coffeeVC") as UIViewController

        self.window?.rootViewController = initialViewController
        self.window?.makeKeyAndVisible()
    }

}

Comment: Could you please add the method signature where the first code part is fetched from? I'm kind of confused as to what you want to achieve, and which data you want to de-reference. Is the main goal of your example to get that the `notificationType == "coffee"`
Comment: I posted as soon as I printed those, so I realized immediately I can access the type using `userInfo["notificationType"]`, although I still would like to know why the `userInfo` data structure is built this way.
Comment: Could you copy more of the code, especially the declaration and the part with "You've been invited...", and give the print output after changing the data assignment into something like 'let data = [ "notificationType" : "coffee", "something" : "else"]'
Comment: i added the two relevant functions, is this what you were looking for?
Answer:
EDIT: I've know rebuilt this answer to conform with the comments given. Do note that I do not have access to Apples Push Notification services currently, and as such can't test this in the same environment as OP

It seems like the APN (or parse.com) adds a little bit here and there to the userInfo as you build it. Therefore my best suggestion is to use code like the following to print everything from the double dictionary which you receive. I've also provided code here to unwrap the optionals which occur as you look up something in the dictionaries.
So here is my modified example code:
func myApplicationFunc(didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
    // NSNotificationCenter.defaultCenter().postNotificationName("getMessage", object: nil)

    // Default printout of userInfo
    println("All of userInfo:\n\( userInfo)\n")

    // Print all of userInfo
    for (key, value) in userInfo {
        println("userInfo: \(key) —> value = \(value)")
    }

    if let info = userInfo["aps"] as? Dictionary<String, AnyObject> {
        // Default printout of info = userInfo["aps"]
        println("All of info: \n\(info)\n")

        for (key, value) in info {
            println("APS: \(key) —> \(value)")
        }

        if  let myType = info["type"] as? String {
            // Printout of (userInfo["aps"])["type"]
            println("\nFrom APS-dictionary with key \"type\":  \( myType)")

            // Do your stuff?
        }
    }
}

var userInfo : [ NSObject: AnyObject] =
[
    "aps" : [
        "alert" : "Coffee is not the answer",
        "type" : "coffee"
    ],
    "anotherType" : 123
]

myApplicationFunc(didReceiveRemoteNotification: userInfo)

This code produced the following output:
All of userInfo:
[anotherType: 123, aps: {
    alert = "Coffee is not the answer";
    type = coffee;
}]

userInfo: anotherType —> value = 123
userInfo: aps —> value = {
    alert = "Coffee is not the answer";
    type = coffee;
}

All of info:
[alert: Coffee is not the answer, type: coffee]

APS: alert —> Coffee is not the answer
APS: type —> coffee

From APS-dictionary with key "type":  coffee

You should be able to add my code within your application(...) method, and hopefully you'll see the light on both how to unwrap the double dictionary, and which information is actually transferred to you.
PS! In this answer to another post talks about how his setMessage disturbed his setData, this might also be interesting, if there are is some code affecting your result. Still my example code, should list everything received in userInfo
Comment: Thanks for unpacking! Literally :)
Typo: it's `APS` not `ASP`
Comment: Hey! thanks for the answer. Your assumptions were correct. And I think it's the last thing you said that I'm having trouble with, userInfo holding a dictionary. I'll update my answer with some print statement results to show you.
Comment: Thanks. You saved a night!

Access userInfo dictionary in Swift


A wizard has $5$ friends. How many days does the wizards' conference last? (Inclusion–Exclusion)

Question: A wizard has $5$ friends. During a long wizards' conference, they met any given friend at dinner $10$ times, any given pair of friends $5$ times, any given threesome of friends $3$ times, any given foursome $2$ times, and all $5$ friends together once. The wizard ate alone $6$ times.  Determine how many days the wizards' conference lasted.
I think I'm supposed to use the Inclusion-Exclusion Formula.
Comment: Is it supposed to be the shortest posible time and you combine events?  If you just say 50 nights he at with single people, 50 nights with pairs of people 30 nights with 3 etc that will do it
Comment: Is this just an analysis of overlapping sets?
Answer: This questions is really asking how many dinners occurred
Assume only 1 dinner per day
The problem gives us 6 pieces of information about how many friends the wizard ate dinner with. How many with 0 friends, how many with 1 friend, up to how many with all 5 friends.
The Inclusion-Exclusion Formula says
$$|A_1, A_2, A_3, ... A_{n-1}, A_n| = S_1 - S_2 + S_3 - S_4 + ... +(-1)^n S_{n-1} +(-1)^{n+1}S_n$$
Which means for a compound union of potentially overlapping sets $A_1, A_2, A_3, ... A_{n-1}, A_n$ that $S_1, S_2, S-3, S_4, ... , S_{n-1}, S_n$ are subsets and you add the subsets where an event is counted an odd number of times and subtract the subsets where an event was counted an even number of times. The giant formula turns into "add $S_1, S_3, S_5, ...$ and subtract $S_2, S_4, S_6, ...$"
The 6 pieces of information from the problem correspond to these subsets
$S_1={5 \choose 1}*10$ We have to choose 1 of the 5 friends ("it met any given friend at dinner 10 times")
$S_2={5 \choose 2}*5$ How many ways to choose 2 friends ("any given pair of friends 5 times")
$S_3={5 \choose 3}*3$ How many ways to choose 3 friends ("any given threesome of friends 3 times")
$S_4={5 \choose 4}*2$ How many ways to choose 4 friends ("any given foursome 2 times")
$S_5={5 \choose 5}*1$ How many ways to choose 5 friends ("all 5 friends together once")
$S_1 - S_2 + S_3 - S_4 + S_5$ Is how many nights the wizard ate with at least 1 friend
But we can't forget about the 6 times he ate alone
The total number of dinners is
$S_1 - S_2 + S_3 - S_4 + S_5 +6$
$={5 \choose 1}*10 - {5 \choose 2}*5 + {5 \choose 3}*3 - {5 \choose 4}*2 + {5 \choose 5}*1 + 6$
$=5*10 - 10*5 + 10*3 - 5*2 + 1*1 + 6  $
$=50 -50 +30 -10 +1 +6$
$=27$
Answer: For convenience I'll call the wizard of the title Rincewind ($R$) who has friends Antares ($A$), Betelgeuse ($B$), Castor ($C$), Deneb ($D$) and Enif ($E$). I'm assuming here that a dinner in a larger grouping also counts towards the smaller contained groupings.
The required dinners are, per grouping level, $(10,5,3,2,1)$, plus $6$ lonesome dinners for $R$.
So one dinner is $RABCDE$. This takes care of the "all-five-friends" dinner and one of each of the other categories, so we have $(9,4,2,1,0)$ left to allocate.
Then we have five dinners $RBCDE$, $RACDE$, $RABDE$, $RABCE$, $RABCD$ to satisfy the sets of four. This also caters for a number of other required sets, leaving $(5,1,0,0,0)$.
So then $\binom 52 = 10$ dinners for two friends, $RAB$, $RAC$, $RAD$, $RAE$, $RBC$, $RBD$, $RBE$, $RCD$, $RCE$, $RDE$. This is leaves just $(1,0,0,0,0)$ to fulfill.
So finally five intimate dinners with each one of $R$'s friends, $RA$, $RB$, $RC$, $RD$, $RE$.
Total: $6+1+5+10+5 = 27$ dinners.
Wizards being unstoppable gluttons, they may well have had three dinners a day, which would give a nine-day conference.

A wizard has $5$ friends. How many days does the wizards’ conference last? (Inclusion–Exclusion)


Java Plugin Table Color T

Question: I have a view with a table that is populated with an array list. The problem is that I can't solve an error regarding the table foreground.
Piece of code:
(1) Table table = new Table(parent, SWT.SINGLE);
(2) table.setForeground(Color.BLUE);

error on (2) : The method setForeground(Color) in the type control is not applicable for the arguments (Color)
I've imported java.awt.color
Can anybody tell me where I'm wrong ?
Answer: Table is an SWT control and does not use anything from java.awt
You should be importing org.eclipse.swt.graphics.Color - but this does not have any predefined colors.
To get predefined colors in SWT use:
Display display = table.getDisplay();

Color color = display.getSystemColor(SWT.COLOR_BLUE);

Answer: You are mixing AWT and SWT. The setForeground method of an SWT table needs a org.eclipse.swt.graphics.Color reference. Call it like this:
Display display = table.getDisplay(); // or whatever can get you the display reference
table.setForeground(display.getSystemColor(SWT.COLOR_BLUE));

Comment: How can I set only the selection foreground ? The ideea is that I want to color the selected row on mouse selection.
Comment: I do not understand your question. Was my answer (or greg's) not understandable? If so, what did you not understand?
Comment: The answer was understandable and it worked. I was wondering, how can I set the selection foreground or maybe the default blue on every selection for the entire row ?
Comment: Ok, maybe you should ask that as another question.

Java Plugin Table Color T


Proper Schema for Spark (when loading data into Dataframe)

Question: I have following structure in RedShift after running describe on a table (all fields are Nullable):
a integer
b numeric(18)
c date
d char(3)
e smallint
f char(1)
g varchar(20)
h numeric(11,2)

All data is extracted to S3. Now want to load data into Spark Dataframe but need to create a proper schema for this table as well.
How would Spark schema look like for these fields?
Is this structure correct? (wondering specially about Numeric (11,2), Date, Char(1) fields)
val schema = StructType(
    Array(
        StructField("a", IntegerType, true),
        StructField("b", IntegerType, true),
        StructField("c", StringType, true),
        StructField("d", StringType, true),
        StructField("e", IntegerType, true),
        StructField("f", StringType, true),
        StructField("g", StringType, true),
        StructField("h", IntegerType, true)
    )
)

Answer: You should use :

DoubleType or DecimalType for float value (like NUMERIC(11,2)). Decimal is better in my opinion, as it operates on BigDecimals
LongType for very big numbers - like NUMERIC(18). Otherwise it will not be stored properly
DateType for dates - it can be stored as a string, but if you can, you should choose more meaningful type
Comment: Thanks! Does the DateType need to follow specific format (or converted to specific format)? (e.g. MM/DD/YYYY HH:MM:SS)
Comment: @Joe You can easily convert string in any format to Date: http://stackoverflow.com/questions/40763796/convert-date-from-string-to-date-format-in-dataframes
Comment: At which moment we should use LongType instead of IntegerType? (e.g. when field in Database is defined as Numeric(5) or Numeric(10) or Numeric(15)...?)
Comment: Integer has maximum value of  2147483647. If you use higher numbers, then you should use LongType. `b` can have 18 digits, so it should be `LongType`, `h` also is too big, but also with fraction part - that's why I recommend DecimalType (or DoubleType if you use Doubles in code - Decimal is safier as it can holds much bigger numbers)
Comment: Thanks. I am getting this error when trying DecimalType (all other Types are OK):
:84: error: type mismatch;
 found   : org.apache.spark.sql.types.DecimalType.type
 required: org.apache.spark.sql.types.DataType
         StructField("aff_num",DecimalType, true)
Comment: @Joe Try `DecimalType(11,2)`


File system... How does it work?

Question: I am new in Drupal. Now I am trying to understand basic philosophy of Home->  Administration -> Configuration -> Media -> File system. Public file system path here is:
sites/default/files

is set as public path by default and Public file base URLis therefore:
http://example.com/sites/default/files

Couple days ago not knowing about File system I created folder, where I put some pdf files.
http://example.com/custom_files/pdf
In the article I set hyperlinks to these files and everybody may download these pdfs happily.
And now I do not know at all, why should I bother with File system public path??? What is it good for, when I may use any folder I want?
Thanks for answers
Answer: TL;DR
Public file path is used for file uploads that happen in Drupal. Usually you want to use Drupal to manage content, that means article, users and files. This requires you to upload files inside Drupal application and this is where the public file setting comes into play.
Longer version
When you create a Drupal site, you can decide where all file uploads (which are public) should be located. The only rule is, that it have to be inside the webroot, so that they are accessible for download.
By default this is sites/default/files, but it could be /uploads or whatever you like.
This is used for when you actually use Drupal as a CMS and upload files on content like on articles, user profile pictures etc. When you upload files through Drupal and they are public, Drupal will save info about the file, know it's location and can do things with it.
Having the public path configurable is pretty smart, it means to change move or rename the upload folder and you only need you change one setting for it to work.
If you have FTP access you can upload any file to the webserver, it will be accessible to users etc. You should note that uploading files this way, means that Drupal wont know that they exist and can't actually use them in any way. It might be a good solution for your use case, but you are effectively bypassing Drupal as a CMS and if you plan on manually uploading all files through FTP, you will loose a lot of the file management features and the public file setting wont matter one bit.
Hope this clear things up for you a bit.
Comment: Thanks for reply... it clear things as you said... :-) I could not find it anywhere, or it was not explained as explicitly as you did...

File system... How does it work?


explanation of result of function auto.arima()

Question: I used the function auto.arima() to a monthly data but I obtained "ARIMA(0,1,0)".
any explanation of this result ?
Comment: It means the model is not AR and not MA but I(1), i.e. a random walk
Comment: Please see http://stats.stackexchange.com/search?q=ARIMA+explanation.
Comment: Yes, that will be the model for your data, and you can look up the structure of the ARIMA. Here you go. https://onlinecourses.science.psu.edu/stat510/node/49
Answer: The model is a first-difference model used to handle non-stationarity. When $X_i$ is the $i$th observation in the series, the model is $Y_i = X_i - X_{i-1}$.


Unity 2d - Inimigo seguir o jogador

Question: Bom, estou com problema para fazer o inimigo seguir o jogador, fiz o código abaixo:
<code>public class folow : MonoBehaviour {

public Transform target;//set target from inspector instead of looking in Update
public float speed = 3f;
private Transform myTransform;

void Start()
{
    myTransform = this.GetComponent<Transform>();

}

void Update()
{

    //rotate to look at the player
    transform.LookAt(target.position);
    transform.Rotate(new Vector3(0, -90, 0), Space.Self);//correcting the original rotation

        myTransform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);

}
</code>
o problema é que ele apenas tenta ir em direção ao player, mas não consegue desviar de objetos e fica preso em qualquer obstaculo
Comment: Claro que não. Afinal, você *não incluiu nenhum código* pra ativamente evitar obstáculos, apenas moveu o inimigo em direção ao jogador ignorando o cenário. Se você quer que o inimigo ache um caminho até o jogador, precisará construir um [*pathfinding*](https://en.wikipedia.org/wiki/Pathfinding). Uma resposta que ensine a fazer isso seria muito ampla para o formato deste site. Você poderia construir um *pathfinding* próprio, mas eu sugiro usar o da Unity. Procure tutoriais sobre `NavMesh`: https://www.youtube.com/watch?v=9zzMTEKif4Q Depois, se tiver dúvidas específicas, volte aqui e pergunte.
Answer: Viva,
Basicamente o seu código está correcto... A agora falta-lhe dar inteligência para encontrar o caminho possivel para chegar ao alvo que marcou.
De forma simples tem:

A* Pathfinding Project
NavMesh

Ambos são otimas escolhas... Apenas tem de ter em conta que em 2d apenas o A* Pathfinding Project é compatível.
Podia dar um exemplo, mas o código necessario é praticamente nulo, visto que já esta feito todos os scripts que necessita. (Em ambas as opções que mencionei acima)
Comment: Muito obrigado, era isso que eu estava procurando, tentei usar o NavMesh nativo do unity mas ele só funciona em 3d

Unity 2d - Inimigo seguir o jogador


Spring-WS SOAP server with existing WSDL not finding endpoint

Question: I am trying to develop a quick SOAP server to use during testing using Spring-Boot and Spring-WS.  It is contract first as I have existing WSDL and XSD files and have my java classes generated at build time from them.  However, when I send a request through using either curl or SOAPUI, I get the following error:
$ curl --header "content-type: text/xml" -d @request.xml http://localhost:8080/ws

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
  <SOAP-ENV:Header/>
  <SOAP-ENV:Body>
    <SOAP-ENV:Fault>
      <faultcode>SOAP-ENV:Server</faultcode>
      <faultstring xml:lang="en">No adapter for endpoint [public org.csapi.schema.parlayx.bpxg.common.v3_1.ChargingInformation com.meanwhileinhell.mock.soap.MockVolumeChargingEndpoint.getAmount(java.lang.String,long,java.util.List<org.csapi.schema.parlayx.payment.v3_0.Property>) throws org.csapi.wsdl.parlayx.common.v3_0.faults.ServiceException,org.csapi.wsdl.parlayx.common.v3_0.faults.PolicyException]: Is your endpoint annotated with @Endpoint, or does it implement a supported interface like MessageHandler or PayloadEndpoint?</faultstring>
    </SOAP-ENV:Fault>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

(Highlights: No adapter for endpoint [...] Is your endpoint annotated with @Endpoint, or does it implement a supported interface like MessageHandler or PayloadEndpoint?
The answer to this question is yes, my endpoint is annotated with @Endpoint.  Full setup below:
build.gradle
plugins {
    id 'org.springframework.boot'
}

configurations {
    all {
        exclude group: 'org.springframework.boot', module: 'spring-boot-starter-log4j2'
    }
}

version = '0.0.1-SNAPSHOT'

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web-services")
    compile("wsdl4j:wsdl4j:1.6.1")
    compile("org.glassfish.jaxb:jaxb-xjc:2.2.11")
    compile('javax.xml.soap:javax.xml.soap-api:1.4.0')
    compile('com.sun.xml.messaging.saaj:saaj-impl:1.5.1')
    compile project(':meanwhile-in-hell-volume-charging-v3-1-wsdl')

    testCompile("org.springframework.boot:spring-boot-starter-test")
}

MockSoapConfig.java
package com.meanwhileinhell.mock.soap.config;

import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.ws.config.annotation.EnableWs;
import org.springframework.ws.config.annotation.WsConfigurerAdapter;
import org.springframework.ws.transport.http.MessageDispatcherServlet;

@EnableWs
@Configuration
public class MockSoapConfig extends WsConfigurerAdapter {

    @Bean
    public ServletRegistrationBean messageDispatcherServlet(final ApplicationContext applicationContext) {
        MessageDispatcherServlet messageDispatcherServlet = new MessageDispatcherServlet();
        messageDispatcherServlet.setApplicationContext(applicationContext);
        messageDispatcherServlet.setTransformWsdlLocations(true);
        return new ServletRegistrationBean(messageDispatcherServlet, "/ws/*");
    }
}

MockVolumeChargingEndpoint.java
package com.meanwhileinhell.mock.soap;

import java.util.List;

import org.csapi.schema.parlayx.bpxg.common.v3_1.ChargingInformation;
import org.csapi.schema.parlayx.bpxg.common.v3_1.ObjectFactory;
import org.csapi.schema.parlayx.payment.v3_0.Property;
import org.csapi.wsdl.parlayx.common.v3_0.faults.PolicyException;
import org.csapi.wsdl.parlayx.common.v3_0.faults.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;

import generated.org.csapi.wsdl.parlayx.bpxg.payment.volume_charging.v3_1._interface.VolumeCharging;

@Endpoint
public class MockVolumeChargingEndpoint implements VolumeCharging {
    private static final Logger logger = LoggerFactory.getLogger(MockVolumeChargingEndpoint.class);

    private static final String NAMESPACE = "http://www.csapi.org/wsdl/parlayx/bpxg/payment/volume_charging/v3_1/service";

    @Autowired
    public MockVolumeChargingEndpoint() {
    }

    @Override
    @PayloadRoot(namespace = NAMESPACE, localPart = "getAmount")
    @ResponsePayload
    public ChargingInformation getAmount(final String endUserIdentifier,
                                         final long volume,
                                         final List<Property> parameters) throws
                                                                          ServiceException,
                                                                          PolicyException {

        logger.debug("GetAmount for endUserIdentifier=[{}], volume=[{}], properties=[{}]",
                     endUserIdentifier,
                     volume,
                     parameters);

        ObjectFactory objectFactory = new ObjectFactory();
        return objectFactory.createChargingInformation();
    }
}

This is the generated interface that I am implementing:
VolumeCharging.java
package generated.org.csapi.wsdl.parlayx.bpxg.payment.volume_charging.v3_1._interface;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;

/**
 * This class was generated by Apache CXF 3.3.2
 * 2020-01-27T09:24:18.615Z
 * Generated source version: 3.3.2
 *
 */
@WebService(targetNamespace = "http://www.csapi.org/wsdl/parlayx/bpxg/payment/volume_charging/v3_1/interface", name = "VolumeCharging")
@XmlSeeAlso({org.csapi.schema.parlayx.payment.volume_charging.v3_1.local.ObjectFactory.class, org.csapi.schema.parlayx.bpxg.payment.volume_charging.v3_1.local.ObjectFactory.class, org.csapi.schema.parlayx.bpxg.common.v3_1.ObjectFactory.class, org.csapi.schema.parlayx.common.v3_1.ObjectFactory.class, org.csapi.schema.parlayx.payment.v3_0.ObjectFactory.class})
public interface VolumeCharging {

    @WebMethod
    @RequestWrapper(localName = "getAmount", targetNamespace = "http://www.csapi.org/schema/parlayx/bpxg/payment/volume_charging/v3_1/local", className = "org.csapi.schema.parlayx.bpxg.payment.volume_charging.v3_1.local.GetAmount")
    @ResponseWrapper(localName = "getAmountResponse", targetNamespace = "http://www.csapi.org/schema/parlayx/bpxg/payment/volume_charging/v3_1/local", className = "org.csapi.schema.parlayx.bpxg.payment.volume_charging.v3_1.local.GetAmountResponse")
    @WebResult(name = "result", targetNamespace = "http://www.csapi.org/schema/parlayx/bpxg/payment/volume_charging/v3_1/local")
    public org.csapi.schema.parlayx.bpxg.common.v3_1.ChargingInformation getAmount(

        @WebParam(name = "endUserIdentifier", targetNamespace = "http://www.csapi.org/schema/parlayx/bpxg/payment/volume_charging/v3_1/local")
        java.lang.String endUserIdentifier,
        @WebParam(name = "volume", targetNamespace = "http://www.csapi.org/schema/parlayx/bpxg/payment/volume_charging/v3_1/local")
        long volume,
        @WebParam(name = "parameters", targetNamespace = "http://www.csapi.org/schema/parlayx/bpxg/payment/volume_charging/v3_1/local")
        java.util.List<org.csapi.schema.parlayx.payment.v3_0.Property> parameters
    ) throws org.csapi.wsdl.parlayx.common.v3_0.faults.ServiceException, org.csapi.wsdl.parlayx.common.v3_0.faults.PolicyException;
}

This is the SOAP packet that I am sending in my curl/SOAPUI request:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
                  xmlns:mock="http://www.csapi.org/wsdl/parlayx/bpxg/payment/volume_charging/v3_1/service">
    <soapenv:Header/>
    <soapenv:Body>
        <mock:getAmount>
            <mock:endUserIdentifier>TestUserId</mock:endUserIdentifier>
            <mock:volume>123123</mock:volume>
            <mock:parameters>
                <name>ParameterName</name>
                <value>ParameterValue</value>
            </mock:parameters>
        </mock:getAmount>
    </soapenv:Body>
</soapenv:Envelope>

I just see why it's not hitting my endpoint.  If I change the name getAmount in my request packet to something that is definitely not implemented, I get the message:
No endpoint mapping found for [SaajSoapMessage {http://www.csapi.org/wsdl/parlayx/bpxg/payment/volume_charging/v3_1/service}getTheWeather]

Turning on DEBUG logging for Spring WebServices, I see that my endpoints are being mapped to my endpoint method ok:
2020-01-28 16:36:35.881 DEBUG 72581 --- [           main] yloadRootAnnotationMethodEndpointMapping : Mapped [{http://www.csapi.org/schema/parlayx/bpxg/payment/volume_charging/v3_1/local}getAmount] onto endpoint [public org.csapi.schema.parlayx.bpxg.common.v3_1.ChargingInformation com.meanwhileinhell.mock.soap.MockVolumeChargingEndpoint.getAmount(java.lang.String,long,java.util.List<org.csapi.schema.parlayx.payment.v3_0.Property>)]

2020-01-28 16:36:58.316 DEBUG 72581 --- [nio-8080-exec-1] .WebServiceMessageReceiverHandlerAdapter : Accepting incoming [org.springframework.ws.transport.http.HttpServletConnection@27ef75ac] at [http://localhost:8080/ws]
2020-01-28 16:36:58.481 DEBUG 72581 --- [nio-8080-exec-1] o.s.ws.server.MessageTracing.received    : Received request [SaajSoapMessage {http://www.csapi.org/schema/parlayx/bpxg/payment/volume_charging/v3_1/local}getAmount]
2020-01-28 16:36:58.541 DEBUG 72581 --- [nio-8080-exec-1] yloadRootAnnotationMethodEndpointMapping : Looking up endpoint for [{http://www.csapi.org/schema/parlayx/bpxg/payment/volume_charging/v3_1/local}getAmount]
2020-01-28 16:36:58.541 DEBUG 72581 --- [nio-8080-exec-1] o.s.w.soap.server.SoapMessageDispatcher  : Endpoint mapping [org.springframework.ws.server.endpoint.mapping.PayloadRootAnnotationMethodEndpointMapping@623a8092] maps request to endpoint [public org.csapi.schema.parlayx.bpxg.common.v3_1.ChargingInformation com.meanwhileinhell.mock.soap.MockVolumeChargingEndpoint.getAmount(java.lang.String,long,java.util.List<org.csapi.schema.parlayx.payment.v3_0.Property>)]
2020-01-28 16:36:58.544 DEBUG 72581 --- [nio-8080-exec-1] o.s.w.soap.server.SoapMessageDispatcher  : Testing endpoint adapter [org.springframework.ws.server.endpoint.adapter.DefaultMethodEndpointAdapter@3571b748]
2020-01-28 16:36:58.547 DEBUG 72581 --- [nio-8080-exec-1] s.e.SoapFaultAnnotationExceptionResolver : Resolving exception from endpoint [public org.csapi.schema.parlayx.bpxg.common.v3_1.ChargingInformation com.meanwhileinhell.mock.soap.MockVolumeChargingEndpoint.getAmount(java.lang.String,long,java.util.List<org.csapi.schema.parlayx.payment.v3_0.Property>)]: java.lang.IllegalStateException: No adapter for endpoint [public org.csapi.schema.parlayx.bpxg.common.v3_1.ChargingInformation com.meanwhileinhell.mock.soap.MockVolumeChargingEndpoint.getAmount(java.lang.String,long,java.util.List<org.csapi.schema.parlayx.payment.v3_0.Property>)]: Is your endpoint annotated with @Endpoint, or does it implement a supported interface like MessageHandler or PayloadEndpoint?

So it would seem that my endpoint is getting mapped ok, but there is some issue with the endpoint adapter?
Answer: Needed to wrap my payloads in JAXBElement type for Spring to get the message handler adapters to support the endpoint.
@PayloadRoot(namespace = NAMESPACE, localPart = "getAmount")
@ResponsePayload
public JAXBElement<GetAmountResponse> getAmount(@RequestPayload JAXBElement<GetAmount> request) {
    ...
}


How do I export my site structure?

Question: Since Drupal 8 is days away from release, I've started experimenting with rebuilding my personal site on it. The one feature I am really looking forward to is configuration management in code.
Unfortunately, my taxonomy terms are not exported by the config module. From what I've found googling on the subject, neither are menu items.
Which leaves me stumped. The natural way to set a sites structure (or information architecture) is a combination of content types, taxonomy vocabularies and their terms, and a set of menus. Or, at least, that seems to be the natural way to me.
While googling, I could not find any discussion on this subject.
So, how do I export the taxonomy terms and menu items that define my sites structure?
Edit to add some details:
Assume the site is a magazine. It has Fiction, World Events, Technical, and Letters sections. There will always be a /fiction, a /world-events, a /technical, and a /letters menu items. There are several kinds of content types, each can go into various sections.
So I create a vocabulary for the sections.
<code>sections
- fiction
- world events
- technical
- letters
</code>
A taxonomy reference field is added to each content type.
Thus, when content is created it is tagged with the appropriate section terms.
If the site deploys without one of those sections, it is broken. Thus the menu items, and taxonomy terms should be considered configuration. Not content.
From what I've read, the main problem is that terms and menu items can collide if you try to move them between instances. Terms have a incrementing tid. Menu items also have an incrementing id. Though I do see the taxonomy_term_data and menu_link_content tables which seem to map uuid's with term and menu item ids. So, couldn't that be used to make exporting them feasible?
Also, isn't one of the main uses cases for taxonomies defining a site's structure?
I guess what I'm stuck on is that some menu items and some taxonomy terms really should be considered as configuration, not data. As in, if I were coding this instead of using Drupal, I'd hard code them. Thus, they should be exportable so that they can be committed to version control.
And that's why I'm asking "How do I export my site structure?"
Comment: Found this: http://dcycleproject.org/blog/83/what-content-what-configuration Placeholder content is an interesting idea, but not easily created using just D8. Hrm...
Answer: For install content, you can use Default Content for D8 (also on GitHub). For ongoing content syncing Entity Pilot is expected to enter public beta this week and there is an active initiative around Deploy module.
Disclaimer: Entity Pilot is my project.
Comment: I haven't tried it yet, but default_content seems like the closest we can get to what I want right now. So I'll accept this answer. If anyone ever makes a module that lets you select content and force config to export it, let me know. :)
Answer: For a deployment that you are planing, you should use features, that packs it all into a module. To add menus you can use yml-files and basic content like taxonomy terms can be added in module_install(). Or wait until UUID Features is ported to drupal 8.
Comment: I was hoping to avoid using features for configuration... Since features should be packages of functionality that can apply to many sites. What I'd really like is an option that has the effect of changing "content" into "config" so that the config module exports it. That said, I likely will have to use features to get what I want...
Answer: Managing configuration in Drupal 8 states:

The Configuration Manager module in Drupal 8 provides a user interface
  for importing and exporting configuration changes between a Drupal
  installation in different environments, such as Development, Staging
  and Production, so you can make and verify your changes with a
  comfortable distance from your live environment.
You can import, export, and synchronize configuration in your site via
  Manage > Configuration > Configuration Synchronization
  (admin/config/development/configuration).

Aparently it supports many types, including taxonomy and menus:
Comment: Technically menu items aren't content nor configuration. They don't inherit from ContentEntityBase and they don't implement ContentEntityInferace - so they aren't content. They also aren't configuration. Which really sucks as you have to treat them in a special way.
Comment: Supports menus, but not menu items. Menu without menu items is kind of useless :(
Comment: Yes, menu items are content, and therefore not export through configuration.

How do I export my site structure?


How do I find out which physical port my ethersvi MAC address corresponds to on a Cisco switch?

Question: I'm doing a layer2 network map (my first) and this is the first virtual mac I've encountered.
From the mac address table of switch1, I have
VLAN 1    6416.8d98.52c0    DYNAMIC     Te0/1
and on the other, which I'll call switch0, when I am looking for that mac address, this is what I find:
Vlan1 is up, line protocol is up
  Hardware is EtherSVI, address is 6416.8d98.52c0 (bia 6416.8d98.52c0)
  Internet address is 192.168.101.252/24
How do I find out the physical port that corresponds to?
When I do a show vlanon switch0, I get:
VLAN Name                             Status    Ports

1    default                          active    Gi0/1, Gi0/2, Gi0/11, Gi0/12, Gi0/13, Gi0/14, Gi0/15, Gi0/16, Gi0/17, Gi0/18, Gi0/19, Gi0/20, Gi0/21, Gi0/22, Gi0/23, Gi0/24
2    VLAN0002                         active    Gi0/7, Gi0/8
3    VLAN0003                         active    Gi0/9, Gi0/10
4    VLAN0004                         active    Gi0/3, Gi0/4
5    VLAN0005                         active    Gi0/5, Gi0/6
What command should I use?
Edit: Mike's command worked (thanks mike!), but now that I have had time to pay a little more attention to my mac address table, I am re-confused. My ignorance will shine bright, so try not to be blinded by it:
How come several ports belong to many VLANs at once? here is a sample of the output on one of the switches:
VLAN
1    0014.4f97.bb1f    DYNAMIC     Gi0/11 <-- ??? similar to MACs on a solaris box
1    edgertr  Fa0/0    DYNAMIC     Gi0/1
1    sw00     Te0/1    DYNAMIC     Te0/1
1    6416.8d98.52c0    DYNAMIC     Te0/1  <--virtual MAC from before
2    box2     nxge2    DYNAMIC     Te0/1
2    box1   e1000g2    DYNAMIC     Gi0/7
2    box0   e1000g2    DYNAMIC     Te0/1
2    sw00     Te0/1    DYNAMIC     Te0/1
3    box2     nxge3    DYNAMIC     Te0/1
3    box1   e1000g3    DYNAMIC     Gi0/9
3    box0   e1000g3    DYNAMIC     Te0/1
3    sw00     Te0/1    DYNAMIC     Te0/1
4    box2     nxge0    DYNAMIC     Te0/1
4    box0   e1000g0    DYNAMIC     Gi0/3
4    edgertr  Fa0/0    DYNAMIC     Gi0/1
4    boxx      bge0    DYNAMIC     Gi0/2
4    box0   e1000g0    DYNAMIC     Te0/1
4    sw00     Te0/1    DYNAMIC     Te0/1
5    sw00     Te0/1    DYNAMIC     Te0/1

And here is my current attempt at a layer2 diagram for good measure (incomplete, haven't started on the other switch). Anything I should leave out or add?
Comment: +1, nice diagram.  The perfect world is to make it big enough that you can include port numbers on the ethernet switches themselves
Comment: Woops. Thanks for the tip. I didn't notice that checkmark. I've edited this question with more questions but maybe I should've started another question?
Comment: to answer your question about a port belonging to multiple Vlans, that is part of how a Vlan Trunk works.  For more information, please read [this answer about Vlan tagging](http://stackoverflow.com/a/8629725/667301)
Answer: Usually, the best way to map a Cisco network is with CDP (as long as it is enabled on switch0 and switch1).  Do a show cdp nei Te0/1 on switch1; this will tell you what Cisco device/port number is connected on the other side.

Vlan1 is up, line protocol is up Hardware is EtherSVI, address is   6416.8d98.52c0 (bia 6416.8d98.52c0) Internet address is 192.168.101.252/24
How do I find out the physical port that corresponds to?

Strictly speaking an SVI doesn't correlate a virtual mac-addresses to a single physical port; that is the point of an SVI. An SVI's virtual mac-address is available on any port that belongs to that SVINote 1.  You can find what physical port in a given SVI connects to another by using the switch's CAM, LLDP, or CDP tables.
BTW, your switches are using an SVI on Vlan1; best practices dictate that you don't use Vlan1 for data traffic, but that's getting outside the scope of this question.

Note 1: As long as that port isn't blocked by spanning-tree
Comment: +1. "don't use Vlan1 for data traffic". Any traffic anyhow, even admin/management, shouldn't use vlan1.
Answer:
How come several ports belong to many VLANs at once?

I'm not well aware of the internals of SVIs, like Mike seems to be, or of how it relates to the virtual LANs your switches are using... However:
One must not confuse virtual LANs (tag-based differenciated traffic on a single physical LAN) which the show vlan displays info about, and a vlan1 interface, which you configure in conf t > int vlan 1 and which has a MAC address.
Why is this interface named vlan1 ? Is there a good reason related to the fact that an SVI interface is a ghost that listens to any traffic going through the virtual LAN 1??
Beats me.
One fact: switches need an interface so they can be configured. No interface, (no IP traffic), no interaction, no terminal, no nothing.
Another fact: virtual LAN number 1 is a special one: virtual LANs work thanks to ethernet frames wearing numbered tags. The number 1 virtual LAN is a catch-all for any frame that wouldn't be wearing any tags (or any tag with number 1, as far as I know).
Without configuration done on the switch (no virtual LANs configured yet) it makes sense that the somewhat-virtual interface your create and use to remotely reach the switch would be related to the virtual LAN number one.
Damn! Forgot to answer your question... But I'm sure you did that yourself by now. Your bewonderment rooted in the confusion between vlans and vlans. Outrageous. :)


WebGL vertices array order

Question: I've just read this mozilla WebGL tutorial and came upon a question
https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Tutorial/Adding_2D_content_to_a_WebGL_context
I'm wondering why an array of positions for a simple square should be
const positions = [
    -1.0,  1.0, // 1 - top left
     1.0,  1.0, // 2 - top right
    -1.0, -1.0, // 3 - bottom left
     1.0, -1.0, // 4 - bottom right
];

instead of
const positions = [
    -1.0,  1.0, // 1 - top left
     1.0,  1.0, // 2 - top right
     1.0, -1.0, // 4 - bottom right
    -1.0, -1.0, // 3 - bottom left
];

which would make more sense to me.
In the first case (the correct one), it seems that the lines drawing the square from vertex to vertex should cross, but obviously it doesn't work that way.
Answer: They're using TRIANGLE_STRIP indexing in that example:

Draws a series of triangles (three-sided polygons) using vertices v0,
  v1, v2, then v2, v1, v3 (note the order), then v2, v3, v4, and so on.
  The ordering is to ensure that the triangles are all drawn with the
  same orientation so that the strip can correctly form part of a
  surface.

Wikipedia - Triangle strip

WebGL vertices array order