Xslt distinct select / Group by

Question: <statisticItems>
    <statisticItem id="1" frontendGroupId="2336" caseId="50264"  />
    <statisticItem id="2" frontendGroupId="2336" caseId="50264"  />
    <statisticItem id="3" frontendGroupId="2337" caseId="50265"  />
    <statisticItem id="4" frontendGroupId="2337" caseId="50266"  />
    <statisticItem id="5" frontendGroupId="2337" caseId="50266"  />
</statisticItems>

<?xml version="1.0" encoding="utf-8"?>
  <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" omit-xml-declaration="yes"/>

  <xsl:key name="statistic-by-frontendGroupId" match="statisticItem" use="@frontendGroupId" />

  <xsl:for-each select="statisticItems/statisticItem[count(.|key('statistic-by-frontendGroupId', @frontendGroupId)[1]) = 1]">
       <xsl:value-of select="@frontendGroupId"/>
  </xsl:for-each>

What i have done so fare is to go through all distict frontendGroupIds. What i would like to do now is to do a count of all the distict caseIds for each distict frontendGroupId but i cant seem to make that work. Can someone help me here plz?
Answer: You were close:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:output method="text" />

  <xsl:key
    name="statistic-by-frontendGroupId"
    match="statisticItem"
    use="@frontendGroupId"
  />

  <xsl:template match="statisticItems">
    <xsl:for-each select="
      statisticItem[
        count(
          . | key('statistic-by-frontendGroupId', @frontendGroupId)[1]
        ) = 1
      ]
    ">
      <xsl:value-of select="@frontendGroupId"/>
      <xsl:value-of select="' - '"/>

      <xsl:value-of select="
        count(
          key('statistic-by-frontendGroupId', @frontendGroupId)
        )
      "/>
      <xsl:value-of select="'
'"/>
    </xsl:for-each>
  </xsl:template>

</xsl:stylesheet>

This results in:

2336 - 2
2337 - 3

EDIT - Oh, I see you want the distinct count within the group. This would be:

<xsl:key
  name="kStatisticItemByGroupAndCase"
  match="statisticItem"
  use="concat(@frontendGroupId, ',', @caseId)"
/>

<xsl:template match="statisticItems">
  <xsl:for-each select="
    statisticItem[
      count(
        . | key('kStatisticItemByGroup', @frontendGroupId)[1]
      ) = 1
    ]
  ">
    <xsl:value-of select="@frontendGroupId"/>
    <xsl:value-of select="' - '"/>
    <xsl:value-of select="
      count(
        key('kStatisticItemByGroup', @frontendGroupId)[
          count(
            . | key('kStatisticItemByGroupAndCase', concat(@frontendGroupId, ',', @caseId))[1]
          ) = 1
        ]
      )
    "/>
    <xsl:value-of select="'
'"/>
  </xsl:for-each>
</xsl:template>

Which looks (admittedly) a bit frightening. It outputs:

2336 - 1
2337 - 2

The core expression:
count(
  key('kStatisticItemByGroup', @frontendGroupId)[
    count(
      . | key('kStatisticItemByGroupAndCase', concat(@frontendGroupId, ',', @caseId))[1]
    ) = 1
  ]
)

boils down to:
Count the nodes from "key('kStatisticItemByGroup', @frontendGroupId)" that fulfill the following condition: They are the first in their respective "kStatisticItemByGroupAndCase" group.
Looking closely, you will find that this is no more complicated than what you already do. :-)

EDIT: One last hint. Personally, I find this a lot more expressive than the above expressions, because it emphasizes node equality a lot more than the "count(.|something) = 1" approach:
count(
  key('kStatisticItemByGroup', @frontendGroupId)[
    generate-id()
    =
    generate-id(
      key('kStatisticItemByGroupAndCase', concat(@frontendGroupId, ',', @caseId))[1]
    )
  ]
)

The result is the same.
Answer: You are attempting to sort via the dreaded 'MUENCHIAN' method - something i've found so confusing that is not worth trying - so i worked out my own method.
It uses two transformations instead of one.
The first sorts the data into the right order based on your grouping requirements -- your sample data is already in the right order so i'll leave it out of this explanation( ask if you want help here)
The second transformation does the grouping simply by comparing one node to the next:
    <?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"
>
    <xsl:output method="xml" indent="yes"/>

    <xsl:template match="statisticItems">
        <groupedItem>
            <xsl:apply-templates select="statisticItem"></xsl:apply-templates>
        </groupedItem>
    </xsl:template>

    <xsl:template match="statisticItem">
        <xsl:choose>

            <xsl:when test="position()=1">
                <xsl:apply-templates select="@frontendGroupId" />
            </xsl:when>

            <xsl:when test="@frontendGroupId!=preceding-sibling::statisticItem[1]/@frontendGroupId">
                <xsl:apply-templates select="@frontendGroupId" />
            </xsl:when>

        </xsl:choose>

        <xsl:apply-templates select="@caseId" />

    </xsl:template>

<xsl:template match="@frontendGroupId">
    <group>
        <xsl:variable name="id" select="." ></xsl:variable>
        <xsl:attribute name="count">
            <xsl:value-of select="count(//statisticItem/@frontendGroupId[.=$id])"/>
        </xsl:attribute>
        <xsl:value-of select="." />
    </group>
</xsl:template>

    <xsl:template match="@caseId">
        <value>
            <xsl:value-of select="." />
        </value>
    </xsl:template>

</xsl:stylesheet>

With this method you can go several groups deep and still have maintainable code.
Comment: "something i've found so confusing that is not worth trying" What a strange attitude.
Comment: you right my grammar is wrong - I did try - alot, i needed to group serveral levels( 4 or 5 if remember correctly). I did get it working but the key definitions were very confusing, espcially when the nested groupings get deep. But the two pass method i've tried to show above is much easier to explain and read
Comment: I recommend reading my answer to: http://stackoverflow.com/questions/948218/xslt-3-level-grouping-on-attributes - maybe it helps you :-)
Comment: I so Wish SO had been around back then! your XSLT to JS descriptions are very good... but I still feel using my method is much much easier to understand and maintain. OK it may be fractionally slower, I did test my transformation with thousands of elements.
Comment: Just try to use a key every time you need to group something. I'll come to you. You'll just never fully "get it" if you never try.

Xslt distinct select / Group by


Insert persistence record in DB where two table are seprate

Question: I am using struts and hibernate. i am trying to insert data in two table which are independent. if first table insertions create any error than i can not able to insert second table data and vice-versa. i want to do like this. how can i do this?
code
public String create() {
    getDaoFactory().instantiateDAO(daoClass).saveOrUpdate(entity);
    getDaoFactory().getMatchPredictionOptionLevel2().saveOrUpdate(
                    optionLevel2);
   return SUCCESS:

}

public T saveOrUpdate(T entity) {
        try {
            getSessionTx().save(entity);
            commit();
        } catch (Exception e) {
            rollback();
            e.printStackTrace();
        } finally {
            getSession().close();
        }
        return entity;
    }

public Session getSessionTx() {
        System.out.println("In Get Sassion Method getSessionTx");
        if (this.session == null)
            this.session = HibernateUtil.getSessionFactory().openSession();

        this.session.beginTransaction();
        return this.session;
    }

Comment: can anyone tell me solution?
Answer: That is what Transactions has been made for.
For Instance:
        try{
            session = HibernateUtil.getSessionFactory().openSession();//<==Creade Session from SessionFactory

            tx = session.beginTransaction();//<==== Start Transacton
            tx.setTimeout(5);
            //doSomething(session); if one of the queries fail to insert it goes to catch
            tx.commit();

        }catch(RuntimeException e){
            try{
                tx.rollback();//<=== you'll be rolling back the previous inserting value in case if one failed to insert
            }catch(RuntimeException rbe){
                log.error("Couldn't roll back transaction", rbe);
            }
            throw e;
        }finally{
            if(session!=null){
                session.close();
            }

Read more about it Here.
Comment: actually for insertion i have use seprate mothod for that. for individualy inseriton i have rollback but if first table query successfully inserted and it create error in second table then first table entry is not roll back
Comment: @CHiRAG your code is broken 1. String should return a value, 2. what is getSessionTx() ?
Comment: see i have add return type, and actually my function is have other logic so i have add important code for that only
Comment: `getSessionTx()` its a custome method for create session and initilize to transaction


Android Graph Coordinatesystem

Question: I am trying to implement a graph view in my android app. It should be able to enter a function. (eg.: f(x1) = x², or f(x) = sin(x) + 5)
For that i will need a coordinate system where i can later draw my function after calculating about 50 points. It should later look similar to that:

I already tried it with the android libary GraphView and i was able to draw something but in this libary i don't have a coordinate so that my graph is "somewhere";
        int num = 400;
    GraphViewData[] data = new GraphViewData[num];
    GraphViewData[] data2 = new GraphViewData[num];
    double x = -100;
    double y = 0;

    //Coordinate system x
    for (int i=0; i<num; i++) {
           data[i] = new GraphViewData(x, y);
           x = x + 0.5;
        }

     x = 0;
     y = -100;
    for (int i=0; i<num; i++) {
           data2[i] = new GraphViewData(x, y);
           y = y + 0.5;
        }

     x = -100;
     y = 0;

    GraphViewData[] data3 = new GraphViewData[num];
    //Coordinate system y
    for (int i=0; i<num; i++) {
           y = (x * x);
           data3[i] = new GraphViewData(x, y);
           x = x + 0.5;
        }
    // sin curve

    for (int i=0; i<num; i++) {
       y = Math.sin(x);
       y = x * x + 50;
       data2[i] = new GraphViewData(x, y);
       x = x + 0.2;
    }

    GraphView graphView = new LineGraphView(
          this
          , ""
    );

    // add data
    graphView.addSeries(new GraphViewSeries(data));
    graphView.addSeries(new GraphViewSeries(data2));
    graphView.addSeries(new GraphViewSeries(data3));
    // set view port, start=-100, size=200
    graphView.setViewPort(-100, 200);

    graphView.setScrollable(false);
    graphView.setScalable(false);

    LinearLayout layout = (LinearLayout) findViewById(R.id.graph1);
    layout.addView(graphView);

With data1 and data2 i am able to draw a Coordinate system:

but as soon as i add data3 it looks like: (because of the huge amount)

Any idea on that ? What is the best and easiest way to do this ? (I don't need multiple lines or scalable) I guess this is a wrong library because there is no correct way to draw this, is it?
Thanks !
EDIT: working fine with: graphView.setManualYAxisBounds(100, -100);

Thanks alot jjo64
Answer: try to fix the y axis bounds with graphView.setManualYAxisBounds(100, -100)
Comment: WOW ! thanks, looks like it works pretty nice. i will later post my result. What a luck you read this :) Am i allowed to use it in my app with proper credit to you ?
Comment: there's a donate button on the project page, if you want to ;-)  http://android-graphview.org/#donate
Comment: i donated 5€, sorry i don't have more on my paypal account :) Thank you alot !

Android Graph Coordinatesystem


picture formatting for kernel svm

Question: I'm having some difficulty to get a series of images into the correct format to feed into sklearn.svm.SVC.
This is my first image recognition project, and so Im suffering a bit.
Ive got a loop which brings in a bunch of base64 RGB images (of different sizes) to a dataframe
imageData = mpimg.imread(io.BytesIO(base64.b64decode(value)),format='JPG')

then I convert the RGB image into gray-scale, and flatten
data_images = rgb2gray(imageData).ravel()

where rgb2gray:
def rgb2gray(rgb):
    r, g, b = rgb[:,:,0], rgb[:,:,1], rgb[:,:,2]
    gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
    return gray

If I look at the size differences
df_raw.sample(10)

We can see that the picture pixel lengths are not the same between my samples. Im a little confused here about how to proceed. For lack of a better idea I decided to add a padding based on the picture with the largest size,
df_raw.picLen.max()

Then appending a number of zeros to the end of each 1D picture array.
def padPic(x,numb,maxN):
    N = maxN-len(x)
    out = np.pad(x,(numb,N),'constant')
    return out

calling
df_raw['picNew'] = df_raw.apply(lambda row: padPic(row['pic'],0,df_raw.picLen.max()), axis=1)
df_raw['picNewLen']  = df_raw.apply(lambda row: len(row['picNew']), axis=1)

I now have arrays all of the same size

From here I attempt to fit a model to support vector algorithm using the picture data as X and a set of labels as y.
from sklearn.svm import SVC
X_train, X_test, y_train, y_test = train_test_split(df_raw.picNew, df_raw.name, test_size = 0.2, random_state=42)

check the size:
print('Training data and target sizes: \n{}, {}'.format(X_train.shape,y_train.shape))
print('Test data and target sizes: \n{}, {}'.format(X_test.shape,y_test.shape))

Training data and target sizes:  (198,), (198,) Test data and target
  sizes:  (50,), (50,)

after Ive convinced myself everything is ready, then I try to fit the model
svm = SVC()
svm.fit(X_train, y_train)

this throws an error, and I cant figure out why:

/opt/wakari/anaconda/envs/ulabenv_2018-11-13_10.15.00/lib/python3.5/site-packages/numpy/core/numeric.py in asarray(a, dtype, order)
      499
      500     """
  --> 501     return array(a, dtype, copy=False, order=order)
      502
      503
ValueError: setting an array element with a sequence.

I think this must have to do with the array size, but I cant figure it out. :-/
In addition to the error, more generally, I have a question to my approach in general. In particular I think my "padding" is probably incorrect and maybe some resize would be better.
I appreciate any feedback to my methodology. Thanks
Answer: I am pretty sure this is due to using list in a feature column and strings as target values. For the latter You need to use LabelEncoder class to turn them to normalized class labels, as required by fit().
See description here:
https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html
This needs to be done before train/test split to make sure you have all names 'seen' by the LabelEncoder.
For the former, you might want to search for MNIST tutorials, that will provide a plethora of algorightms applied to image classification problems.
Also, Resize before flattening should work better than padding.
Comment: shoot, I completely missed the encoder. Thank you. When I fit and set the encoder le = LabelEncoder(), le.fit(df_raw.name), le.transform(df_raw.name) I still have the same error.
Comment: just to show that my pictures have an equal amount of elements. 'result = map(lambda x: len(x), X_train), print(np.unique(list(result))) ' [830435]
Answer: Ive figured out the problem.
Thank you to Artem for his catching my obvious problem of not encoding the classes, but this was not my issue in the end.
Turns out the way that my picture array was represented was incorrect.
The original array was df_raw['picNew'].shape which evaluates to

(248,)

What I needed was a 2D representation
np.stack(df_raw['picNew'] , axis=1).shape

(830435, 248)

All good now.
I'm still unsure about the most "correct" way to resize the images to be all the same length. Appending 0 to the array lengths seems a bit unsophisticated... So if anyone has an idea :)

picture formatting for kernel svm


creating function names dynamically

Question:
Possible Duplicate:
Dynamic function name in javascript?

I want to achieve the below result .Can someone tell me how.Basically name is dynamic.
 var name =  'tab'+ ID;
name(tab);

So far tried stuff which works fine.Is it a good way of doing or else somebody can suggest another way.
var function_name  =  't'+ ID;
if (typeof(window[function_name]) === "function")
{
    window[function_name](tab);
}

Comment: Note that the above only works if the function being called is in the global scope, or if you explicitly put it there.
Answer: I'd first create an object to store your functions:
var funcs = {};

Then you can just use bracket notation:
var id = '001';

funcs['tab'+ id] = function(tab) {

};

funcs.tab001(tab);
// or if you have special chars...
funcs['tab001'](tab);

creating function names dynamically


c# - Creating a method that uses an array AND restarting a console application with a loop

Question: My most humble greetings S.O folk,
I am having trouble with the syntax and language requirements for the following assessment criteria.
NOTE: I am not looking for a definitive/"here you go!" answer (i.e: a completed assignment) but I do genuinely need some guidance with the c# language in order to complete the assignment. Thank you in advance.
This is the assignment brief:

Generate a card for the dealer that displays 2 random numbers using a struct.
Generate a card for the player that displays 3 random numbers using (the same) struct.

-- So far, I have been able to do this with the code at the bottom of my post. The rest of the assessment criteria has me stuck --

Ask the user to type in which single number they want to "play" against the dealer to win. These options should be stored in an array {0, 1, 2} that will be called upon to run a method to calculate the winner. I must also use the TryParse method(?) to convert the user input into a number. -- To run the calculate winner method, I am assuming that I will use an if statement something like this:
if (PlayerSelection > DealerCard)
{
    Console.WriteLine ("You Win");
}
else (DealerCard > PlayerSelection)
{
    Console.WriteLine ("Dealer Wins");
}
else if (PlayerSelection == DealerCard)
{
    Console.WriteLine ("It is a draw");
}

-- Apart from the above, I do not understand the syntax for using the tryParse method to convert user input into a number--

Finally, I must create a loop that will run the program again depending on user input. Would you like to play again? User input Yes = run application again  or User input No = Exit application.

As I said, this is an assignment so I'm not looking for a quick answer. Some patient guidance that will (hopefully) see me complete this assignment and understand more would be much appreciated. I also apologize if this exercise is incredibly simple for some. I am very VERY new to the c# language and programming in general.
Below is the code I have so far. As you can see, I have structured it so I can follow along with my own work without getting lost. I feel like a toddler but hey, dumbing things down seems to be the only way I can really get a handle on any of this stuff. I may not be a natural at programming but by god I wont give up!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Assessment2_Nicole_Haines

{
    class Program
    {

        static void Main(string[] args)
        {
            card PlayerCard = new card(6,26); // Calls an instance of the card struct to create PlayerCard card

card PlayerCard2 = new card(6,26); // Calls an instance of the card struct to create PlayerCard2 card
            card PlayerCard3 = new card(6,26); // Calls an instance of the card struct to create PlayerCard3 card

            card DealerCard = new card(6,26); // Calls a new instance of the struct (named card) to create the dealers card with 2 numbers

            //declare an array of card
            card[] PlayerCards = { PlayerCard, PlayerCard2, PlayerCard3 };

            // Welcome text
            Console.WriteLine("Welcome! Press the 'enter' key to play!");
            Console.ReadLine();

            // Use of struct for Dealers single card
            Console.WriteLine("The dealers card is: {0} , {1}", DealerCard.Number1, DealerCard.Number2);
            Console.ReadLine();

            // Use of struct for Players first card
            Console.WriteLine("Your first card is: {0} , {1}", PlayerCard.Number1, PlayerCard.Number2);
            Console.ReadLine();

            // Use of struct for Players second card
            Console.WriteLine("Your second card is: {0} , {1}", PlayerCard2.Number1, PlayerCard2.Number2);
            Console.ReadLine();

            // Use of struct for Players third (and final) card
            Console.WriteLine("Your third (and final!) card is: {0}, {1}", PlayerCard3.Number1, PlayerCard3.Number2);
            Console.ReadLine();

            // Request user input - As you can see - the rest of the code is incomplete/incorrect

            Console.WriteLine("Please enter the number you wish to 'play' in order to beat the dealer:");

                // Accept/Parse user input
// Create a while loop that runs application again if user enters Y. otherwise - exits.

            Console.WriteLine("Would you like to play again?");
            Console.ReadLine();

            Console.WriteLine("You selected 'Y' Let's play again!");
            Console.ReadLine();

            Console.WriteLine("You selected 'N' See you later!");
            Console.ReadLine();

        }

        // Struct

        public struct card
        {

            static Random r = new Random();
            public int Number1;
            public int Number2;
            public card(int Minimum, int Maximum)
            {
                Number1 = r.Next(Minimum, Maximum);
                Number2 = r.Next(Minimum, Maximum);
            }

        }

    }
}

Answer: While the answer is very simple heres a link that will help
http://www.dotnetperls.com/console-readkey
   // Call ReadKey again and test for the letter Y.
info = Console.ReadKey();
if (info.KeyChar == 'Y')
{
    Play again;
}

  // Call ReadKey again and test for the letter Y.
info = Console.ReadKey();
if (info.KeyChar == 'N')
{
   Close;
}

Also I think your if statement,
  if (PlayerSelection > DealerCard)
   {
Console.WriteLine ("You Win");
    }
  else if(DealerCard > PlayerSelection)
  {
Console.WriteLine ("Dealer Wins");
  }
 else if (PlayerSelection == DealerCard)
  {
Console.WriteLine ("It is a draw");
  }
  else{Console.WriteLine("Something Went Wrong"}

As far as determining who wins with the tryparse,
   // Call ReadKey again and test for the letter Y.
info = Console.ReadLine();
    int pleayercardvalue = tryparse(info, int32)
if (playercardvalue != playercard1.value OR playercard2.value OR playercard3.value)
{
    "Select Valid Card";
}
    else
    {
      playercardvalue
    }

None of these are exact code, just the rough idea.
Comment: Thank you. Being a learner I did not even know that the ReadKey method even exists. This is extremely handy to know. Unfortunately the assessment does require the use of a while loop to rerun or exit the application. I have made a note of ReadKey though, that will definitely come in handy with my own experimentation of c# language features.
Comment: Im reasonably sure you will use the readkey method to set the while loop. After all you have to know if they select Y or N.
Answer: Most types in C# have two methods for parsing strings into values of that type, Parse and TryParse. The syntax for calling both is the same.  The TryParse method differs from the Parse method in that TryParse returns a bool that indicates whether the string was parsed or not.  That is, passing "1" to int.TryParse will return true, but passing "A" will return false.
These methods are overloaded.  The easiest one to call is TryParse(string), which just takes the string to be parsed as its only argument.  It will use the application's current Culture settings, whatever that is, to parse the number.  This is probably OK, because the default Culture is the same as that specified in the Windows culture settings.  Other overloads allow you to specify specific culture and formatting options.  Don't worry about those.
Lastly, your loop.  You would put your code inside of a loop, I'd use a do . . . while loop, that first does everything you're doing now, determines the winner, then asks the user if they want to play again.  Parse their response (this isn't a call to TryParse, but comparing their response to the expected response), and if they say yes, the loop repeats.


Qual a diferença de SCRIPT_FILENAME e REQUEST_FILENAME?

Question: Estou estudando URL amigável, e em muitos exemplos me deparei com estas duas formas de escrita:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

e
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d

Qual a diferença entre elas? Olhando a documentação do Apache eu entendi que são a mesma coisa. Será que entendi certo?
Comment: O valor é o mesmo, em princípio. REQUEST_FILENAME é pra fazer par como REQUEST_URI, nunca vi nada falando de algum caso que não fosse o mesmo valor. Em teoria, apontam pra mesma estrutura interna do Apache. Não faço idéia da razão de ter as duas. Teria que olhar documentação antiga pra ver se antes era só SCRIPT_FILENAME, aí faria sentido um "apelido" novo depois, pra combinar com o REQUEST_URI, como comentei. De qq forma, é uma dúvida legítima.
Comment: Muito obrigado pela ajuda @Bacco :D
Answer: SCRIPT_FILENAME :
É o nome da variável CGI geralmente conhecido
REQUEST_FILENAME : É a contrapartida apropriada de REQUEST_URI (que contém o valor do campo uri de request_rec).
Ambas contêm o mesmo valor.


what is the difference between INCLUDE 'param.inc' and INCLUDE 'param.fi'?

Question: How to make a file for .inc for extension in PGI visual FORTRAN?What is the difference between INCLUDE 'param.inc' and INCLUDE 'param.fi' ?
Answer: The INCLUDE statement just includes any text file as a part of the source code.
The difference between your two statements is that one includes a file with a different file name than the other. The extension is completely irrelevant.
You can place in the file param.whatever any Fortran statements you need. Do not care about the file name.


Configuring tomcat https for specific service

Question: I have one web application, in which one specific service needs to go through secure https, and other all service should be http, I did:
<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
           maxThreads="150" scheme="https" secure="true"
           keystoreFile="${user.home}/keystore/keystore.jks" keystorePass="test"
           truststoreFile="${user.home}/keystore/keystore.jks" truststorePass="test"
           truststoreType="JKS" disableUploadTimeout="true"
           enableLookups="true" maxHttpHeaderSize="8192"
           maxSpareThreads="75" minSpareThreads="25"
           clientAuth="true" sslProtocol="TLS" />

but it expects every service as https, is their a way I can configure tomcat which fulfill my requirement?
Answer: You can run both both HTTP and HTTPS on same server, just add another connector for http.
<Connector port="80" protocol="HTTP/1.1"
           maxThreads="150"
           disableUploadTimeout="true"
           enableLookups="true" maxHttpHeaderSize="8192"
           maxSpareThreads="75" minSpareThreads="25" />

<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
           maxThreads="150" scheme="https" secure="true"
           keystoreFile="${user.home}/keystore/keystore.jks" keystorePass="test"
           truststoreFile="${user.home}/keystore/keystore.jks" truststorePass="test"
           truststoreType="JKS" disableUploadTimeout="true"
           enableLookups="true" maxHttpHeaderSize="8192"
           maxSpareThreads="75" minSpareThreads="25"
           clientAuth="true" sslProtocol="TLS" />

Comment: if I do clientAuth=true, in http configuration,will I receive client certificate in that case?


how to update data from input box to observable list

Question: I am designing a shopping cart.
The list of products (prodList) is shown to customer, when a user click on "Add" button, the respective product is shown in shopping cart list(orderList).
The Qty column for product added on orderList is a input box of type text.
I have one increment button (+) and decrement button(-), to update the Qty.
Now what I want is when user input a number directly into the input box, the same should get reflected.
I know I need to try with observable element, but I am unable to get it working, any suggestion, tips are also welcomed.
Below is the code
HTML For prodList

Rs

<button class="button" data-bind="click: $root.addToCartViaProdList">Add</button>

HTML for orderList

Rs

            -
            <input class="editQty"type="text" data-bind="value: ProductQty"/>
            +

KNOCKOUT CODE
function ProdList(ProductID, ProductName, ProductPrice, ProductCartDesc, ProductCategoryID, ProductQty)
{
    this.ProductID = ko.observable(ProductID);
    this.ProductName = ko.observable(ProductName);
    this.ProductPrice = ko.observable(ProductPrice);
    this.ProductCartDesc = ko.observable(ProductCartDesc);
    this.ProductCategoryID = ko.observable(ProductCategoryID);
    this.ProductQty = ko.observable(ProductQty);

}
function ProdListViewModel(prods)
{
    var self = this;
    self.prodList = ko.mapping.fromJS(data);

    self.orderList = ko.computed(function()
    {
        var orderedItems = [];
        /*Save data if browser is closed, still the data of cart will be retrievable*/
            if (self.remOrAdd() == "FINISH")
            {
                localStorage.removeItem("orderListDemo");
                return orderedItems;
            }

            if (localStorage.getItem("orderListDemo") != null)
            {
                var orderListSaved = [];
                var dataSaved = ko.utils.parseJson(localStorage.getItem("orderListDemo"));

                orderListSaved = ko.utils.arrayMap(dataSaved, function(item)
                {
                    return new ProdList(item.ProductID, item.ProductName, item.ProductPrice, item.ProductCartDesc, item.ProductCategoryID, item.ProductQty);
                });

                for(var ctrOrderListSaved = 0 ; ctrOrderListSaved < orderListSaved.length ; ctrOrderListSaved++)
                {
                    if (orderListSaved[ctrOrderListSaved].ProductQty() > 0)
                    {
                        orderedItems.push(orderListSaved[ctrOrderListSaved]);
                    }
                }
            }

            /*Checks whether to increment or decrement the QTY*/
            var ctrOrderedItems = 0;
            var trackIndex = 0;
            var index = -1;
            var loopTracker = 0;

            if(self.remOrAdd().length > 3)
                index = parseInt(self.remOrAdd().substring(3));

            if (self.remOrAdd().indexOf("ADD") > -1 && index > -1)
            {
                $(self.prodList()).each(function(i,e){

                    if (index > -1 && index == e.ProductID())
                    {
                        for(ctrOrderedItems = 0; ctrOrderedItems < orderedItems.length; ctrOrderedItems++)
                        {
                            if (e.ProductID() == orderedItems[ctrOrderedItems].ProductID())
                            {
                                orderedItems[ctrOrderedItems].ProductQty(orderedItems[ctrOrderedItems].ProductQty() + 1);
                                break;
                            }
                        }

                        if (ctrOrderedItems >= orderedItems.length)
                        {
                            orderedItems.push(e);
                            orderedItems[orderedItems.length-1].ProductQty(1);

                        }
                    }

                    loopTracker++;

                });
            }

            if (self.remOrAdd().indexOf("REM") > -1 && index > -1)
            {
                if (orderedItems.length > 0)
                    if (orderedItems[index].ProductQty() > 1)
                        orderedItems[index].ProductQty(orderedItems[index].ProductQty() - 1);
                    else
                        orderedItems.splice(index,1);

            }

        localStorage.removeItem("orderListDemo");

        self.viewOrderTab(0);
        if (orderedItems.length > 0)
        {
            localStorage.setItem("orderListDemo", ko.toJSON(orderedItems));
            self.viewOrderTab(1);

        }

        return orderedItems;
    },this);

    self.addToCartViaProdList = function (item, event)
    {
        /*get current item index*/
        /*in dom element $index() is enough but in viewModel a context is to be obtained*/

        var context = ko.contextFor(event.target);
        var index = context.$index();
        var incQty = self.prodList()[index].ProductQty();
        var prodID = self.prodList()[index].ProductID();
        incQty++;
        self.remOrAdd("");
        self.remOrAdd("ADD"+prodID);

    };

    self.addToCartViaOrderList = function (item, event)
    {

        var context = ko.contextFor(event.target);
        var index = context.$index();

        //Assumption this button can only be clicked only when the saved data storage is available.
        var orderListSaved = [];
        var dataSaved = ko.utils.parseJson(localStorage.getItem("orderListDemo"));

        orderListSaved = ko.utils.arrayMap(dataSaved, function(item)
        {
            return new ProdList(item.ProductID, item.ProductName, item.ProductPrice, item.ProductCartDesc, item.ProductCategoryID, item.ProductQty);
        });

        var prodID = orderListSaved[index].ProductID();

        self.remOrAdd("");
        self.remOrAdd("ADD"+prodID);
    };

    self.removeFromList = function(item, event)
    {
        var context = ko.contextFor(event.target);
        var index = context.$index();

        self.remOrAdd("");
        self.remOrAdd("REM"+index);

    };
}

var prodListViewModel = new ProdListViewModel();
ko.applyBindings(prodListViewModel);

Answer: It should work, check the snippet below, whatever value you enter into text box, it will increment from there only. There might be an issue with parsing in your code.
And try to give a simple code next time which can be understood and run easily.
Also your code is complex, try to break it into different module, do not add this much code in one single file.

   function AppViewModel() {

     this.ProductQty = ko.observable(0);

     this.removeFromList = function() {
       var currentVal = parseInt(this.ProductQty());
       if (currentVal >= 1) {
         this.ProductQty(currentVal - 1);
       }
     };

     this.addToCartViaOrderList = function() {
       var currentVal = parseInt(this.ProductQty());
       if (isNaN(currentVal)) {
         currentVal = 0;
       }
       this.ProductQty(currentVal + 1);
     };
   }

    // Activates knockout.js
   ko.applyBindings(new AppViewModel());
.qty {
  font-size: 38px;
}
a {
  text-decoration: none;
}

    -

  <input type="text" data-bind="value: ProductQty" />

    +

Comment: Thanks for your answer @Parshii. I tried your approach and it works. The complexity here arises because of two reason: 1. I need to preserve the data selected. 2. If user moves on to different category then prodList will have data as per that category. Any previous data will be erased. Hence to have above feature the code gets complex.
Comment: No Problem, may you make the best app for your business, also feel free to mark it as an answer. @DashmeetSingh


Why does invoking a module with -m option set sys.path[0] to empty string?

Question: I have a python script foo.py in my current directory C:\test.
Here is the code.
import sys
print('sys.path:', sys.path)
print('sys.argv:', sys.argv)

When I execute it as a script, I see this output.
C:\test>python foo.py
sys.path: ['C:\\test', 'C:\\Windows\\system32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages']
sys.argv: ['foo.py']

But when I execute it as a module, I see this output.
C:\test>python -m foo
sys.path: ['', 'C:\\Windows\\system32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages']
sys.argv: ['C:\\test\\foo.py']

Why does sys.path[0] become empty string when I execute my program as a module?
The documentation at http://docs.python.org/3.4/library/sys.html#sys.path mentions this:

As initialized upon program startup, the first item of this list,
  path[0], is the directory containing the script that was used to
  invoke the Python interpreter. If the script directory is not
  available (e.g. if the interpreter is invoked interactively or if the
  script is read from standard input), path[0] is the empty string,
  which directs Python to search modules in the current directory first.

So if the script directory is not available, only then it is supposed to set sys.path[0] to ''. But in my case, even while executing python -m foo, the script directory foo is clearly available. So it should not set sys.path[0] to '' as per the documentation. Instead, it should set it to 'C:\\test'.
Is it a bug in the documentation or a bug in the Python interpreter or a bug in my understanding?
Comment: Where do you see the empty string? In both cases `sys.path` has a *non empty* first element. The difference is whether or not it contains the full or relative path.
Comment: @Bakuriu Where do you see a non empty first element? You don't see an empty string in this output: `sys.path: ['', 'C:\\Windows\\system32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages']`?
Comment: Touchè. When reading the output I misread `sys.argv` for `sys.path`.
Answer: Look at what man python says about -m:

-m module-name

Searches sys.path for the named module and runs the corresponding .py file as a script.

If you think about it, it makes no sense to add the directory containing the .py file to be run into sys.path, as it already has to be there to be found in the first place. So, IMO, the behavior is correct.
But the documentation says that if it is run as a script, the directory containing it should be prepended to sys.path. I would say that it is an error in the documentation, it should say:

[...] (e.g. if the interpreter is invoked interactively or if the script is read from standard input or if the script is run using the -m option) [...]
Comment: What does it mean man and how do I install it to the start menu?
Comment: @Cuadue: `man` is the standard Unix command to read the manual pages. You just go to a terminal and run the command `man `. If you don't know it, probably you are running a non Unix-like system, such as Windows, where you don't have an easy alternative. For Python at least you have the integrated help files. For everything else... you have the Internet! To get a feel of what it is like, visit the [Linux man pages](https://www.kernel.org/doc/man-pages/).
Comment: if you think the docs should be improved; you could [submit documentation patch](http://docs.python.org/devguide/docquality.html)


Consulta MySQL utilizando JOIN

Question: Olá! Tenho o seguinte banco de dados:

Gostaria de fazer uma consulta onde eu consiga pesquisar por exemplo o professor x que está relacionado ao aluno y e z mas não o aluno w. Porém ao executar minhas consultas ele exibe o professor x relacionado tbm ao aluno w msm não constando a relação na tabela aluno_has_professor.
SELECT nomealuno, nomeprofessor FROM  aluno, professor as A
INNER JOIN aluno_has_professor as B ON (B.professor_idprofessor = A.idprofessor)
WHERE idprofessor = 2;

Por gentileza alguém poderia me ajudar com isso?
Comment: Um aluno só pode ter um professor ou pode vários?
Comment: Seu sql está selecionando tudo de aluno, vc tem que adicionar um join entre aluno e aluno_has_professor
Answer: O seu erro se encontra nesse trecho:
FROM  aluno, professor as A
INNER JOIN aluno_has_professor as B ON (B.professor_idprofessor = A.idprofessor)

Acabou misturando duas formas de fazer select, utilizando INNER JOIN ou não.
Você realizar select de duas formas:
SELECT * FROM professor AS A
INNER JOIN aluno_has_professor as B ON
(B.professor_idprofessor = A.idprofessor)

Ou
SELECT * FROM professor AS A, aluno_has_professor as B
WHERE B.professor_idprofessor = A.idprofessor

Sempre que utilizar mais que uma tabela você deve fazer o relacionamento entre elas e a diferença neste dois select's é que usando o INNER JOIN o relacionamento é feito após o ON e NÃO UTILIZANDO o INNER JOIN o relacionamento é feito após o WHERE.
No seu código você acabou misturando os dois jeitos ao montar seu select e ao colocar FROM aluno, professor e não colocar nenhum relacionamento entre as duas tabelas, você acaba trazendo tudo das duas tabelas. Por isso você trás o aluno W mesmo não sendo do professor com id = 2.
Você tem que interpretar da seguinte maneira, você tem uma tabela de alunos, uma tabela de professor e uma tabela de ligação entre as duas, o seu select deve ser feito da tabela aluno e da tabela professor para a tabela de ligação.
Select * from professor as A
INNER JOIN aluno_has_professor as B ON (B.professor_idprofessor = A.idprofessor)
INNER JOIN aluno as C ON (B.aluno_idaluno = C.idaluno)
WHERE idprofessor = 2;

Não sei se os campos da tabela aluno estão corretos, mas a lógica é essa ligar suas duas tabelas na tabela de ligação.
Com isto ao escolher o professor de ID = 2, a tabela de ligação irá identificar apenas os alunos que são do professor ID = 2 na tabela de alunos.
Answer: Tenta esta query:
SELECT
    p.nomeprofessor,a.nomealuno
from professor p
JOIN aluno_has_professor ap on p.idprofessor = ap.professor_idprofessor
JOIN aluno a on a.idaluno = ap.aluno_idaluno
WHERE
p.nomeprofessor='Walmir'

ou pelo id
SELECT
    p.nomeprofessor,a.nomealuno
from professor p
JOIN aluno_has_professor ap on p.idprofessor = ap.professor_idprofessor
JOIN aluno a on a.idaluno = ap.aluno_idaluno
WHERE
p.idprofessor ='2'

Comment: funcionou! muito obrigado!
Comment: ^^ fico feliz em ajudar espero que tenha entendido o que eu fiz.

Consulta MySQL utilizando JOIN


Assign object[key] to a temp variable in a javascript "for...in" loop?

Question: I'm working on a JS to show different messages depending on the current url's hash.
Now, that's all working, but I was wondering what the best way would be to access my messages (They'll be coded into a .js file)
At the moment, I have the messages stored in a object like this:
popups = {
    TemplateMessage: {
        title: "Template Popup Title",
        message: "This is a template popup message! Copy this to add a message.",
        modal: true
    },
    AnotherMessage: {
        title: "another title",
        message: "message.",
        modal: true
    } /* etc */
};

the way I'm accessing these messages is with a "for in:  loop, as follows:
for (key in popups) {
    //Do something with...
    popups[key].title;
    popups[key].message;
    popups[key].modal;
}

But would it be more efficient to assign popups[key] to a temporary variable?
Like:
var p;
for (key in popups) {
    p = popups[key];
    //Do something with...
    p.title;
    p.message;
    p.modal;
}

This is all relatively small-scale at the moment and it wouldn't matter a lot (if anything at all) at this stage, but what if you have, say, 25 different objects with 50 properties on each of them?
I guess my real question would be, is there a (relatively) significant difference in obtaining a variable from a temp variable, or from a object in a object?
I'm not quite sure how to properly test this, any suggestions?
Comment: You can test things like this yourself easily at http://jsperf.com
Comment: Nice. Yeah it's a useful site. Just don't start using it all the time for micro-optimizations when you should probably focus on readability and maintainability of your code!
Comment: @JamesAllardice Done: http://jsperf.com/tempvarforin
Apparently, it is faster to assign a temporary variable, after all...

Gotta keep that in mind. Thanks!
Answer: It turns out it is indeed faster to assign your object[key] to a temporary variable in for-in loops with large objects, as seen in this jsPerf test. That way, you won't have to obtain object[key] for every property of the object.


An Example of KKT Problem

Question: I tried using KKT sufficient condition on the problem $$\min_{x\in X} \langle g, x \rangle + \sum_{i=1}^n x_i \ln x_i \text{ s.t. }  \sum_{i=i}^n x_i = 1,
 \text{ where } X:= \{x\in\mathbb{R}^n | x_i >0, \forall i=1,\ldots, n\}.$$
Upon solving:

Primal feasibility: $\sum x_i = 1$

Dual feasibility: $g + \sum (\ln x + 1) + u(\sum x-1)=0.$

Textbook's solution: $x=e^{-g_t}/\sum_{k=1}^n e^{-g_k}.$ Are there any better options?
Answer: With the KKT conditions I would always recommend writing things out variable by variable, it often makes things a lot clearer.
So by the Lagrangian part of the KKT conditions we have:
$$
g_{i} + \ln(x_{i}) + 1 + u = 0.
$$
Solving for $\ln(x_{i})$ it should be obvious that
$$
\ln(x_{i}) = -g_{i} - 1 - u.
$$
Hence we conclude that
$$
x_{i} = e^{-g_{i} - 1 - u}
$$
But remember from our primal feasibility condition we must have:
$$
\sum x_{k} = \sum e^{-g_{k} - (1+u)} = \frac{\sum e^{-g_{k}}}{e^{1+u}}  = 1.
$$
I am just using standard properties of the exponential here, nothing special. Thus we conclude that:
$$
e^{1+u} = \sum e^{-g_{k}}
$$
Plugging this back into our formula for $x_{i}$ we find that
$$
x_{i} = e^{-g_{i} - 1 - u} = \frac{e^{-g_{i}}}{e^{1+u}} = \frac{e^{-g_{i}}}{\sum e^{-g_{k}}}
$$
Of course, note that you actually have $n$ inequality constraints to consider when computing the Lagrangian as you are optimising over the simplex, but in this case it doesn't matter.
Comment: I forgot to find the gradient of the equality constraint; mistake.
Comment: Could you share your idea to [this](https://math.stackexchange.com/questions/4470777/how-to-convert-transform-linear-programming-problems)?

An Example of KKT Problem


Is there a theoretical explanation for a change of a major7 to minor7 of the same root in jazz?

Question: In jazz there are many chord substitutions with various names like tritone, but there's a particular chord movement which I have seen in many jazz standards where major7 is immediately followed by a minor7 of the same root. For instance in a popular jazz standard Misty there's a part where Abmaj7 is immediately followed by Abm7.
Is there a theoretical explanation to this type of change and when should it be applied?
Comment: Check out [this page](https://www.learnjazzstandards.com/blog/learning-jazz/jazz-theory/how-to-master-the-backdoor-jazz-chord-progression/). You've identified this major-to-minor movement within an extremely common chord progression sometimes called the "backdoor progression." It is all over the place in jazz (Misty, How Deep is the Ocean, My Romance, Stella by Starlight, Just Friends...). The major-to-minor comes in when you backcycle (add V's and ii's to the V's). For example, check out the movement around the circle of 4ths: `|| EbM | Cm | Fm | Bb7 || Bbm | Eb7 | AbM | Abm Db7 || EbM | ...`
Comment: There are a lot of good answers already, and if I were to write a full answer, it would be way too similar to Matt L.'s (who is spot-on, I think). I wanted to include a comment mostly to share the linked article and to provide some context for understanding your question and the answers below. My point about the circle of 4th's isn't an answer to your question--the answer (I think) is Matt L.'s explanation about borrowed chords. I just wanted to highlight the circle of 4th's as something to keep an eye on when looking at the existing answers and thinking about why the progression sounds good.
Comment: @jdjazz your response should be posted as an answer more than a comment. Kindly expand it and post it as an answer.
Comment: @jdjazz thanks for the explanation. As for which response is spot on, I will rather wait until I have heard other possible answers. For instance the comment and the link that you gave provided a much simpler and detailed explanations of the "Backdoor Progression" which is a concept that I wasn't even aware of and none of the answers given here had touched upon.
Comment: Those are good points. So, the reason I prefer Matt L.'s answer is that it explains why | AbMaj | Abmin | EbMaj | works *as well as* | AbMaj | Abmin Db7 | EbMaj |. I see his answer as being somewhat more general, whereas the backdoor progression is maybe a narrower idea. The article does a great job of explaining the resolution, but it focuses on the V7 up a whole step to I resolution (e.g., Db7-EbMaj), which is a little different from the major-to-minor movement you've identified in this question.
Answer: This happens very often in a major key with the IV chord, which is altered to the minor chord with the same root (iv), and then resolves to the tonic chord. This works so well because of the voice leading. E.g., in C major you would get F to Fm to C, where the note A (third of F) moves down to the Ab (third of Fm) resolving to G (fifth of C).
The iv chord in a major key is often called a borrowed chord, because it can be viewed as borrowed from the parallel minor key (i.e., the minor key with the same root). This borrowing is part of a broader concept called modal interchange.
In the song Misty, if played in Eb major, the Ab maj7 chord is the IV chord, and the resolution back to Eb maj7 is as described above, just that there's usually a Db7 (bVII) chord in between the Abm7 and the tonic chord. That Db7 has the same function as the iv chord, because it is basically the same as an Abm6 chord, just with a different root.
Comment: Yes, the ⅳ chord has also been discussed in numerous other questions on the site. IMO it acts not so much as a burrowed chord from the parallel minor, but as a neat way of bringing in some tension in form of notes from the strongly dominant ⅶ⁰ chord, without the dissonance of an actual diminished chord.
Comment: This answer is by far the best explanation. Using chords from the parallel minor key is a very common and effective device. It occurs in many other ways, not just on a IV chord, for example on the tonic in several Jobim tunes like Wave and Triste. Other widely used parallel minor chords are the bIII and the bVI. Also I don't see any correlation between a IVm7 and a VIIo chord.
Answer: This is not a chord substitution but could be a cadence or a key change.  As mentioned in other answers a very common device (found in other forms of music not just Jazz) is
IV --> iv --> I (example in the key of C, F --> F min --> C)
The Maj 3rd of the IV chord is the 6th degree of the Key and the movement is chromatic walking down to the 5th degree of the key, the 5th of the I chord.
This is an alternate resolution to the classic IV --> V7 --> I.
If one is changing key down a whole step then this could be a set up for a ii-V-I in the new key.  Changing from C to Bb one might have C --> C min7 --> F7 --> Bb.
Moving away from your example for a moment it is quite common to replace any chord in the circle progression with its dom 7th to move to the next chord in the progression (with the exception of the IV as that moves to the viii).
C --> C7 --> F --> F# dim --> B-7(b5) --> B7 --> E-7 --> E7 --> A-7 --> A7 --> etc
This created the sound and feel of a resolution to the next chord in the sequence.
Comment: +1  I not only agree in principle, but I'd go as far as to say that this is exactly how the "trick" is used in the vast majority of the cases. Tune Up by Miles Davis is a classic example of just that.
Answer: This isn't something that theory 'commands' you to do, in the way that a dominant expects to resolve to a tonic.  It's not following some rule.  It's just a thing you CAN do, and not a particularly 'outside' one.  Same root, different flavour of chord.  A unifying factor and a variation.  Happens all the time in music.  Repetition, imitation, variation.
'Misty' is based on two types of stock progression.  There's the ii7 - V7 - I in bars 2-3 then again (aiming for a different temporary tonic but not actually getting there!) in bar 4.   Then there's the standard 'cycle of 5ths' turnaround in 5-6 and 7-8.
ii7 - V7 - I is a very strong progression.  You can jump to almost ANY m7 chord with the flimsiest of excuses and justify doing so by treating it as the beginning of such a progression.   Modifying an existing chord is a pretty conservative way of setting off for somewhere exotic.   'Giant Steps' uses a rather more contrived method!
In the case of 'Misty' I can't see much point in calling it anything more complicated than 'modifying a chord'.   Does 'Modal Interchange' tell you anything extra?

Here's another direction 'Misty' could have taken.  Still ii7 - V7 - I, which is what gives it integrity with what's before. (I've carried on and 'taken it back home' but I didn't have to.)   Not quite so obvious, which makes it... well what?  'Theory' can tell us it's a less obvious choice, but not that it's a worse one.  (Since when was 'obvious' better?)

(And I'm sure you've noticed that 'Misty' DOES take very much this route in the middle 8!)
Comment: Yes, "modal interchange" *does* tell us something extra, because it tells us a specific detail of this style. If someone were to come along and try to write something in the style of "Misty," modal interchange may get them there, and just "modifying a chord" likely won't. Imagine you sat down in a writing class and the instructor said "Eh, grammar is just theory. Just put whatever letters you like right next to each other...it's your artistic decision!" That's hardly an answer, don't you think?
Comment: I didn't downvote your answer but if I understand your argument correctly, then you're saying that the Abm7-Db7 combination might as well have been any other II-V progression. This is really not the case, and there's a good reason that it is Abm7-Db7, and not (for instance) Am7-D7.
Comment: @LaurencePayne Modal interchange is a very specific subset of modifying a chord. Which is why this clarity is important: just saying "modifying a chord" opens up possibilities far beyond the realm of mode mixture.
Comment: I didn't downvote, but there's a chance for an interesting discussion. "Does 'Modal Interchange' tell you anything extra?" Yes. When that Abm7 chord kicks in, to my ears, self-evidently the D note becomes Db automatically, even if the next chord wasn't a Db7.  "Modal interchange" is a more suitable word for describing the change of situation than just saying that one single chord was modified. I mean, nobody would try to solo a strong D natural on the Abm7 chord?
Comment: Well, like so many musical things it IS just an artistic decision! Theory can describe it, but theory doesn't command or predict it. It COULD have been Am7 - D7. A bit more 'outside', but quite possible. It would have led to a temporary tonic of G or Gm.   See my extended answer above.
Comment: @PhemeloKhetho: Of course a 2-5-1 is a very strong progression, nobody would doubt that. But here it is specifically about a 2-5 resolving to the tonic of the song. And apart from the actual 2-5 (Fm7-Bb7), the only other frequently occurring option is Abm7-Db7, for the reason explained in my answer.
Comment: @LaurencePayne: Yes I have, but this has no bearing on our answers, because nobody would doubt that you can use any II-V to go anywhere at any point in a song. The point is, which IIm7-V7 can be used to lead to the *tonic*? And there are only 2 reasonable choices. In the key of Eb major, Abm7-Db7 is one of them. And there's a good reason why it works, unlike Am7-D7 or most others.
Comment: Laurence, you acknowledged yourself that there's a difference when you wrote "it COULD have been Am7 - D7. *A bit more 'outside', but quite possible*." Why does one sound more outside? Theory can explain why Am-D7 sounds more outside than Abm-Db7--it can explain why Abm-Db7 leads to the tonic in a more natural sounding way. Those explanations are valuable for understanding the genre and creating/working within it. Theory offers the language for distinguishing between the differences you identify in how it sounds.
Comment: I didn't downvote you either. Wish you could beef up your answer and land it with a solid theoretical explanation. As it stands now, it sounds more like the Xmaj7 to Xm7 change is just an artistic license.
Comment: @Matt L. Have you noticed what harmonic route 'Misty' actually DOES take in the middle 8?
Comment: @LaurencePayne I have been noodling around, using my ear and trying this out; _"ii7 - V7 - I is a very strong progression. You can jump to almost ANY m7 chord"_; You are right! I didn't know it but it works outright
Comment: @Richard - isn't 'Modal interchange' just another way of saying 'modifying a chord'?
Comment: You can create a modal mixture even with single notes without playing any actual chords. Play notes from "outside" and the harmonic context changes.
Comment: You're still playing chords.  Just linear rather than vertical.
Comment: I upvoted appreciating the point about not forcibly imposing theoretical explanations everywhere. I also think that Tune Up would have made a much better example than Misty in this case.
Comment: @MMazzon the reason why I picked "Misty" over "Tune Up" is because it is more popular and it has been covered a lot by many artists. There are many other jazz standards that I could have used as examples of major to minor change using the same root.
Comment: @MattL., I agree 100% with everything you and many others have said. RE: ii-V's leading to the tonic, maybe there are 3 if we count Bm-E7-EbΔ.
Answer: One place I've seen this done a lot in jazz harmony is in a pair of descending ii-V progressions (often in the bridge). As an example, E♭m7 A♭7 D♭maj7 D♭m7 G♭7 C♭maj7. There's a lot of ways to explain why this 'works', but the key is that the shift is primarily created to get from the first key, D♭ major, to the second, C♭ major. You could also call the whole progression a variation on iii VI ii V I in C♭ major.
The color shift one gets from that parallel transformation is a nice sound, and just as good a reason to use this chord sequence as any other. So most of the time I see that chord movement of major to minor on the same root, it's either the minor plagal sound (IV iv I), or it's the ii V down two semitones thing I explained above.
Answer: I think one of the classic sources for the sound is the B section of Cherokee..

C#m7  F#7   BΔ7   BΔ7
Bm7   E7    AΔ7   AΔ7
Am7   D7    GΔ7   GΔ7
Gm7   C7    Cm7   F7

Each of the four bar lines is a basic ii V I pattern, but it is sequenced down a full step four times.
The transition between each sequence is where the major to minor change happens. Like: ...BΔ7 | Bm7...
On a structural level you could say that major to minor change is just a happy accident and the bigger picture idea is ii V I sequenced down by whole step. That's a theoretical explanation for the major to minor change in what is otherwise just a long progression by descending fifths from C# to F.
This song is supposed to be the one that Charlie Parker woodshedded on to develop his chops, so it seems like an important example to mention, and it happens this way in other songs.
Another common example is using a borrowed chord, a chord that comes from the parallel minor key. In I V IV iv | I the minor iv is "borrowed" from the parallel minor. In that case the theory is the borrowed chord maintains its function. So, both major IV and minor iv "function" as subdominants and the change of major to minor just adds chromatic color.
I put borrowed and function in quotes above, because some may prefer to explain the motion as a chromatic passing tone between the sixth and fifth scales degrees. I think that is a fine explanation too, and doesn't contradict the idea there is not a change of function.
Misty has this kind of "borrowed" progression, but it uses it in a specific way involving a bVII chord which has it's own special name: the backdoor progression: iv bVII I.
Compare the Misty borrowed chord explanation to the Cherokee sequential explanation. While the "function" of the two chords is the same in Misty in Cherokee the function changes. In Cherokee when getting to the BΔ7 the chord is a temporary tonic I in the pattern ii V I in C#m7 F#7 BΔ7, but then when it changes to Bm7 in the next sequence it becomes the supertonic chord ii of ii V I in Bm7 E7 AΔ7. In that case the two B chord not only change from major to minor but the function also changes.
If all this dithering about the use of "function" is a problem, you can look at it more plainly. In Misty when you look at the larger picture the opening section is an elaboration of movement between Eb and Bb (clearly I and V.) It starts on Eb and ends on Eb, that's the tonic. Regardless of the terminology used to describe the two major and minor Ab chords, one thing is clear: they aren't doing anything that changes the tonic of Eb. That's an "A" section establishing a tonic. The "B" section of Cherokee it totally different. It starts on C# and ends on F. It keeps moving and moving, transitioning back to Bb. It's a bridge returning to a tonic. Instead of talking about function we can describe them as two very different structural events.
Answer: The Abm7 chord is just doing the old jazz harmony trick, a temporary change between parallel minor and major tonalities. It can also be called a tonic shift of three semitones. Matt L. already gave an introduction to the subject of modal interchange, but to give a different perspective, I'll add a demonstration of what I feel the Abm7 chord is doing:

I think Laurence tries to say that if we take the question literally, the only "theoretical" explanation for why that was used must come from social sciences or psychology or something. Music theory can only describe the phenomena that happen in the harmonic context AFTER someone has decided to want to do that change. Why they did it - it was an artistic choice. They liked the feelings produced by the change, or at least they thought that prospective customers might like it. ;)


Calling function from other module does not work with module_load_include

Question: I'm building a custom module that uses functions from other modules. Specifically the node_clone module. I'm building a custom module to clone a certain content type from a selected user to another selected user.
In my custom module I'm adding those lines:
module_load_include('inc', 'node_clone', 'clone.pages');
clone_node_save($nid);

The function clone_node_save is defined in the module "node_clone", in the root folder of that module,
function clone_node_save($nid, $account = NULL) {
//Function Content
}

inside a file called clone.pages.inc
yet those 2 lines of code give me the error Fatal error: Call to undefined function clone_node_save()
I also tried making a function inside node_clone.module that calls clone_node_save but that gets the same error.
This is drupal 7
Comment: I just realized module_load_include is returning false
Comment: It is enabled. I can call functions from clone_node.module. And I can use the module in the backend.
But I cannot call functions from clone.pages.inc (which is an include in that module)
Answer: You don't include the file extension in the third argument.
So this:
module_load_include('inc', 'node_clone', 'clone.pages.inc');

Should be this:
module_load_include('inc', 'node_clone', 'clone.pages');

Comment: My bad, I tried that earlier and it gives the same result. And drupal_get_path('module', 'node_clone'); returns empty
Comment: Sounds like the node clone module is not enabled.
Comment: It is enabled. I can call functions from clone_node.module. And I can use the module in the backend. But I cannot call functions from clone.pages.inc (which is an include in that module)
Comment: Is there any way I can provide the full path to include this module? Its located in /sites/all/modules/contrib/node_clone
Answer: I was using the wrong name for the module. The .info file says project = "node_clone", which I assumed was the machine name of the module (its also the name of the folder). But the actual module is called clone.module, And I noticed this name in the System table when I was checking the path for the clone module.
Cheers!


NTP Server with no connection to the internet

Question: I have a small LAN that has no connection to the internet. It consists of two ubuntu servers clustered together providing NFS services to two IP cameras.
I need to synchronize the time on all the equipment. The Cameras support NTP so my plan was to run NTP on the server cluster.
Can I configure NTPD to just use the system time until this project gets funding to add a 3G/4G connection?
This is actually going to be harder than I thought. I'm running a heartbeat cluster with DRBD.  I'm going to need to have my primary server provide NTP to the two IP cameras and the other server in the cluster. If my primary server fails I need the secondary server to take over the NTP time server.
What do you guys suggest I do here??
Comment: http://www.ntp.org/ntpfaq/NTP-s-config.htm#S-CONFIG-BASIC-LAN
Answer: Your best-bet is to create a time cluster. A set of three (or more) systems, configured with peer associations. The cluster will negotiate a common consensus of time and should defend against clock-drift on all of them. It won't be truly accurate, for that you'll need a radio clock like you already know.
<code>peer 192.168.62.4
peer 192.168.62.12
</code>
Comment: Actually I'd say the *best* bet is to buy a cheap GPS and set up a proper NTP service using that as a reference.  This would be the second best (and cheaper) option :-)
Comment: I just found a section in my book that says I can reference the local hardware clock. I would add the line "server 127.127.1.1" in the ntp.conf file. I'll take what you said into consideration though!
Comment: @Matthew You'll need to do that to get reference clocks on each, but having three in a peer-group should help keep clock drift from getting *too* far out of true.
Comment: Due to the way that the NTP algorithm works, there is no guarantee that this will actually keep the time in sync.  Adding a GPS as voretaq7 suggested is really the only sensible choice.  I hear Opengear have some small, simple embedded devices that might work for this...
Comment: You may prefer to pick one clock and set that as a lower stratum than the others. Otherwise, each machine may just prefer its own clock and no actual synchronization will take place.
Comment: Voretaq I completely agree, but my boss is serious about this budget. Soon one of our IP cameras will have a GPS and I can use that camera as a NTP server. It's not very redundant but it will make them happy. anyway I'll make sure of that sysadmin1138!
Comment: I'm reading up on peering right now!
Comment: So here is my ntp.conf file on both servers http://pastebin.com/KKjf67UH... EMserver1 is the my primary. I'm rather exhausted so thanks everyone for the help!
Answer: If you're offline but want actual time, connecting any run-of-the-mill GPS receiver to your systems will keep time synched to within a second. You'll notice a relatively high jitter, but you'll keep regular time.
For some effort on your part, acquiring a GPS with a pulse-per-second feature will provide fantastic time keeping. In particular, the Garmin 18x LVC can be purchased for under $65. For the effort of giving it a 5 volt power supply and a serial port on the bare wires, you can have an accurate time keeping system for a very low impact on the budget.
There are plenty of tutorials on this subject if you search for "Garmin 18x NTP" or some other variation.
Comment: I know about the GPS but its not a option right now.
Answer: To add to all the above check out http://css-timemachines.com/ - they have a $299 minimum features NTP server. If you add that to the peering suggestion above you would have to spend a whole pile of money to get only a fraction better!


Looking for currency gem in rails

Question: I am looking for a rails gem to have a text_field that I can put a number and have a select where I can select a symbols of money ($, €...). If I change the select again that change the value of the text_field.
Anyone know a good gem for this.
Thanks!
Answer: See Font Awesome Icons gem. It's contains some symbols of money and many other helpful symbols
Answer: Check out the Money Gem. It has currency convertor built in, formatting, and lots of other great stuff to work with money.

Looking for currency gem in rails


How do you cache database queries with Google Cloud Run?

Question: I have a server on GCR and it pings a db when called. I was thinking of just adding a simple mechanism for cacheing like
<code>var lastDBUpdate int
var lastCache int
if lastDBUpdate > lastCache {
  lastCache = now
  return newResults
} else {
  return cachedResults
}
// endpoints that modify the db update the lastDBUpdate global var
</code>
This would work if there was only one container (i.e. while my backend has little load), but as my app grows and multiple containers are created, the lastDBUpdate and lastCache variables will be out of sync amongst the different containers. So how can I cache db reads with GCR?
Answer: You can use Memorystore.
Here is a guide how to connect to a Redis instance from Cloud Run.


JQuery mobile returned from background event

Question: good time
I am wondering if there is any jquery mobile event that's trigger if the user returned back to app and it's was in the background and still alive not terminated !!!
So the app in the background and swapped back again, I want to trigger some events at this case.
any thoughts?
Comment: what tool do you use to build your app? Or it is a web-app?
Answer: I found the answer and the correct event is "resume" below the code to run the event
<code>document.addEventListener("resume", function() {

                    // post your action or any trigger here

                });
</code>


JSON data deserialized incorrectly

Question: So I have a custom class:
public class CompanyInfo
{
    public int CompanyID { get; set; }
    public BasicInfo BasicInfo { get; set; }
    public EmployeesInfo EmployeesInfo { get; set; }
    ...
}

In my view, I want to send data back to my controller function:
 [HttpPost]
 public JsonResult SaveCompanyInfoWithOutBalanceSheet(CompanyInfo model)
 {
    ...
 }

The Ajax function is like this:
function onSubmit(){
    basicInfoFormData = $("#basicInfoForm").serialize();
    employeesInfoFormData = $("#employeesInfoForm").serialize();
    var companyInfoData =
    {
      basicInfoFormData, employeesInfoFormData
    };
    $.ajax({
            type: "POST",
            url: '@Url.Action("SaveCompanyInfoWithOutBalanceSheet")',
            dataType: "json",
            data: JSON.stringify(companyInfoData),
            success: function (result) {
                if (result.Success)
                    secondStepOnSubmit();
                else
                    submitError();
            }
        });
}

When I run the ajax function, my controller function do successfully receive the HTTP request and translate it to my custom class "CompanyInfo". However, there's one issue here. The last property cof my "BasicInfo" class is a string, the name of the property is "Website". If I set a breakpoint in the controller method, I can see that the binder doesn't deserialize the "Website" property correctly. Below is the value that Binder assigned to the "Website" property:
"test_email_address \",\"employeesInfoFormData\":\"EmployeesInfo.ID=0"

"test_email_address" is what I typed in for "WebSite" but somehow the binder includes the beginning of the "EmployeesInfo" part of the JSON string as well. Any ideas?
Comment: You need to set the specify `contentType: "application/json"` in your request object, jQuery x-form-url-encodes the body by default.
Comment: Did it worked as per the above comment "contentType: "application/json"" ?
Comment: @AluanHaddad Hey, I tried adding contentType:"application/json" but it didn't work, actually now the model is null in my controller function
Comment: Exactly, when you want your C# Method (EditAssetOnboarding) need parameter as a model then you should pass the whole model with data - not few attribute values of the model
Comment: @AluanHaddad I am confused here, so what should I do?
Answer: When you want your C# Action(SaveCompanyInfoWithOutBalanceSheet) need parameter as a model(CompanyInfo) then you should pass the whole model with data - not few attribute values of the model.
For Example, if your Model is having three properties like below
public class CompanyInfo
{
    public int CompanyID { get; set; }
    public BasicInfo BasicInfo { get; set; }
    public EmployeesInfo EmployeesInfo { get; set; }
}

And your Controller Action is like below
 [HttpPost]
 public JsonResult SaveCompanyInfoWithOutBalanceSheet(CompanyInfo companyInfo)
 {
    ...
 }

So, in javascript function you need to get the values where you have assigned to your html controls. Generate the correct structure of your model and pass it as parameter.
In your model, it holds one int attribute and two separate classes as two other attributes. So, when you are sending the parameter create the proper structure and pass it. It should work
function onSubmit(){
    var companyIdValue =  $("#yourcompanyidtextbox").val();
    //Ensure the basicInfoFormData contains all the property values of BasicInfo class
    var basicInfoFormData = $("#basicInfoForm").serialize();
    //Ensure the employeesInfoFormData contains all the property values of EmployeesInfo class
    var employeesInfoFormData = $("#employeesInfoForm").serialize();
    var companyInfo =
    {
      CompanyID : companyIdValue,
      BasicInfo : basicInfoFormData,
      EmployeesInfo : employeesInfoFormData
    };
    $.ajax({
            type: "POST",
            contentType: 'application/json; charset=utf-8',
            url: '@Url.Action("SaveCompanyInfoWithOutBalanceSheet")',
            data: JSON.stringify(companyInfo),
            success: function (result) {
                if (result.Success)
                    secondStepOnSubmit();
                else
                    submitError();
            },
            error: function (request, textStatus, errorThrown) {
               alert("Status: " + textStatus + "Error: " + errorThrown);
            }
        });
}

Hope you are clear.

JSON data deserialized incorrectly


How to edit and save Python file via command-line

Question: I have a Dockerfile that in one of its RUN instructions creates a conan file. I'd like to edit and save that conan file in my Dockerfile to set project specific settings. Is there a way to do so  via command line, for example the Python prompt?
Alternatively is there a way to embed a Python file in a Dockerfile?
Comment: What do you mean by `do so via command line`? And use `ADD` to add a python file to image is not what you needed?
Answer: I don't know any command to do so. But I would suggest you to use another approach :

Create a Conan template file with environment variables as placeholders (youconanfile.dist).
use envsubst command in order to runtime-create the file you need with current project variables.

I use this technique in a Docker stack to generate multiple files (wp-cli.yml, deploy.php...). My example is in a Makefile. If you need to use it in your Dockerfile, it is possible assuming that

envsubst is installed on your container
COPY command is used for pushing the Conan template file in your container.


Expressing a combination of sine and cosine as a single cosine

Question: Prove that:
$$\dfrac{\sqrt2}2 \cos \omega t - \dfrac{\sqrt2}2 \sin \omega t = \cos \left(\omega t + \dfrac\pi4\right)$$
Obviously, if we are evaluating the right side of the equation, it would a easier. It would only take the following steps:
$cos \left(\omega t + \dfrac\pi4\right) = \cos \omega t\cos\dfrac\pi4 - \sin \omega t\sin\dfrac\pi4 = \dfrac{\sqrt2}2 \cos \omega t - \dfrac{\sqrt2}2 \sin \omega t$
Thus, it was proven.
But when I was evaluating the left side of the equation, I was having a hard time. Any idea on how or what approach I should do?
Thanks a lot.
Comment: Why not do the exact same steps in reverse order?
Comment: @celtschk, but isn't it questionable if we just directly conclude that $\frac{\sqrt2}2$ is equal to $cos \frac\pi4$ ?
Comment: Why should it be questionable?
Comment: I maybe over-thinking everything. But think about this. What if we don't know that $\frac{\sqrt2}2 $ is $cos \frac\pi4$ ?
Comment: We prove it by drawing an isosceles right angled triangle (half a square) and computing the ratios directly??
Comment: If you don't know that equality, you cannot use it in *either* direction without proving it first.
Answer: Getting too long for a comment:
For proving an identity such as yours, $$A(t) = B(t)$$it is sufficient to show that

The left-hand side can be manipulated to equate with the right-hand side, $$A(t) = A^*(t) = A^{**}(t) = \cdots = B(t)$$
OR the right-hand side can be manipulated until it equates with the left-hand side: $$B(t) = B^{*}(t) = B^{**}(t) = \cdots = A(T)$$
Or each side of the proposed equality can be manipulated until each expression is equivalent: $$A(t) = A^*(t) = A^{**}(t) = B^{**}(t) = B^*(t) = B(t)$$

So your work is just fine to show that each side is indeed equivalent. You show equivalence by showing the right-hand side can be manipulated to equate with the left-hand side.
Indeed, as your steps show, you can simply apply them in "reverse order"...i.e., invert the process.
Answer: If you want to prove it as if you didn't know what it actually should be equal to, then here what people usually do. Assume, you have the expression $$a \cos x + b \sin x$$ and you want to find what it is equal to. The very first step is to notice the if you pull some factor outside of the brackets, so the whole expression becomes $$c (a_1 \cos x + b_1 \sin x)$$, so that $$a_1^2 + b_1^2 = 1$$ and $$0 \le |a_1|, |b_1| \le 1,$$ i.e. you can substitute $a_1 = \cos t$ and $b_1 = \sin t$.
$$
a_1 = \frac ac; \qquad b_1 = \frac bc
$$
and now just use condition above
$$
\left ( \frac ac \right )^2 + \left (\frac bc \right )^2 = 1
$$
from which you can find that the factor is
$$
c = \sqrt{a^2 + b^2}
$$
and therefore
$$
a \cos x + b \sin x = \sqrt{a^2 + b^2} \left ( \frac a{\sqrt{a^2 + b^2}} \cos x + \frac b{\sqrt{a^2 + b^2}} \sin x\right ) = \\
= \sqrt{a^2 + b^2} \left ( \cos t \cos x + \sin t \sin x \right ) = \sqrt{a^2 + b^2} \cos (x - t)
$$
where
$$
\cos t = \frac a{\sqrt{a^2 + b^2}} \\
\sin t = \frac b{\sqrt{a^2 + b^2}}
$$
Now, just substitute your numbers.
$$
c = \sqrt{\frac 12 + \frac 12} = 1
$$
so no need to factor anything out, since coefficients already make unity. So, all you need to do is finding some angle that corresponds to those coefficients, namely
$$
\sin t = \frac {\sqrt 2}2 \\
\cos t = -\frac {\sqrt 2}2
$$
you can easily see, that $t = -\frac \pi 4$ is one of those angles. At the same time, you could've taken any angle of the form $-\frac \pi 4 + 2 \pi n$.
So, angle is found, then substitute it to the final answer
$$
\frac {\sqrt 2}2 \cos \omega t - \frac {\sqrt 2}2 \sin \omega t = \cos \left ( \omega t - \left (-\frac \pi 4 \right )\right ) = \cos \left ( \omega t + \frac \pi 4 \right )
$$
Answer: $$\dfrac{\sqrt2}2 \cos \omega t - \dfrac{\sqrt2}2 \sin \omega t =\frac1{\sqrt2}\left(\cos\omega t -\sin  \omega t \right)$$
Let $1=r\cos A, 1=r\sin A$ where $r\ge 0$
So that $$\cos\omega t -\sin  \omega t=r\cos A\cos\omega t -r\sin A\sin  \omega t=r\cos(\omega t+A)$$
Now, $(r\cos A)^2+(r\sin A)^2=1+1\implies r^2=2\implies r=\sqrt2$ as $r\ge0$
$\implies \cos A=\sin A=\frac1{\sqrt2}\implies A=2n\pi+\frac{\pi}4$ where $n$ is any integer
So, the principal value of $A$ will be $\frac{\pi}4$
Can you take it from here?
Answer: There is a more general statement:

PROP For any $x,y\in\Bbb R$, it holds that $$\tag 1\cos(x+y)=\cos x \cos y-\sin x\sin y$$

Then let $x=\omega t,y=\dfrac{\pi }4$ and note that $\cos y=\sin y=\dfrac{\sqrt 2}2$
To prove $(1)$, fix $y\in \Bbb R$ and consider the function $$f(x)=\cos(x+y)-\cos x \cos y+\sin x\sin y$$
Note that $f(0)=0$. Moreover, $$f'(x)= - \sin (x + y) + \sin x\cos y + \cos x\sin y$$
so $f'(0)=0$. Finally $$f''\left( x \right) =  - \cos (x + y) + \cos x\cos y - \sin x\sin y$$
so $f''+f=0$. But this means $$f'f''+ff'=0$$ $$(f')^2+f^2=\rm const$$
Since $f(0)=f'(0)=0$, we get $$(f')^2+f^2=0$$
But this is a sum of non-negative terms, which means $f$ vanishes identically. Since $y$ was arbitrary, we have proven the proposition.
Answer: Here is my answer to the question guys. This is when evaluating the left side of the equation.
We were given,
$$\dfrac{\sqrt2}2 \cos \omega t - \dfrac{\sqrt2}2 \sin \omega t = \cos \left(\omega t + \dfrac\pi4\right)$$
Then,
$$\dfrac{\sqrt2}2 (\cos \omega t - \sin \omega t) = \cos \left(\omega t + \dfrac\pi4\right)$$
Recall that the sum of the cosine and sine of the same angle is given by:
$$cos x \pm sin x = \sqrt2 sin (\dfrac\pi4 \pm x )$$
Thus,
$$\dfrac{\sqrt2}2(\sqrt2 sin (\dfrac\pi4 - wt )) = \cos \left(\omega t + \dfrac\pi4\right)$$
$$ sin (\dfrac\pi4 - wt ) = \cos \left(\omega t + \dfrac\pi4\right)$$
Recall that, $sin(A - B)$ can be alternatively represented as $cos (-A + b + \dfrac\pi2) $. Therefore,
$$cos (-\dfrac\pi4 + wt + \dfrac\pi2) = = \cos \left(\omega t + \dfrac\pi4\right)$$
$$\cos (\omega t + \dfrac\pi4)= \cos \left(\omega t + \dfrac\pi4\right)$$
QED
Comment: Try to replicate your solution with expression like $3\cos x + 2 \sin x$. What's it equal to?
Comment: I used that sum of same angle because the two have the same coefficients, w/c is $\frac{\sqrt2}2$. With expression like yours, i think a different approach should be used to solve it.
Comment: yes different, the one I posted as an answer.


Show that numbers on a blackboard cannot be less than 1.442

Question: The numbers $n+1,n+2,...,2n$ are written on a blackboard $(n ≥ 2)$, and the following procedure is repeated:
two numbers are selected ( $x$ and $y$ ) from the board, erased, and replaced with the numbers $x+y+\sqrt{x^2 +y^2}$ and $x+y-\sqrt{x^2 +y^2}$
. Prove that there will never be a number less than 1.442 written on the board.
I've managed to find out that 1.442 is approximately $1/\ln(2)$ and that
$1/(n+1) + 1/(n+2) + ... + 1/(2n) = 1 -1/2 + 1/3 -...-1/(2n) = \ln(2)$, which I feel should be really useful, but I have absolutely no idea how to utilize it.
Comment: Note:  your header does not reflect your meaning.  You meant to say that no number $\textit{less than} \,1.442$ will appear on the blackboard.
Answer: $$\frac1{x+y+\sqrt{x^2+y^2}}+\frac1{x+y-\sqrt{x^2+y^2}}=\frac1x+\frac1y $$
Thus it remains to show that your $\approx \ln 2$ can be turned into a $<\frac1{1.442}$.
Comment: ah so because of this, then the sum of 1 over the numbers on the board is a constant ln(2), and so if any of the numbers on the board is less than 1.442, it's less than 1/ln(2), so it can't happen. Is that right, or did I miss something?


Cisco Nexus 5000 Vs. UCS 6100

Question: I'm a bit lost when I take a look to Nexus 5000 and UCS 6100.
The description of Nexus 5000 is quite clear and I see what it does but the description of the UCS 6100 is a bit unclear for me.
Could someone told me what would be the difference between a Nexus 5000 with all port at 10G and an UCS 6100 with all port at 10G ?
Thanks,
Answer: The UCS6100 is a component of the UCS architecture and while it provides network fabrics connectivity for discrete devices (your servers, other network gear, etc) its reason for existing is to provide unified (10G, DCB, FCoE) network fabric functionality and management for the Cisco UCS Blade chassis. I'm not familiar with either so I'm sure there are many specific feature differences given the huge array of configurations and features these devices provide - one that I'm aware of at the moment is that the UCS 6100 does not currently support Fiber Channel Switching completely (it supports NPIV only at the moment) for external connectivity (Northbound in UCS terms) - while the Nexus 5000 does (as explained in this blog post by Scott Lowe from EMC). In simple terms this means you cannot use a UCS 6100 as the sole Switch for a Fiber Channel Fabric. At the moment at least, that particular issue could change but the fundamental difference between a UCS part and a Nexus part won't, the former is a component for a unified platform and the latter is [or can be] a stand alone device.

Cisco Nexus 5000 Vs. UCS 6100


What else must I do to set up a new custom module?

Question: I am defining my first custom module and cannot get Drupal to see it.
What I have done:

Created a subdirectory with module name at sites/all/modules/custom/mymodulename. The name is just letters, nno spaces underscores or dashes.
Added two files mymodulename.info & mymodulename.module.
mymodulename.info contains: name = mymodulename and includes a description, package = Other, and core = 7.x.
ran update.php
flushed caches
reloaded admin/modules page
module is not listed???

I suspect that I somehow let Drupal know this is my first attempt and it is just messing with me! How can I appease it?
Comment: OH DAMN! I went to my mymodulename.inf file to get the info for your request and noticed the missing"o" in "info".  I knew when I wrote this the answer would probably embarrass me. That you for your incredible assistance!  Leave a question and I'll check it off for you!
Comment: Can you post the content of your .info file?
Comment: np, have seen that mistake before=)
Answer: Check for spelling mistakes, because you seem to have everything you need for it to be listed.


Indepedent pairs of RAID 1 is superior to RAID 10

Question: I am rather new to databases. I was reading up on RAID Storage and it seems that the consensus is that RAID 10 is

RAID 10 is best is terms of performance and redundancy

However at the end article , the author went on to state

Independent pairs of RAID 1 is superior to RAID 10 provided application knows how to evenly distribute data across multiple volumes

The author:George Ou did an analysis  to proof why independent pairs of RAID 1 is superior to RAID 10 though i cant really understand as i am quite new to databases
However another author : Robin  did his own analysis and rebuts George Ou analysis.
I am confused over all these analysis which is totally out of my depth.
These are my questions

Is it really true that Independent pairs of RAID 1 is superior to RAID 10 provided application knows how to evenly distribute data across multiple volumes
In practice, it is easy to create an application that is able to even distribute data across multiple volumes and how is it done ??
Can someone provide a simplified explanation regarding the above 2 points??
Comment: @ewwhite This question is not about RAID levels. It is as about a "RAID" vs an "Application" using multiple drives itself. I did not find an answer in http://serverfault.com/questions/339128/what-are-the-different-widely-used-raid-levels-and-when-should-i-consider-them and wonder why this question is marked as "duplicate".
Comment: I vote to reopen. This is not a "explain me raid levels" question - this is more detailed and specific. It should be allowed to stand.
Answer:
yes, because the failure of a Raid pair only means part of the data is gone. In a Raid 10, a raid pair failure means that all the data is unreadable. That said, access to the data is also slower.
not necessarily. Basically you must do that in the application and it depends on the application how complex it is - which is a programming, not an admin question. It may be easy or hard - it totally depends on the application. In many cases loss of a part of the data means stopping everything anyway and reloading a backup.
How much easier than that? (which I consider as easy as it gets for an admin - if you are not on that level, the question should be re-asked on superuser.com).
Comment: THe other problem is load distribution. If you have a Raid 10, then the whole IO budget is available regardless how the data and requests are distributed. Split them and you may end up with a lot of the requests hitting the same Raid 1 - slowing them down.
Comment: +1 Great answer... I'd add to #2 that programming intelligent distribution of data is incredibly hard *usually*. There might be applications where that's easy, but for most database applications that's you're going to be pandering to particular use cases rather than the general case, if you're lucky.
Comment: Yes. If you store images for example (social site, for example) then you can just have numbered "buckets" and store the bucket no. in the db - and a bucket goes to a file system. But that is a very special case.
Comment: Used to work with some "makes lots of drives and use tablespaces a lot" dbas. Put all my stuff on one big RAID-10 under linux/pgsql and stomped their oracle db server (similar hardware) right into the ground.
Answer: An application distributing data over drives can always be superior to RAID simply because It has more info for optimization decisions. MS SQL is a good example since It shows better performance on bare drives vs. running on its combination as RAID0 (concerning your case RAID10 is RAID0 combination of RAID1).
But practically It is not so obvious:
First, George Ou explored motherboard integrated raid. With dedicated power RAID card his results may be different considerably.
Second, with RAID10 you can use ALL your disks. If you make disks to be managed by an application then you need to leave something for system. Say, in 8-drive server you may need to choose between 8-drive RAID10 and RAID1 for susyetm plus 3*RAID1 for an application. And in this case RAID10 may produce better results.
And third, with RAID10 one has flexibility that is often preferable then a little gain of performance. Volume management, space reallocations, snapshotting, block-level replication an other cool features are points to sacrifice then an application manages drives itself.


Visual Studio publish to custom Docker container fails due to non-existent Dockerfile directory

Question: I'm following Scott Hanselman's article Brainstorming development workflows with Docker, Kitematic, VirtualBox, Azure, ASP.NET, and Visual Studio and failing during the publish process.
To set the stage, I've got Docker Toolbox (as of 2/11/16), Visual Studio 2015, Visual Studio 2015 Tools for Docker (as of 2/11/16) and ASP.NET RC 1.
My publish dialog looks as follows (I present this not to show specific settings but rather to show where I am in the process):

Error: An error occured during publish.
The command [docker --tlsverify
  --tlscacert="C:\Users\bla\.docker\machine\certs\ca.pem" --tlscert="C:\Users\bla\.docker\machine\certs\cert.pem" --tlskey="C:\Users\bla\.docker\machine\certs\key.pem" -H tcp://192.168.99.100:2376 build -t devwkflowtest -f
  "C:\Users\bla\AppData\Local\Temp\PublishTemp\zapp29\approot\src\zapp\Properties\PublishProfiles\v"
  "C:\Users\bla\AppData\Local\Temp\PublishTemp\zapp29"] exited with code
  1: unable to process Dockerfile: read
  C:\Users\bla\AppData\Local\Temp\PublishTemp\zapp29\approot\src\zapp\Properties\PublishProfiles\v:
  The handle is invalid.

The Dockerfile can't be found (and hence the invalid handle error) because the \v directory shown in the path does not exist.
Manually creating it was not helpful because that part of the publish path is deleted and recreated during the publish operation.
Answer: Poking around I found that my publish profile:

had the value v for <DockerfileRelativePath>:

Some Googling lead me to https://github.com/Lybecker/ContainerWorkshop/tree/master/Exercise06 which had <DockerfileRelativePath>..\..\Dockerfile</DockerfileRelativePath>.
I changed v to ..\..\Dockerfile and the publish completed successfully.
I don't understand how the v was generated and I also don't understand why it shouldn't have worked regardless; I'd expect v to refer to \.v and work.


Drush won't work after installing drupal 8 on remote server using composer

Question: After installing drupal 8 on a remote server (I have SSH access) using composer I installed drush using the following command: 'composer require drush/drush'. After I type vendor/bin/drush I get the following error:

[preflight] The following restricted PHP modes have non-empty values:
  {disable_functions}. This configuration is incompatible with drush.
  {Please check your configuration settings in /usr/local/lib/php.ini or
  in your drush.ini file; see examples/example.drush.ini for details.}

My drush version is 9.6. How do I make it work?
Comment: The error message tells you what todo...
Comment: I'm new to linux, therefore I seeked help. Error message tells me to check my configuration settings for compatibility with drush - I don't know what needs to be done to make them compatible (empty some values, what values?). And there is no example.drush.ini file in my vendor/drush/drush/examples folder.
Answer: It turns out that making it work wasn't at all easy, so I'll try to post an answer to my own question in the hope that it helps some other newbies, who do not have a lot of experience in working with remote linux servers, but want to use drush 9.x with their Drupal 8 installation:

First of all, after finding a similar problem in https://www.drupal.org/forum/support/post-installation/2015-08-02/solved-installed-drush-not-working-warning-popen-disabled (this quite long collection of posts is, I believe, worth reading) I found out that you have to give Drush its own php.ini file with looser security. One way to do it is described in here: http://www.6by9.net/drush-on-an-hosting-fix-using-custom-php-ini/
Sadly, the above doesn't work for drush 9.x, so after another search I chanced upon the following https://github.com/drush-ops/drush/issues/3294#issuecomment-370201342 In this comment Moshe Weitzman writes that you have to

insure that the PHPRC environment variable is set to the directory containing the desired php.ini

So after another search I managed to find out how to do it using the following command:

export PHPRC=/your/path

and in my particular case it looked like this:

export PHPRC=~/.drush

I don't know if it is the 'right' way to do it, but it works :-)


Listing City required in osclass

Question: I the osclass When I post listing, choosing a city is not required. How can I make it required ?
When I select city, it shows in the post, but I also can post listing without selection the city, but I want the city to be required.
Comment: Do you have any code you can show? It's usually as simple as adding a `requried` attribute to the `` http://www.w3schools.com/tags/att_input_required.asp
Answer: You have two ways to do it:
1- Hook method
Using the pre_item_post (osclass < 3.3) or pre_item_add (osclass >=3.4).
<code>osc_add_hook("pre_item_add", function($aItem) {
    if($aItem["city"] !== "") {
        osc_add_flash_error_message(_e("Please select a city", "your_theme"));
        $this->redirectTo(osc_item_post_url());
    }
});
</code>
2- Javascript method
Using jQuery Validate, like in Bender theme.
<code>$('.form-horizontal').validate({
    rules: {
        region: {
            required: true
        },
        city: {
            required: true
        }
    },
    messages: {
        region: {
            required: "Please select a region"
        },
        city: {
            required: "Please select a city"
        }
    }
});
</code>

Listing City required in osclass


ASP.NET 4x and ASP.net Core on the same machine

Question: My question is very simple, but I will ask it at the risk of sounding like an idiot.
I have a Windows 2008 R2 server called "machine" running several production web applications (asp WebForm) on an IIS ASP.net 4.X server.
Now, I would like to develop MVC web applications (targeting .NET Core platform) using the MVC with the tag helpers available only with ASP CORE.
Is it possible to install ASP Core on the  server "machine" while maintaining the existing applications and then deploy new ASP Core web application (with visual studio 2019) ? The objective is to run production application WebForm (.Net Framework) and MVC application (ASP Core) on the same machine.
Thank you for your attention!
Comment: You may have to do additional work - please see [Install .NET Core on Windows](https://learn.microsoft.com/en-us/dotnet/core/install/windows?tabs=netcore31#dependencies) for some dependencies. I assume you know that on January 14, 2020, support for Windows Server 2008 and 2008 R2 ended.
Answer: Yes Just download supported installer from here.
Now you can easily host asp.net 4.X & .net core application in same IIS without any issue.


When are two measures equivalent?

Question: Given to measures $\mu$ and $\nu$, with the relation $d\nu = f d \mu$, $f$ measurable and non-negative, then we know that $\nu << \mu$ (the Radon Nikodym theorem proves that the converse also holds).
Under what condition on $f$  is $\mu << \nu$, i.e. the two measures are equivalent?
Answer: They are equivalent iff $f > 0$ $\mu$-a.e.
This is immediate from the standard fact that for $f \ge 0$ and any measurable set $A$, we have $\int_A f\,d\mu = 0$ if and only if $f = 0$ $\mu$-a.e. on $A$.

When are two measures equivalent?