问:
Iteratively examine the values in a variable in a dataframe, and return the values of an adjacent variable in R
I am trying to create a new variable (Nprice) in a dataframe in R. The values in Nprice depend on the values in a list of other vectors in the dataframe.

Here is my sample data

```<code>dataframe <- data.frame(
Comp = abs(rnorm(35)),
priceMar16 = rnorm(35),priceApr16 = rnorm(35), priceMay16 = rnorm
(35),priceJune16 = rnorm(35),priceJuly16 = rnorm(35),priceAug16 = rnorm(35),
cellchangeMar16 = rep(c("SP", "2xSP", "SP: SP", NA, NA), 7),
cellchangeApr16 = rep(c(NA, NA, "SP", "2xSP", "SP: SP"), 7),
cellchangeMay16 = rep(c("SP", NA, NA, "2xSP", "SP: SP"),7),
cellchangeJune16 = rep(c("SP: SP", NA, "SP", "2xSP", NA),7),
cellchangeJuly16 = rep(c(NA, "SP", "2xSP", "SP: SP", NA), 7),
cellchangeAug16 = rep(c("SP: SP", "SP", "2xSP", NA, NA), 7))
</code>```

For each component ("Comp") I want to look up the value for cellchangeAug16, if it is NA, then I want to return the value of priceAug16 to the vector Nprice. If cellchangeAug16 is not NA, then I want to examine cellchangeJul16. If cellchangeJul16 is NA, then I want NPrice to be the value for priceJul16, if cellchangeJuly is not NA, then I want to go to cellchangeJun16; and iteratively down the list of columns for cellchange.

If there are no NA values for any of the cellchange variables for that component, then I want NPrice to be "No NP".

This is what I have tried

```<code>my_seq <- seq_along(dataframe)
my_seq <- my_seq[-1]

dataframe$Nprice <- for (i in my_seq) { test[i] <- ifelse
((grepl("Cell",names(dataframe[i]),ignore.case=T))==F,next,
ifelse(grepl("SP",dataframe[i]),dataframe[i-1],"")) }
dataframe$Nprice <- if (dataframe$Nprice == ""){"No SP"}
</code>```

This returns the error message "13: In [<-.data.frame(tmp`, i, value = list(c(2016.03,  ... : replacement element 1 has 9238 rows to replace 9237 rows"

Can anyone tell me what I'm doing wrong?

答:
I figured this out. So if anyone is interested, here is how it can be done:

Create two subsets of the dataframe, which contain only the variables of interest

```<code>CellChange <- dataframe[,c(grep("Cell",colnames(dataframe),ignore.case = T))]
Prices <- dataframe[,c(grep("price",colnames(dataframe),ignore.case = T),
                               grep("Comp",colnames(dataframe),ignore.case = T))]
</code>```

Find the location (new vector called 'Location') of the instances where the cell change value does not contain SP

```<code>Location <- vector()
for (i in 1:nrow(CellChange)) { temp <- CellChange[i,]
tempgrep <- min(grep("SP", temp, invert = T, ignore.case = T))
if (tempgrep == Inf) {Location[i] <- ""}
else Location[i] <- tempgrep }
</code>```

For each of the locations in the Location vector, return the corresponding value in the Prices data

```<code>for (i in 1:length(Location)) {
if (Location[i] == "") {Prices$FinalValue[i] <- "No NP for last 12 months"}
else { Prices$FinalValue[i] <- Prices[i, as.numeric(Location[i])] }
}
</code>```

Extract the information from the previous step into a dataframe

```<code>Finalvalue <- data.frame(Prices$FinalValue, Prices$Comp)
</code>```

Merge this back into the original data

```<code>colnames(Finalvalue) <- c("FinalValue", "Comp")
dataframe <- merge(dataframe, Finalvalue, by.x = "Comp", all = T)
</code>```

Body:
I am trying to create a new variable (Nprice) in a dataframe in R. The values in Nprice depend on the values in a list of other vectors in the dataframe.

Here is my sample data

dataframe <- data.frame(
Comp = abs(rnorm(35)),
priceMar16 = rnorm(35),priceApr16 = rnorm(35), priceMay16 = rnorm
(35),priceJune16 = rnorm(35),priceJuly16 = rnorm(35),priceAug16 = rnorm(35),
cellchangeMar16 = rep(c("SP", "2xSP", "SP: SP", NA, NA), 7),
cellchangeApr16 = rep(c(NA, NA, "SP", "2xSP", "SP: SP"), 7),
cellchangeMay16 = rep(c("SP", NA, NA, "2xSP", "SP: SP"),7),
cellchangeJune16 = rep(c("SP: SP", NA, "SP", "2xSP", NA),7),
cellchangeJuly16 = rep(c(NA, "SP", "2xSP", "SP: SP", NA), 7),
cellchangeAug16 = rep(c("SP: SP", "SP", "2xSP", NA, NA), 7))

For each component ("Comp") I want to look up the value for cellchangeAug16, if it is NA, then I want to return the value of priceAug16 to the vector Nprice. If cellchangeAug16 is not NA, then I want to examine cellchangeJul16. If cellchangeJul16 is NA, then I want NPrice to be the value for priceJul16, if cellchangeJuly is not NA, then I want to go to cellchangeJun16; and iteratively down the list of columns for cellchange.

If there are no NA values for any of the cellchange variables for that component, then I want NPrice to be "No NP".

This is what I have tried

my_seq <- seq_along(dataframe)
my_seq <- my_seq[-1]

dataframe$Nprice <- for (i in my_seq) { test[i] <- ifelse
((grepl("Cell",names(dataframe[i]),ignore.case=T))==F,next,
ifelse(grepl("SP",dataframe[i]),dataframe[i-1],"")) }
dataframe$Nprice <- if (dataframe$Nprice == ""){"No SP"}

This returns the error message "13: In [<-.data.frame(tmp`, i, value = list(c(2016.03,  ... : replacement element 1 has 9238 rows to replace 9237 rows"

Can anyone tell me what I'm doing wrong?

Body:
I figured this out. So if anyone is interested, here is how it can be done:

Create two subsets of the dataframe, which contain only the variables of interest

CellChange <- dataframe[,c(grep("Cell",colnames(dataframe),ignore.case = T))]
Prices <- dataframe[,c(grep("price",colnames(dataframe),ignore.case = T),
                               grep("Comp",colnames(dataframe),ignore.case = T))]

Find the location (new vector called 'Location') of the instances where the cell change value does not contain SP

Location <- vector()
for (i in 1:nrow(CellChange)) { temp <- CellChange[i,]
tempgrep <- min(grep("SP", temp, invert = T, ignore.case = T))
if (tempgrep == Inf) {Location[i] <- ""}
else Location[i] <- tempgrep }

For each of the locations in the Location vector, return the corresponding value in the Prices data

for (i in 1:length(Location)) {
if (Location[i] == "") {Prices$FinalValue[i] <- "No NP for last 12 months"}
else { Prices$FinalValue[i] <- Prices[i, as.numeric(Location[i])] }
}

Extract the information from the previous step into a dataframe

Finalvalue <- data.frame(Prices$FinalValue, Prices$Comp)

Merge this back into the original data

colnames(Finalvalue) <- c("FinalValue", "Comp")
dataframe <- merge(dataframe, Finalvalue, by.x = "Comp", all = T)


来源: stackexchange

问:
Summing up the elements in a linked list recursively in C++
Suppose I have a Sum method to help sum the elements in a linked list recursively,

```<code>void Sum(Node *head)
{
    int sum = 0;   //I think this is the problem since it resets the sum on each recursive call
    while (head != NULL) {
        Sum(head->next); //iterate to the last node before null
        sum += head->data;
        return;
    }

    cout << " The sum is : " << sum << endl;
}
</code>```

The issue I'm having is I think due to my sum value being reinitialized to 0 with each recursive back call; what is a way to allow me to maintain the value of the sum once all the recursion is complete?

答:
It can be a lot simpler than what you have. Changes I suggest:

Change the return value of the function so it returns the sum.

Use the returned value in the recursive call.

Don't use a while loop AND a recursive call. Use one or the other.

Recursive version:

```<code>int Sum(Node *head)
{
    if ( head != NULL )
        return head->data + Sum(head->next);
    else
        return 0;
}
</code>```

Looping version:

```<code>int Sum(Node *head)
{
   int sum = 0;
   while (head != NULL) {
     sum += head->data;
     head = head->next;
   }
   return sum;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Suppose I have a Sum method to help sum the elements in a linked list recursively,

void Sum(Node *head)
{
    int sum = 0;   //I think this is the problem since it resets the sum on each recursive call
    while (head != NULL) {
        Sum(head->next); //iterate to the last node before null
        sum += head->data;
        return;
    }

    cout << " The sum is : " << sum << endl;
}

The issue I'm having is I think due to my sum value being reinitialized to 0 with each recursive back call; what is a way to allow me to maintain the value of the sum once all the recursion is complete?

Body:
It can be a lot simpler than what you have. Changes I suggest:

Change the return value of the function so it returns the sum.

Use the returned value in the recursive call.

Don't use a while loop AND a recursive call. Use one or the other.

Recursive version:

int Sum(Node *head)
{
    if ( head != NULL )
        return head->data + Sum(head->next);
    else
        return 0;
}

Looping version:

int Sum(Node *head)
{
   int sum = 0;
   while (head != NULL) {
     sum += head->data;
     head = head->next;
   }
   return sum;
}


问:
Python 3: Find an element in a list inside a dictionary
```<code>houses={'apartment':15, 'penthouse':35, 'others':[20,5,70]}
</code>```

what I need is to check and then find 20 for example.

been trying for hours.

would be great if you could provide and explanation and multiple solutions.

thanks in advance.

答:
Your houses is a dictionary. It is missing a } though.  Its others key is a list, so you can access its first item like so: print (houses['others'][0]). If you need to iterate over the keys and values, there are several ways as demonstrated in this link:Iterating over dict values
. A basic version  is like this:

```<code>houses={'apartment':15, 'penthouse':35, 'others':[20,5,70]}
bool = False
for (k,v) in houses.items():
    if type(v)==list:
        if 20 in v:
            bool = True
            print(k,v)
    if v == 20:
        bool = true
        print(k,v)
print(bool)
</code>```

Body:
houses={'apartment':15, 'penthouse':35, 'others':[20,5,70]}

what I need is to check and then find 20 for example.

been trying for hours.

would be great if you could provide and explanation and multiple solutions.

thanks in advance.

Body:
Your houses is a dictionary. It is missing a } though.  Its others key is a list, so you can access its first item like so: print (houses['others'][0]). If you need to iterate over the keys and values, there are several ways as demonstrated in this link:Iterating over dict values
. A basic version  is like this:

houses={'apartment':15, 'penthouse':35, 'others':[20,5,70]}
bool = False
for (k,v) in houses.items():
    if type(v)==list:
        if 20 in v:
            bool = True
            print(k,v)
    if v == 20:
        bool = true
        print(k,v)
print(bool)


问:
Convert Java object to XML string
Yes, yes I know that lots of questions were asked about this topic. But I still cannot find the solution to my problem. I have a property annotated Java object. For example Customer, like in this example. And I want a String representation of it. Google reccomends using JAXB for such purposes. But in all examples created XML file is printed to file or console, like this:

```<code>File file = new File("C:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

jaxbMarshaller.marshal(customer, file);
jaxbMarshaller.marshal(customer, System.out);
</code>```

But I have to use this object and send over network in XML format. So I want to get a String which represents XML.

```<code>String xmlString = ...
sendOverNetwork(xmlString);
</code>```

How can I do this?

答:
A convenient option is to use javax.xml.bind.JAXB:

```<code>StringWriter sw = new StringWriter();
JAXB.marshal(customer, sw);
String xmlString = sw.toString();
</code>```

The [reverse] process (unmarshal) would be:

```<code>Customer customer = JAXB.unmarshal(new StringReader(xmlString), Customer.class);
</code>```

No need to deal with checked exceptions in this approach.

Title: Convert Java object to XML string

Body:
Yes, yes I know that lots of questions were asked about this topic. But I still cannot find the solution to my problem. I have a property annotated Java object. For example Customer, like in this example. And I want a String representation of it. Google reccomends using JAXB for such purposes. But in all examples created XML file is printed to file or console, like this:

File file = new File("C:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

jaxbMarshaller.marshal(customer, file);
jaxbMarshaller.marshal(customer, System.out);

But I have to use this object and send over network in XML format. So I want to get a String which represents XML.

String xmlString = ...
sendOverNetwork(xmlString);

How can I do this?

Body:
A convenient option is to use javax.xml.bind.JAXB:

StringWriter sw = new StringWriter();
JAXB.marshal(customer, sw);
String xmlString = sw.toString();

The [reverse] process (unmarshal) would be:

Customer customer = JAXB.unmarshal(new StringReader(xmlString), Customer.class);

No need to deal with checked exceptions in this approach.

ContentLicense: CC BY-SA 4.0


问:
For loop overwriting text in HTML
My array called myEmployees has 5 names in it, yet when I run the code it only prints out 3 of them. I believe this is happening because the for loop in the script is overwriting the previous line that it wrote in the HTML document. How can I fix this?

Yearly Bulletin Board Announcements!

Congratulations to Taylor, you have been here for 9 years and you meet the magic number! You get 2 extra weeks of PTO!

Derek, thank you for your service over the past 8 years. I look forward to many more years working with you!

Tyler, no longer works here.

The above  is what shows on my screen when I run the code, there should be two other statements to appear. Any suggestions would be greatly appreciated!

```<code><body>

  <h1>Yearly Buttetin Board Announcements!</h1>
  <h2 id='win'></h2>
  <h3 id='here'></h3>
  <h4 id='notHere'></h4>

  <script src='app.js'></script>
</body>
</code>```

TypeScript

```<code>for( i = 0; i < myEmployees.length; i++ ) {
    const employee = myEmployees[i];
    let magicNumber   = employee.extraVacay;
    let stillEmployed = employee.stillEmployed;
    let timeInJob     = employee.timeInJob;
    let name          = employee.name;

    if( magicNumber > 30 && timeInJob > 5 && stillEmployed == true ) {

        document.getElementById('win').innerHTML = (`Congratulations to ${name}, you have been here for ${timeInJob} years and you meet the magic number! You get 2 extra weeks of PTO!`);

    }
    else if (stillEmployed == true) {

        document.getElementById('here').innerHTML = (`${name}, thank you for your service over the past ${timeInJob} years. I look forward to many more years working with you!`);

    }
    else {

        document.getElementById('notHere').innerHTML = (`${name}, no longer works here.`)
    }
};
</code>```

答:
Use insertAdjacentHTML

```<code>document.getElementById('here').insertAdjacentHTML('beforeend', 'your html')
</code>```

It can have better performance than using innerHTML, especially when using beforeend.

Title: For loop overwriting text in HTML

Body:
My array called myEmployees has 5 names in it, yet when I run the code it only prints out 3 of them. I believe this is happening because the for loop in the script is overwriting the previous line that it wrote in the HTML document. How can I fix this?

Yearly Bulletin Board Announcements!

Congratulations to Taylor, you have been here for 9 years and you meet the magic number! You get 2 extra weeks of PTO!

Derek, thank you for your service over the past 8 years. I look forward to many more years working with you!

Tyler, no longer works here.

The above  is what shows on my screen when I run the code, there should be two other statements to appear. Any suggestions would be greatly appreciated!

Yearly Buttetin Board Announcements!

TypeScript

for( i = 0; i < myEmployees.length; i++ ) {
    const employee = myEmployees[i];
    let magicNumber   = employee.extraVacay;
    let stillEmployed = employee.stillEmployed;
    let timeInJob     = employee.timeInJob;
    let name          = employee.name;

    if( magicNumber > 30 && timeInJob > 5 && stillEmployed == true ) {

        document.getElementById('win').innerHTML = (`Congratulations to ${name}, you have been here for ${timeInJob} years and you meet the magic number! You get 2 extra weeks of PTO!`);

    }
    else if (stillEmployed == true) {

        document.getElementById('here').innerHTML = (`${name}, thank you for your service over the past ${timeInJob} years. I look forward to many more years working with you!`);

    }
    else {

        document.getElementById('notHere').innerHTML = (`${name}, no longer works here.`)
    }
};

Body:
Use insertAdjacentHTML

document.getElementById('here').insertAdjacentHTML('beforeend', 'your html')

It can have better performance than using innerHTML, especially when using beforeend.


问:
Removing all whitespace in Bootstrap panel containing select list
This has been bothering me for ever now. I've tried removing the padding from the bottom, setting the size of the select field to be the same height as the inner height of the panel, etc.

Here's my jsfiddle so you can just see what I'm talking about: jsfiddle

I'm just trying to have that select list span the whole height of the panel with no white space at the bottom.

I've tried playing around with JQuery as well, but no success. If I resize the select menu, everything just becomes larger and the whitespace remains. A javascript solution would be fine too.

Here is my html:

```<code><div class="panel panel-default" id="obs-list">
  <div class="panel-heading">
    <h3 class="panel-title">Observations</h3>
  </div>
  <div class="panel-body scroll-list" id="list-panel">
    <div class="form-group">
      <select class="form-control patient-list noglow" id="observation" name="observation" size="7">
        <option value="1">2017-03-23 04:40:36</option>
        <option value="2">2017-03-23 04:50:32</option>
        <option value="4">2017-03-28 04:18:55</option>
        <option value="5">2017-03-28 19:01:34</option>
        <option value="11">2017-03-28 22:06:25</option>
        <option value="12">2017-03-28 22:37:32</option>
        <option value="13">2017-03-28 23:10:19</option>
        <option value="14">2017-03-29 02:17:57</option>
      </select>
    </div>
  </div>
</div>
</code>```

And my css:

```<code>.patient-list {
    font-size: 20px;
    border: none;
}

.panel-body.scroll-list {
    padding: 0px 0px 0px 0px;
}
</code>```

And below is that ugly looking whitespace in my list:

答:
Try this:

```<code>.panel-body .form-group {
  margin-bottom:0px;
}
</code>```

updated link

Decription

If you change form-group class property it will effect in bootstrap, because form-group class use globally for forms.. so change its property by making it as a child div..

Body:
This has been bothering me for ever now. I've tried removing the padding from the bottom, setting the size of the select field to be the same height as the inner height of the panel, etc.

Here's my jsfiddle so you can just see what I'm talking about: jsfiddle

I'm just trying to have that select list span the whole height of the panel with no white space at the bottom.

I've tried playing around with JQuery as well, but no success. If I resize the select menu, everything just becomes larger and the whitespace remains. A javascript solution would be fine too.

Here is my html:

Observations

      <select class="form-control patient-list noglow" id="observation" name="observation" size="7">
        <option value="1">2017-03-23 04:40:36</option>
        <option value="2">2017-03-23 04:50:32</option>
        <option value="4">2017-03-28 04:18:55</option>
        <option value="5">2017-03-28 19:01:34</option>
        <option value="11">2017-03-28 22:06:25</option>
        <option value="12">2017-03-28 22:37:32</option>
        <option value="13">2017-03-28 23:10:19</option>
        <option value="14">2017-03-29 02:17:57</option>
      </select>

And my css:

.patient-list {
    font-size: 20px;
    border: none;
}

.panel-body.scroll-list {
    padding: 0px 0px 0px 0px;
}

And below is that ugly looking whitespace in my list:

Body:
Try this:

.panel-body .form-group {
  margin-bottom:0px;
}

updated link

Decription

If you change form-group class property it will effect in bootstrap, because form-group class use globally for forms.. so change its property by making it as a child div..


问:
check for duplicates in diffrent worksheets and thereafter print value
I have searched but i cant seem to figure out how to print specified value in the column next to where i find my duplicate. What i have since earlier are code that first specify the diffrent ranges and thereafter look if a duplicate is found in sheet Y from sheet X. Sheet Le is this weeks information and sheet Be is the last weeks information.

IF i find a duplicate in the specified range i want to on my Delivery sheet print in column A next to the duplicate either Delivered or not delivered depending on if my output from function compareAEO print true or false.

The conditions that i am looking for are that if the we can find the same value that are in column B in sheet (Le) on sheet (Be) it will then check if the text in column F has changed. IF SO then it shall print in column A on sheet (Le) = Delivered. Otherwise not delivered.

It then checks to se if the dates in column M is the same. IF not then it shall print Replanned in column A on sheet (Le).

Shortly
IF value in cell on column B, Sheet (Le) = Value in column B, Sheet (Be) then
value in column A on sheet Le = "Delivered" Else "not deliverd".

Then

If value in cell in column M, Sheet (Le) <> If value in cell in column M, Sheet (Be) then value in column A, Sheet(Le) = "replanned"

This is how my data looks like,
Sheet (Le)

```<code>Col B   Col F    Col M
PZ2408  X13    2017-02-13
PZ2345  X30    2017-02-23
PZ2463  X45    2017-02-25
PZ2513  X13    2017-02-10
PZ2533  X70    2017-02-05
PZ2561  X60    2017-02-20
</code>```

For sheet (Be) my data looks like this

```<code>Col B   Col F    Col M
PZ2408  X30    2017-02-13
PZ2345  X30    2017-02-23
PZ2463  X30    2017-02-25
PZ2513  X13    2017-02-05
PZ2533  X13    2017-02-10
PZ2561  X60    2017-02-17
</code>```

After the code has done its course i would like it to show for example,

Sheet (Le)

```<code>    col A           Col B   Col F    Col M
   Delivered       PZ2408   X13    2017-02-13
Not Delivered      PZ2345   X30    2017-02-23
   Delivered       PZ2463   X45    2017-02-25
  replanned        PZ2513   X13    2017-02-10
   Delivered       PZ2533   X70    2017-02-05
   replanned       PZ2561   X60    2017-02-20
</code>```

Bascilly my Not delivered, delivered and Replanned statements does not work and my brain does not work.

Can SO help save my day?

```<code>Sub checkASMT()
Dim rng1 As Range
Dim rng2 As Range
Dim lastRowSource As Long
Dim lastRowTarget As Long
Dim row As Long
Dim ASMT As String

'Looping trough Range
With ThisWorkbook.Worksheets("Le")

   lastRowTarget = .Range("B" & .Rows.Count).End(xlUp).row
   For i = 29 To lastRowTarget
        ASMT = .Range("b" & i).value
        'Define range and see if we can find duplicates
        With ThisWorkbook.Worksheets("Be")
            lastRowSource = .Range("B" & .Rows.Count).End(xlUp).row
            Set rng1 = .Range("B3", "B" & lastRowSource)

            row = findValueInRangeReturnRow(rng1, ASMT)

            'Check FAX
            If compareAEO(i, row, "FAX") = True Then
                'Debug.Print compareASMT(i, row, "FAX")
                Worksheets("Le").Cells(i, ASMT).value = "Not Delivered"

                Else

                .Worksheets("Le").Cells(i, ASMT).value = "delivered"

                'Check if dax are correct
                If compareAEO(i, row, "DAX") = False Then
                .Worksheets("Le").ASMT.Offset(0, 1).value = "Replan"

            End If

        End With
    Next i

End With

 End Sub
</code>```

here are my first function

```<code> Function findValueInRangeReturnRow(rng As Range, value As Variant) As Long

        Set c = rng.Find(value, LookIn:=xlValues)

        If Not c Is Nothing Then

            findValueInRangeReturnRow = c.row

        End If

End Function
</code>```

My second function that checks if duplicates are found in specified ranges.

```<code>Function compareAEO(rad1 As Variant, rad2 As Variant, typeCOMPARE As String) As Boolean

Dim col1 As String
Dim col2 As String

  Select Case typeCOMPARE
    Case "FAX"
        col1 = "F"
        col2 = "F"

    Case "DAX"
        col1 = "M"
        col2 = "M"

    End Select

   If ThisWorkbook.Worksheets("Le").Range(col1 & rad1).value =   ThisWorkbook.Worksheets("Be").Range(col2 & rad2).value Then

    compareAEO = True
    Else

    compareAEO = False
End If

End Function
</code>```

答:
Try this; place data in single sheet from B to G (Le then Be); place this formula in column H

```<code>=IF(VLOOKUP(E2,B$2:D$7,2,FALSE)=F2,IF(G2<D2,"replanned","Not Delivered"),"delivered")
</code>```

tweak this formula to suit your needs to make it work across sheets

Body:
I have searched but i cant seem to figure out how to print specified value in the column next to where i find my duplicate. What i have since earlier are code that first specify the diffrent ranges and thereafter look if a duplicate is found in sheet Y from sheet X. Sheet Le is this weeks information and sheet Be is the last weeks information.

IF i find a duplicate in the specified range i want to on my Delivery sheet print in column A next to the duplicate either Delivered or not delivered depending on if my output from function compareAEO print true or false.

The conditions that i am looking for are that if the we can find the same value that are in column B in sheet (Le) on sheet (Be) it will then check if the text in column F has changed. IF SO then it shall print in column A on sheet (Le) = Delivered. Otherwise not delivered.

It then checks to se if the dates in column M is the same. IF not then it shall print Replanned in column A on sheet (Le).

Shortly
IF value in cell on column B, Sheet (Le) = Value in column B, Sheet (Be) then
value in column A on sheet Le = "Delivered" Else "not deliverd".

Then

If value in cell in column M, Sheet (Le) <> If value in cell in column M, Sheet (Be) then value in column A, Sheet(Le) = "replanned"

This is how my data looks like,
Sheet (Le)

Col B   Col F    Col M
PZ2408  X13    2017-02-13
PZ2345  X30    2017-02-23
PZ2463  X45    2017-02-25
PZ2513  X13    2017-02-10
PZ2533  X70    2017-02-05
PZ2561  X60    2017-02-20

For sheet (Be) my data looks like this

Col B   Col F    Col M
PZ2408  X30    2017-02-13
PZ2345  X30    2017-02-23
PZ2463  X30    2017-02-25
PZ2513  X13    2017-02-05
PZ2533  X13    2017-02-10
PZ2561  X60    2017-02-17

After the code has done its course i would like it to show for example,

Sheet (Le)

    col A           Col B   Col F    Col M
   Delivered       PZ2408   X13    2017-02-13
Not Delivered      PZ2345   X30    2017-02-23
   Delivered       PZ2463   X45    2017-02-25
  replanned        PZ2513   X13    2017-02-10
   Delivered       PZ2533   X70    2017-02-05
   replanned       PZ2561   X60    2017-02-20

Bascilly my Not delivered, delivered and Replanned statements does not work and my brain does not work.

Can SO help save my day?

Sub checkASMT()
Dim rng1 As Range
Dim rng2 As Range
Dim lastRowSource As Long
Dim lastRowTarget As Long
Dim row As Long
Dim ASMT As String

'Looping trough Range
With ThisWorkbook.Worksheets("Le")

   lastRowTarget = .Range("B" & .Rows.Count).End(xlUp).row
   For i = 29 To lastRowTarget
        ASMT = .Range("b" & i).value
        'Define range and see if we can find duplicates
        With ThisWorkbook.Worksheets("Be")
            lastRowSource = .Range("B" & .Rows.Count).End(xlUp).row
            Set rng1 = .Range("B3", "B" & lastRowSource)

            row = findValueInRangeReturnRow(rng1, ASMT)

            'Check FAX
            If compareAEO(i, row, "FAX") = True Then
                'Debug.Print compareASMT(i, row, "FAX")
                Worksheets("Le").Cells(i, ASMT).value = "Not Delivered"

                Else

                .Worksheets("Le").Cells(i, ASMT).value = "delivered"

                'Check if dax are correct
                If compareAEO(i, row, "DAX") = False Then
                .Worksheets("Le").ASMT.Offset(0, 1).value = "Replan"

            End If

        End With
    Next i

End With

 End Sub

here are my first function

 Function findValueInRangeReturnRow(rng As Range, value As Variant) As Long

        Set c = rng.Find(value, LookIn:=xlValues)

        If Not c Is Nothing Then

            findValueInRangeReturnRow = c.row

        End If

End Function

My second function that checks if duplicates are found in specified ranges.

Function compareAEO(rad1 As Variant, rad2 As Variant, typeCOMPARE As String) As Boolean

Dim col1 As String
Dim col2 As String

  Select Case typeCOMPARE
    Case "FAX"
        col1 = "F"
        col2 = "F"

    Case "DAX"
        col1 = "M"
        col2 = "M"

    End Select

   If ThisWorkbook.Worksheets("Le").Range(col1 & rad1).value =   ThisWorkbook.Worksheets("Be").Range(col2 & rad2).value Then

    compareAEO = True
    Else

    compareAEO = False
End If

End Function

Body:
Try this; place data in single sheet from B to G (Le then Be); place this formula in column H

=IF(VLOOKUP(E2,B$2:D$7,2,FALSE)=F2,IF(G2<D2,"replanned","Not Delivered"),"delivered")

tweak this formula to suit your needs to make it work across sheets


问:
SQL - Order by time, then text on beginning
I have a query below :

SELECT DISTINCT TimeSched from tbl_schedule

It returns this result:

```<code>TimeSched

Rest Day
11:00 AM - 08:00 PM
No Schedule
09:00 AM - 06:00 PM
10:00 AM - 07:00 PM
</code>```

When I use ORDER BY TimeSched, it returns this result:

```<code>TimeSched

09:00 AM - 06:00 PM
10:00 AM - 07:00 PM
11:00 AM - 08:00 PM
No Schedule
Rest Day
</code>```

However, my desired result is I want 'Rest Day' and 'No Schedule' on the first and second row by default, then followed by the order of schedules in ascending order. As seen below :

```<code>TimeSched

Rest Day
No Schedule
09:00 AM - 06:00 PM
10:00 AM - 07:00 PM
11:00 AM - 08:00 PM
</code>```

答:
How about simply doing:</p>

```<code>SELECT DISTINCT TimeSched
FROM tbl_schedule
ORDER BY (CASE WHEN timesched LIKE '[a-zA-Z]%' THEN 1 ELSE 0 END),
         timesched;
</code>```

Body:
I have a query below :

SELECT DISTINCT TimeSched from tbl_schedule

It returns this result:

TimeSched

Rest Day
11:00 AM - 08:00 PM
No Schedule
09:00 AM - 06:00 PM
10:00 AM - 07:00 PM

When I use ORDER BY TimeSched, it returns this result:

TimeSched

09:00 AM - 06:00 PM
10:00 AM - 07:00 PM
11:00 AM - 08:00 PM
No Schedule
Rest Day

However, my desired result is I want 'Rest Day' and 'No Schedule' on the first and second row by default, then followed by the order of schedules in ascending order. As seen below :

TimeSched

Rest Day
No Schedule
09:00 AM - 06:00 PM
10:00 AM - 07:00 PM
11:00 AM - 08:00 PM

Body:
How about simply doing:

SELECT DISTINCT TimeSched
FROM tbl_schedule
ORDER BY (CASE WHEN timesched LIKE '[a-zA-Z]%' THEN 1 ELSE 0 END),
         timesched;


问:
Angular 2 Dragula Model updating incorrectly
Working with ng2-dragula. I'm looking to update the orderNumber for every item in a database using the new dropped order.

```<code>dragulaService.dropModel.subscribe((value) => {
  var drake = dragulaService.find('bag-orders').drake
  var models = drake.models
  console.log(models)
})
</code>```

The new model order that it returns does not reflect the order within the bag.

TL;DR: has anyone implemented reordering within a database onDrop with ng2-dragula?

答:
I found Marçal's answer incredibly helpful, and have even expanded on it a little to post an update to my DB to update the sequence value of each item (contacts within an organization, in my case) in the list:

HTML (container is the contact's organization. a contact, in my case, can't be moved between organizations):

```<code><div class="container" [dragula]="'org-' + org.id" [dragulaModel]="org.contacts">
  <nested-contact *ngFor="let contact of org.contacts" [user]="contact" class="contact" [attr.data-id]="contact.id"></nested-contact>
</div>
</code>```

JS (in my Contact Service, a PUT function to update the stored sequence values associated with each of my contacts, so that their orders persist):

```<code>contactsIdPut (id, body) {
  let url = '/api/v3/contacts/' + id + '?access_token=' + localStorage.getItem('access_token');
  let headers = new Headers({ 'Content-Type': 'application/json' });
  let options = new RequestOptions({ headers: headers });

  return this.http.put(url, body, options)
    .map((response: Response) => {
      return response.json();
    });
</code>```

}

JS (in my organization view component, to outline the actions to be taken upon drag and drop, respectively):

```<code>export class nestedOrganizationComponent {
  orgs = [];
  thisOrg: any;
  thisContact: any;

  constructor (private _contactService: ContactService, private dragulaService: DragulaService) {
    this._contactService = _contactService;

    let dragIndex: any;
    let dropIndex: any;
    let elementNode: any;

    dragulaService.drag.subscribe((value) => {
      let id = Number(value[1].dataset.id);
      let orgId: Number = value[0].split('-')[1];
      elementNode = value[2].querySelectorAll('.contact:not(.ignore)').item(dragIndex);

      if (!!id) {
        // this renderedOrgs is just an array to hold the org options that render in this particular view
        this._organizationService.renderedOrgs.push(this.org);
        this.thisOrg = this._organizationService.renderedOrgs.filter(org => { return org.id == orgId; })[0];
        this.thisContact = this.thisOrg.contacts.filter(contact => { return contact.id == id; })[0];

        let arr = this.thisOrg.contacts.map(x => { return x.id; });
        dragIndex = arr.indexOf(id);
      }
    });

    dragulaService.drop.subscribe((value: any[]) => {
      if (elementNode) {
          let id = Number(elementNode.dataset.id);
          if (!!id) {
            let arr = this.thisOrg.contacts.map(x => { return x.id; });
            dropIndex = arr.indexOf(id);
          }
      }

      if (value[2] === value[3]) { // target container === source container
          if (dragIndex >= 0 && dropIndex >= 0 && dragIndex !== dropIndex) {
            this.thisOrg.contacts.forEach((contact, index) => {
              contact.sequence = index;
              this.updateSequence(contact.id, index);
            });
          }
      }
    });
  }

  updateSequence (id: Number, index: Number) {
    let contactBody = {
      avatar: {
        sequence: index,
      }
    };

    return this._contactService.contactsIdPut(id, contactBody)
      .subscribe(
        (data: any) => {
          // nothing is needed, the same view can apply because the contact has already been moved.
        },
        (error: any) => {
          console.error(error);
        }
      );
  }
}
</code>```

Hopefully this provides a bit more clarity on the matter to someone else in a spot similar to where I found myself today.

Body:
Working with ng2-dragula. I'm looking to update the orderNumber for every item in a database using the new dropped order.

dragulaService.dropModel.subscribe((value) => {
  var drake = dragulaService.find('bag-orders').drake
  var models = drake.models
  console.log(models)
})

The new model order that it returns does not reflect the order within the bag.

TL;DR: has anyone implemented reordering within a database onDrop with ng2-dragula?

Body:
I found Marçal's answer incredibly helpful, and have even expanded on it a little to post an update to my DB to update the sequence value of each item (contacts within an organization, in my case) in the list:

HTML (container is the contact's organization. a contact, in my case, can't be moved between organizations):

<div class="container" [dragula]="'org-' + org.id" [dragulaModel]="org.contacts">
  <nested-contact *ngFor="let contact of org.contacts" [user]="contact" class="contact" [attr.data-id]="contact.id"></nested-contact>
</div>

JS (in my Contact Service, a PUT function to update the stored sequence values associated with each of my contacts, so that their orders persist):

contactsIdPut (id, body) {
  let url = '/api/v3/contacts/' + id + '?access_token=' + localStorage.getItem('access_token');
  let headers = new Headers({ 'Content-Type': 'application/json' });
  let options = new RequestOptions({ headers: headers });

  return this.http.put(url, body, options)
    .map((response: Response) => {
      return response.json();
    });

}

JS (in my organization view component, to outline the actions to be taken upon drag and drop, respectively):

export class nestedOrganizationComponent {
  orgs = [];
  thisOrg: any;
  thisContact: any;

  constructor (private _contactService: ContactService, private dragulaService: DragulaService) {
    this._contactService = _contactService;

    let dragIndex: any;
    let dropIndex: any;
    let elementNode: any;

    dragulaService.drag.subscribe((value) => {
      let id = Number(value[1].dataset.id);
      let orgId: Number = value[0].split('-')[1];
      elementNode = value[2].querySelectorAll('.contact:not(.ignore)').item(dragIndex);

      if (!!id) {
        // this renderedOrgs is just an array to hold the org options that render in this particular view
        this._organizationService.renderedOrgs.push(this.org);
        this.thisOrg = this._organizationService.renderedOrgs.filter(org => { return org.id == orgId; })[0];
        this.thisContact = this.thisOrg.contacts.filter(contact => { return contact.id == id; })[0];

        let arr = this.thisOrg.contacts.map(x => { return x.id; });
        dragIndex = arr.indexOf(id);
      }
    });

    dragulaService.drop.subscribe((value: any[]) => {
      if (elementNode) {
          let id = Number(elementNode.dataset.id);
          if (!!id) {
            let arr = this.thisOrg.contacts.map(x => { return x.id; });
            dropIndex = arr.indexOf(id);
          }
      }

      if (value[2] === value[3]) { // target container === source container
          if (dragIndex >= 0 && dropIndex >= 0 && dragIndex !== dropIndex) {
            this.thisOrg.contacts.forEach((contact, index) => {
              contact.sequence = index;
              this.updateSequence(contact.id, index);
            });
          }
      }
    });
  }

  updateSequence (id: Number, index: Number) {
    let contactBody = {
      avatar: {
        sequence: index,
      }
    };

    return this._contactService.contactsIdPut(id, contactBody)
      .subscribe(
        (data: any) => {
          // nothing is needed, the same view can apply because the contact has already been moved.
        },
        (error: any) => {
          console.error(error);
        }
      );
  }
}

Hopefully this provides a bit more clarity on the matter to someone else in a spot similar to where I found myself today.


问:
Javascript: Is there a way to FindControl like in C#?
Please no jQuery solutions! I am still learning JavaScript.

I have a function that breaks down some of the DOM elements based on a given checkbox control.

```<code>            function highlightRow(chk) {
                var cell = chk.parentNode;
                var row = cell.parentNode;
                var tbody = row.parentNode;
                var rows = tbody.children;
                var hrow = rows[0];                         //get header row
-->             var hCbox = hrow.getElementsByID("cbHDR");  //get 'cbHDR' checkbox that's in the header

                if (chk.checked) {
                    addClass(row, 'selected-row');
                }
                else {
                    removeClass(row, 'selected-row');
                }
    ..etc
    }
</code>```

The problem I am having is the line shown ...

var hCbox = hrow.getElementsByID("cbHDR");

How do I find elements based on a given element, such as in this case the HeaderRow of a Gridview?

The above returns null. In fact I don't even know if it even runs, as I am not sure if getElementsByID() is purely a method for the document object.

I am trying to avoid using document.get... as it retrieves ALL header checkboxes across 4 GridViews in my case. I am trying to find the Header checkbox based on the HeaderRow only.

Thanks

答:
in pure javascript, finding an element by tag name can be done with querySelector on the containing element. So if you've already obtained a reference to the dom element for the gridview (say, using getElementById), captured in a variable called gridView, then:

```<code>let headerRow = gridView.querySelector('HeaderRow');
</code>```

BTW let is es6 syntax. So if you're worried about old browser compatibility, use var instead.

Body:
Please no jQuery solutions! I am still learning JavaScript.

I have a function that breaks down some of the DOM elements based on a given checkbox control.

            function highlightRow(chk) {
                var cell = chk.parentNode;
                var row = cell.parentNode;
                var tbody = row.parentNode;
                var rows = tbody.children;
                var hrow = rows[0];                         //get header row
-->             var hCbox = hrow.getElementsByID("cbHDR");  //get 'cbHDR' checkbox that's in the header

                if (chk.checked) {
                    addClass(row, 'selected-row');
                }
                else {
                    removeClass(row, 'selected-row');
                }
    ..etc
    }

The problem I am having is the line shown ...

var hCbox = hrow.getElementsByID("cbHDR");

How do I find elements based on a given element, such as in this case the HeaderRow of a Gridview?

The above returns null. In fact I don't even know if it even runs, as I am not sure if getElementsByID() is purely a method for the document object.

I am trying to avoid using document.get... as it retrieves ALL header checkboxes across 4 GridViews in my case. I am trying to find the Header checkbox based on the HeaderRow only.

Thanks

Body:
in pure javascript, finding an element by tag name can be done with querySelector on the containing element. So if you've already obtained a reference to the dom element for the gridview (say, using getElementById), captured in a variable called gridView, then:

let headerRow = gridView.querySelector('HeaderRow');

BTW let is es6 syntax. So if you're worried about old browser compatibility, use var instead.


问:
Exception: The speech privacy policy was not accepted prior to attempting a speech recognition
From where do I have to accept the speech recognition policy?

Here is the code

```<code>public async void display()
{
    SpeechRecognizer rec = new SpeechRecognizer();
    await rec.CompileConstraintsAsync();
    rec.Timeouts.InitialSilenceTimeout = TimeSpan.FromSeconds(5);
    rec.Timeouts.EndSilenceTimeout = TimeSpan.FromSeconds(20);
    rec.UIOptions.AudiblePrompt = "I am listening";
    rec.UIOptions.ShowConfirmation = true;
    rec.UIOptions.IsReadBackEnabled = true;
    rec.Timeouts.BabbleTimeout = TimeSpan.FromSeconds(5);
    SpeechRecognitionResult result = await rec.RecognizeAsync(); // Error here

    if (result!=null)
    {
        textBlock.Text= result.Text;
    }
}
</code>```

答:
It is a setting under Speech, Inking and Typing.
First, go to Settings and click "Time & Language".
Next, select "Speech" from the menu on the left.
After that, press "Speech, inking & typing privacy settings".
Just press the button called "Get to know me".

Then, click the popup to turn the setting on.

After that, any software that uses the Speech Recognition API will work.

A helpful way to tell users to turn on would be...

```<code>catch (System.Runtime.InteropServices.COMException e) when (e.HResult == unchecked((int)0x80045509))
//privacyPolicyHResult
//The speech privacy policy was not accepted prior to attempting a speech recognition.
{
    ContentDialog Dialog = new ContentDialog()
    {
        Title = "The speech privacy policy was not accepted",
        Content = "You need to turn on a button called 'Get to know me'...",
        PrimaryButtonText = "Shut up",
        SecondaryButtonText = "Shut up and show me the setting"
    };
    if (await Dialog.ShowAsync() == ContentDialogResult.Secondary)
    {
        const string uriToLaunch = "ms-settings:privacy-speechtyping";
        //"http://stackoverflow.com/questions/42391526/exception-the-speech-privacy-policy-" +
        //"was-not-accepted-prior-to-attempting-a-spee/43083877#43083877";
        var uri = new Uri(uriToLaunch);

        var success = await Windows.System.Launcher.LaunchUriAsync(uri);

        if (!success) await new ContentDialog
        {
            Title = "Oops! Something went wrong...",
            Content = "The settings app could not be opened.",
            PrimaryButtonText = "Shut your mouth up!"
        }.ShowAsync();
    }
}
</code>```

More ways to launch the Settings app

Body:
From where do I have to accept the speech recognition policy?

Here is the code

public async void display()
{
    SpeechRecognizer rec = new SpeechRecognizer();
    await rec.CompileConstraintsAsync();
    rec.Timeouts.InitialSilenceTimeout = TimeSpan.FromSeconds(5);
    rec.Timeouts.EndSilenceTimeout = TimeSpan.FromSeconds(20);
    rec.UIOptions.AudiblePrompt = "I am listening";
    rec.UIOptions.ShowConfirmation = true;
    rec.UIOptions.IsReadBackEnabled = true;
    rec.Timeouts.BabbleTimeout = TimeSpan.FromSeconds(5);
    SpeechRecognitionResult result = await rec.RecognizeAsync(); // Error here

    if (result!=null)
    {
        textBlock.Text= result.Text;
    }
}

Body:
It is a setting under Speech, Inking and Typing.
First, go to Settings and click "Time & Language".
Next, select "Speech" from the menu on the left.
After that, press "Speech, inking & typing privacy settings".
Just press the button called "Get to know me".

Then, click the popup to turn the setting on.

After that, any software that uses the Speech Recognition API will work.

A helpful way to tell users to turn on would be...

catch (System.Runtime.InteropServices.COMException e) when (e.HResult == unchecked((int)0x80045509))
//privacyPolicyHResult
//The speech privacy policy was not accepted prior to attempting a speech recognition.
{
    ContentDialog Dialog = new ContentDialog()
    {
        Title = "The speech privacy policy was not accepted",
        Content = "You need to turn on a button called 'Get to know me'...",
        PrimaryButtonText = "Shut up",
        SecondaryButtonText = "Shut up and show me the setting"
    };
    if (await Dialog.ShowAsync() == ContentDialogResult.Secondary)
    {
        const string uriToLaunch = "ms-settings:privacy-speechtyping";
        //"http://stackoverflow.com/questions/42391526/exception-the-speech-privacy-policy-" +
        //"was-not-accepted-prior-to-attempting-a-spee/43083877#43083877";
        var uri = new Uri(uriToLaunch);

        var success = await Windows.System.Launcher.LaunchUriAsync(uri);

        if (!success) await new ContentDialog
        {
            Title = "Oops! Something went wrong...",
            Content = "The settings app could not be opened.",
            PrimaryButtonText = "Shut your mouth up!"
        }.ShowAsync();
    }
}

More ways to launch the Settings app


问:
Hack `kur -v data mnist.yml` for a simpler overview of data on provider?
The problem

When I run kur -v data mnist.yml, kur prints out a batch of samples, which is so long that you can see or take a long time to scroll to the beginning for log messages.

Then I store the log output in a file with kur -v data mnist.yml 2>&1 | tee my.txt, and now I can paste the log messages below

```<code>[1;37m[INFO 2017-03-25 16:18:09,717 kur.kurfile:709][0m Parsing source: mnist.yml, included by top-level.[0m
[1;37m[INFO 2017-03-25 16:18:09,724 kur.kurfile:709][0m Parsing source: mnist-defaults.yml, included by mnist.yml.[0m
[1;37m[INFO 2017-03-25 16:18:09,733 kur.kurfile:84][0m Parsing Kurfile...[0m
[1;37m[INFO 2017-03-25 16:18:09,749 kur.__main__:144][0m Preparing data sources for: train[0m
Entry 1/32:
  images: [[[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
...
...
</code>```

The problem with this output is that it is not exactly what I want. I normally want two things from a data overview:
1. shape of provided data
2. a sample printed out

Current kur -v data mnist.yml just prints out total 32 samples in a batch. To be fair, kur -vv data mnist.yml do tell us the number of samples in a batch. That's it.

Challenge

How to make kur -v data mnist.yml to print out:

shape of provided data

a sample printed out

Like the following:

```<code>[INFO 2017-03-25 14:31:14,318 kur.kurfile:760] Parsing source: mnist.yml, included by top-level.
[INFO 2017-03-25 14:31:14,324 kur.kurfile:760] Parsing source: mnist-defaults.yml, included by mnist.yml.
[INFO 2017-03-25 14:31:14,334 kur.kurfile:113] Parsing Kurfile...
[INFO 2017-03-25 14:31:15,465 kur.__main__:290] A single batch consists of: {'labels': (32, 10), 'images': (32, 28, 28, 1)}
[INFO 2017-03-25 14:31:15,465 kur.__main__:294] There are total 32 samples in a single batch.
[INFO 2017-03-25 14:31:15,466 kur.__main__:295] Let's have a look a single sample
Entry 1/32:
  images: [[[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.37130019]
  [ 0.37130019]
  [ 0.86933935]
  [ 0.61835897]
  [ 0.37130019]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.12031978]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.12031978]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.61835897]
  [ 0.37130019]
  [ 0.12031978]
  [ 0.61835897]
  [ 0.86933935]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.37130019]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.37130019]
  [ 0.86933935]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.12031978]
  [ 0.61835897]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.61835897]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.61835897]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.61835897]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.12031978]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.12031978]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.61835897]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.12031978]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.37130019]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.12031978]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.12031978]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.12031978]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.12031978]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.12031978]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.37130019]
  [ 0.37130019]
  [ 0.37130019]
  [ 0.37130019]
  [ 0.12031978]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.37130019]
  [ 0.86933935]
  [ 0.61835897]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.12031978]
  [ 0.61835897]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.61835897]
  [ 0.12031978]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.61835897]
  [ 0.86933935]
  [ 0.37130019]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.61835897]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.37130019]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.37130019]
  [ 0.37130019]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.37130019]
  [ 0.61835897]
  [ 0.86933935]
  [ 0.37130019]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.37130019]
  [ 0.86933935]
  [ 0.37130019]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.86933935]
  [ 0.37130019]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.37130019]
  [ 0.86933935]
  [ 0.86933935]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.12031978]
  [ 0.86933935]
  [ 0.61835897]
  [ 0.12031978]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.12031978]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.61835897]
  [ 0.86933935]
  [ 0.12031978]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.61835897]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.37130019]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.12031978]
  [ 0.12031978]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.37130019]
  [ 0.61835897]
  [ 0.86933935]
  [ 0.37130019]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.61835897]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.37130019]
  [ 0.37130019]
  [ 0.37130019]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.37130019]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.37130019]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.61835897]
  [ 0.37130019]
  [ 0.37130019]
  [ 0.12031978]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]]
  labels: [ 0.  0.  0.  0.  0.  0.  1.  0.  0.  0.]
</code>```

答:
Here is another way to output a simpler view of data: </p>

```<code>In [17]: !kur -v data --single mnist.yml
[INFO 2017-03-29 11:34:42,369 kur.kurfile:712] Parsing source: mnist.yml, included by top-level.
[INFO 2017-03-29 11:34:42,376 kur.kurfile:712] Parsing source: mnist-defaults.yml, included by mnist.yml.
[INFO 2017-03-29 11:34:42,386 kur.kurfile:85] Parsing Kurfile...
[INFO 2017-03-29 11:34:42,407 kur.__main__:147] Preparing data sources for: train
[INFO 2017-03-29 11:34:43,309 kur.__main__:186] We are training with 15 batches using 480 samples of data
[INFO 2017-03-29 11:34:43,309 kur.__main__:190] A single batch consists of: {'labels': (32, 10), 'images': (32, 28, 28, 1)}
Entry 1/32:
  images: [[[-0.13066062]
  [-0.13066062]
</code>```

Body:
The problem

When I run kur -v data mnist.yml, kur prints out a batch of samples, which is so long that you can see or take a long time to scroll to the beginning for log messages.

Then I store the log output in a file with kur -v data mnist.yml 2>&1 | tee my.txt, and now I can paste the log messages below

[1;37m[INFO 2017-03-25 16:18:09,717 kur.kurfile:709][0m Parsing source: mnist.yml, included by top-level.[0m
[1;37m[INFO 2017-03-25 16:18:09,724 kur.kurfile:709][0m Parsing source: mnist-defaults.yml, included by mnist.yml.[0m
[1;37m[INFO 2017-03-25 16:18:09,733 kur.kurfile:84][0m Parsing Kurfile...[0m
[1;37m[INFO 2017-03-25 16:18:09,749 kur.__main__:144][0m Preparing data sources for: train[0m
Entry 1/32:
  images: [[[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
...
...

The problem with this output is that it is not exactly what I want. I normally want two things from a data overview:
1. shape of provided data
2. a sample printed out

Current kur -v data mnist.yml just prints out total 32 samples in a batch. To be fair, kur -vv data mnist.yml do tell us the number of samples in a batch. That's it.

Challenge

How to make kur -v data mnist.yml to print out:

shape of provided data

a sample printed out

Like the following:

[INFO 2017-03-25 14:31:14,318 kur.kurfile:760] Parsing source: mnist.yml, included by top-level.
[INFO 2017-03-25 14:31:14,324 kur.kurfile:760] Parsing source: mnist-defaults.yml, included by mnist.yml.
[INFO 2017-03-25 14:31:14,334 kur.kurfile:113] Parsing Kurfile...
[INFO 2017-03-25 14:31:15,465 kur.__main__:290] A single batch consists of: {'labels': (32, 10), 'images': (32, 28, 28, 1)}
[INFO 2017-03-25 14:31:15,465 kur.__main__:294] There are total 32 samples in a single batch.
[INFO 2017-03-25 14:31:15,466 kur.__main__:295] Let's have a look a single sample
Entry 1/32:
  images: [[[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.37130019]
  [ 0.37130019]
  [ 0.86933935]
  [ 0.61835897]
  [ 0.37130019]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.12031978]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.12031978]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.61835897]
  [ 0.37130019]
  [ 0.12031978]
  [ 0.61835897]
  [ 0.86933935]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.37130019]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.37130019]
  [ 0.86933935]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.12031978]
  [ 0.61835897]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.61835897]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.61835897]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.61835897]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.12031978]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.12031978]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.61835897]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.12031978]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.37130019]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.12031978]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.12031978]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.12031978]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.12031978]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.12031978]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.37130019]
  [ 0.37130019]
  [ 0.37130019]
  [ 0.37130019]
  [ 0.12031978]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.37130019]
  [ 0.86933935]
  [ 0.61835897]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.12031978]
  [ 0.61835897]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.61835897]
  [ 0.12031978]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.61835897]
  [ 0.86933935]
  [ 0.37130019]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.61835897]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.37130019]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.37130019]
  [ 0.37130019]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.37130019]
  [ 0.61835897]
  [ 0.86933935]
  [ 0.37130019]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.37130019]
  [ 0.86933935]
  [ 0.37130019]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.86933935]
  [ 0.37130019]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.37130019]
  [ 0.86933935]
  [ 0.86933935]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.12031978]
  [ 0.86933935]
  [ 0.61835897]
  [ 0.12031978]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.12031978]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.61835897]
  [ 0.86933935]
  [ 0.12031978]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.61835897]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.37130019]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.12031978]
  [ 0.12031978]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.37130019]
  [ 0.61835897]
  [ 0.86933935]
  [ 0.37130019]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.61835897]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.37130019]
  [ 0.37130019]
  [ 0.37130019]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.37130019]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [ 0.37130019]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.86933935]
  [ 0.61835897]
  [ 0.37130019]
  [ 0.37130019]
  [ 0.12031978]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]

 [[-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]
  [-0.13066062]]]
  labels: [ 0.  0.  0.  0.  0.  0.  1.  0.  0.  0.]

Body:
Here is another way to output a simpler view of data:

In [17]: !kur -v data --single mnist.yml
[INFO 2017-03-29 11:34:42,369 kur.kurfile:712] Parsing source: mnist.yml, included by top-level.
[INFO 2017-03-29 11:34:42,376 kur.kurfile:712] Parsing source: mnist-defaults.yml, included by mnist.yml.
[INFO 2017-03-29 11:34:42,386 kur.kurfile:85] Parsing Kurfile...
[INFO 2017-03-29 11:34:42,407 kur.__main__:147] Preparing data sources for: train
[INFO 2017-03-29 11:34:43,309 kur.__main__:186] We are training with 15 batches using 480 samples of data
[INFO 2017-03-29 11:34:43,309 kur.__main__:190] A single batch consists of: {'labels': (32, 10), 'images': (32, 28, 28, 1)}
Entry 1/32:
  images: [[[-0.13066062]
  [-0.13066062]


问:
How can I build multiple submit buttons django form?
I have form with one input for email and two submit buttons to subscribe and unsubscribe from newsletter:

```<code><form action="" method="post">
{{ form_newsletter }}
<input type="submit" name="newsletter_sub" value="Subscribe" />
<input type="submit" name="newsletter_unsub" value="Unsubscribe" />
</form>
</code>```

I have also class form:

```<code>class NewsletterForm(forms.ModelForm):
    class Meta:
        model = Newsletter
        fields = ('email',)
</code>```

I must write my own clean_email method and I need to know by which button was form submited. But the value of submit buttons aren't in self.cleaned_data dictionary.
Could I get values of buttons otherwise?

答:
one url to the same view!
like so!

urls.py

```<code>url(r'^$', views.landing.as_view(), name = 'landing'),
</code>```

views.py

```<code>class landing(View):
        template_name = '/home.html'
        form_class1 = forms.pynamehere1
        form_class2 = forms.pynamehere2
            def get(self, request):
                form1 = self.form_class1(None)
                form2 = self.form_class2(None)
                return render(request, self.template_name, { 'register':form1, 'login':form2,})

             def post(self, request):
                 if request.method=='POST' and 'htmlsubmitbutton1' in request.POST:
                        ## do what ever you want to do for first function ####
                 if request.method=='POST' and 'htmlsubmitbutton2' in request.POST:
                         ## do what ever you want to do for second function ####
                        ## return def post###
                 return render(request, self.template_name, {'form':form,})
</code>```

```<code>/home.html
    <!-- #### form 1 #### -->
    <form action="" method="POST" >
      {% csrf_token %}
      {{ register.as_p }}
    <button type="submit" name="htmlsubmitbutton1">Login</button>
    </form>
    <!--#### form 2 #### -->
    <form action="" method="POST" >
      {% csrf_token %}
      {{ login.as_p }}
    <button type="submit" name="htmlsubmitbutton2">Login</button>
    </form>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have form with one input for email and two submit buttons to subscribe and unsubscribe from newsletter:

<form action="" method="post">
{{ form_newsletter }}
<input type="submit" name="newsletter_sub" value="Subscribe" />
<input type="submit" name="newsletter_unsub" value="Unsubscribe" />
</form>

I have also class form:

class NewsletterForm(forms.ModelForm):
    class Meta:
        model = Newsletter
        fields = ('email',)

I must write my own clean_email method and I need to know by which button was form submited. But the value of submit buttons aren't in self.cleaned_data dictionary.
Could I get values of buttons otherwise?

Body:
one url to the same view!
like so!

urls.py

url(r'^$', views.landing.as_view(), name = 'landing'),

views.py

class landing(View):
        template_name = '/home.html'
        form_class1 = forms.pynamehere1
        form_class2 = forms.pynamehere2
            def get(self, request):
                form1 = self.form_class1(None)
                form2 = self.form_class2(None)
                return render(request, self.template_name, { 'register':form1, 'login':form2,})

             def post(self, request):
                 if request.method=='POST' and 'htmlsubmitbutton1' in request.POST:
                        ## do what ever you want to do for first function ####
                 if request.method=='POST' and 'htmlsubmitbutton2' in request.POST:
                         ## do what ever you want to do for second function ####
                        ## return def post###
                 return render(request, self.template_name, {'form':form,})

/home.html
    <!-- #### form 1 #### -->
    <form action="" method="POST" >
      {% csrf_token %}
      {{ register.as_p }}
    <button type="submit" name="htmlsubmitbutton1">Login</button>
    </form>
    <!--#### form 2 #### -->
    <form action="" method="POST" >
      {% csrf_token %}
      {{ login.as_p }}
    <button type="submit" name="htmlsubmitbutton2">Login</button>
    </form>


问:
Interfaces — What's the point?
The reason for interfaces truly eludes me. From what I understand, it is kind of a work around for the non-existent multi-inheritance which doesn't exist in C# (or so I was told).

All I see is, you predefine some members and functions, which then have to be re-defined in the class again. Thus making the interface redundant. It just feels like syntactic… well, junk to me (Please no offense meant. Junk as in useless stuff).

In the example given below taken from a different C# interfaces thread on stack overflow, I would just create a base class called Pizza instead of an interface.

easy example (taken from a different stack overflow contribution)

```<code>public interface IPizza
{
    public void Order();
}

public class PepperoniPizza : IPizza
{
    public void Order()
    {
        //Order Pepperoni pizza
    }
}

public class HawaiiPizza : IPizza
{
    public void Order()
    {
        //Order HawaiiPizza
    }
}
</code>```

答:
Simple Explanation with analogy

No interface (Example 1):

No interface (Example 2):

With an interface:

The Problem to Solve: What is the purpose of polymorphism?

Analogy: So I'm a foreperson on a construction site. I don't know which tradesperson is going to walk in. But I tell them what to do.

If it's a carpenter I say: build wooden scaffolding.

If it's a plumber, I say: Set up the pipes

If it's a BJP government bureaucrat, I say, three bags full of cash, sir.

The problem with the above approach is that I have to: (i) know who's walking in that door, and depending on who it is, I have to tell them what to do. This typically makes code harder to maintain  or more error prone.

The implications of knowing what to do:

This means if the carpenter's code changes from: BuildScaffolding() to BuildScaffold() (i.e. a slight name change) then I will have to also change the calling class (i.e. the Foreperson class) as well - you'll have to make two changes to the code instead of (basically) just one. With polymorphism you (basically) only need to make one change to achieve the same result.

Secondly you won't have to constantly ask: who are you? ok do this...who are you? ok do that.....polymorphism - it DRYs that code, and is very effective in certain situations:

with polymorphism you can easily add additional classes of tradespeople without changing any existing code. (i.e. the second of the SOLID design principles: Open-close principle).

The solution

Imagine a scenario where, no matter who walks in the door, I can say: "Work()" and they do their respect jobs that they specialise in:  the plumber would deal with pipes, and the electrician would deal with wires, and a bureaucrat could specialise in extracting bribes and making double work for everyone else.

So instead of this:

```<code>if(electrician) then  electrician.FixCablesAndElectricity()

if(plumber) then plumber.IncreaseWaterPressureAndFixLeaks()

if(keralaCustoms) then keralaCustoms.askForBribes()
</code>```

I can do something like this:

```<code>ITradesman tradie = Tradesman.Factory(); // in reality i know it's a plumber, but in the real world you won't know who's on the other side of the tradie assignment.

tradie.Work(); // and then tradie will do the work of a plumber, or electrician etc. depending on what type of tradesman he is. The foreman doesn't need to know anything, apart from telling the anonymous tradie to get to Work()!!
</code>```

What's the benefit?

The benefit is that if the specific job requirements of the carpenter etc change, then the foreperson won't need to change his code - he doesn't need to know or care. All that matters is that the carpenter knows what is meant by Work(). Secondly, if a new type of construction worker comes onto the job site, then all the foreman cares for is if the construction worker (.e.g Welder, Glazier, Tiler etc.) can get some Work() done.

Summary

An interface allows you to get the person to do the work they are assigned to, without you having the knowledge of exactly who they are or the specifics of what they can do. This allows you to easily add new types (of trade), and allows you to effectively changing your code and minimising any cascading effects.

Confused? Hopefully not - if so pls post a commment and I will fix it up for the benefit of the community.

Title: Interfaces — What's the point?

Body:
The reason for interfaces truly eludes me. From what I understand, it is kind of a work around for the non-existent multi-inheritance which doesn't exist in C# (or so I was told).

All I see is, you predefine some members and functions, which then have to be re-defined in the class again. Thus making the interface redundant. It just feels like syntactic… well, junk to me (Please no offense meant. Junk as in useless stuff).

In the example given below taken from a different C# interfaces thread on stack overflow, I would just create a base class called Pizza instead of an interface.

easy example (taken from a different stack overflow contribution)

public interface IPizza
{
    public void Order();
}

public class PepperoniPizza : IPizza
{
    public void Order()
    {
        //Order Pepperoni pizza
    }
}

public class HawaiiPizza : IPizza
{
    public void Order()
    {
        //Order HawaiiPizza
    }
}

Body:
Simple Explanation with analogy

No interface (Example 1):

No interface (Example 2):

With an interface:

The Problem to Solve: What is the purpose of polymorphism?

Analogy: So I'm a foreperson on a construction site. I don't know which tradesperson is going to walk in. But I tell them what to do.

If it's a carpenter I say: build wooden scaffolding.

If it's a plumber, I say: Set up the pipes

If it's a BJP government bureaucrat, I say, three bags full of cash, sir.

The problem with the above approach is that I have to: (i) know who's walking in that door, and depending on who it is, I have to tell them what to do. This typically makes code harder to maintain  or more error prone.

The implications of knowing what to do:

This means if the carpenter's code changes from: BuildScaffolding() to BuildScaffold() (i.e. a slight name change) then I will have to also change the calling class (i.e. the Foreperson class) as well - you'll have to make two changes to the code instead of (basically) just one. With polymorphism you (basically) only need to make one change to achieve the same result.

Secondly you won't have to constantly ask: who are you? ok do this...who are you? ok do that.....polymorphism - it DRYs that code, and is very effective in certain situations:

with polymorphism you can easily add additional classes of tradespeople without changing any existing code. (i.e. the second of the SOLID design principles: Open-close principle).

The solution

Imagine a scenario where, no matter who walks in the door, I can say: "Work()" and they do their respect jobs that they specialise in:  the plumber would deal with pipes, and the electrician would deal with wires, and a bureaucrat could specialise in extracting bribes and making double work for everyone else.

So instead of this:

if(electrician) then  electrician.FixCablesAndElectricity()

if(plumber) then plumber.IncreaseWaterPressureAndFixLeaks()

if(keralaCustoms) then keralaCustoms.askForBribes()

I can do something like this:

ITradesman tradie = Tradesman.Factory(); // in reality i know it's a plumber, but in the real world you won't know who's on the other side of the tradie assignment.

tradie.Work(); // and then tradie will do the work of a plumber, or electrician etc. depending on what type of tradesman he is. The foreman doesn't need to know anything, apart from telling the anonymous tradie to get to Work()!!

What's the benefit?

The benefit is that if the specific job requirements of the carpenter etc change, then the foreperson won't need to change his code - he doesn't need to know or care. All that matters is that the carpenter knows what is meant by Work(). Secondly, if a new type of construction worker comes onto the job site, then all the foreman cares for is if the construction worker (.e.g Welder, Glazier, Tiler etc.) can get some Work() done.

Summary

An interface allows you to get the person to do the work they are assigned to, without you having the knowledge of exactly who they are or the specifics of what they can do. This allows you to easily add new types (of trade), and allows you to effectively changing your code and minimising any cascading effects.

Confused? Hopefully not - if so pls post a commment and I will fix it up for the benefit of the community.


问:
Pig Latin Program Java, problems with vowel inputs
This is my attempt at a simple Pig Latin Word Translator in Java.  If the word starts with a consonant, the consonant is moved to the end of the word and "ay" is added.  If the word starts with a vowel then way is added to the end of the word.  I have difficulty understanding as to why my program is having issues with vowels.

Example:

apple is translated to ppleaay instead of appleway
Yet, van is translated to anvay as it should.

```<code>public class PigLatin
{
    public static String translate (String original) {
        String vowels = "aeiouAEIOU";
        String latin = "";
        for (int i = 0; i < vowels.length() - 1; i++) {
            if (original.charAt(0) == vowels.charAt(i)) {
                latin = original + "way";
            }else {
                latin = original.substring(1) + original.charAt(0) + "ay";
            }
        }
        return latin;
    }

    public static void main(String[] args) {

        System.out.print("What is the word to be translated: ");
        String origWord = IO.readString();
        String newWord = translate(origWord);
        System.out.print("The translated word is: " + newWord);
    }
}
</code>```

答:
The problem is that the if is inside of the for loop. You want that the else branch is only executed if the first character is neither 'a' nor 'e' nor 'i' etc.

This is a simpler way to get the correct result:

```<code>public static String translate(String original) {
    switch (original.toLowerCase().charAt(0)) { // transform to lowercase to simplify code
        case 'a':
        case 'e':
        case 'i':
        case 'o':
        case 'u':
            return original + "way";
        default:
            return original.substring(1) + original.charAt(0) + "ay";
    }
}
</code>```

If you have to transform uppercase words properly:

```<code>public static String translate(String original) {
    switch (original.toLowerCase().charAt(0)) { // transform to lowercase to simplify code
        case 'a':
        case 'e':
        case 'i':
        case 'o':
        case 'u':
            return original + "way";
        default:
            if (original.charAt(0) >= 'a' || original.length() == 1) {
                // lowercase word or word with only 1 character
                return original.substring(1) + original.charAt(0) + "ay";
            } else {
                // uppercase, at least 2 characters
                String first = "" + original.charAt(0);
                String second = "" + original.charAt(1);
                String rest = original.substring(2);
                return second.toUpperCase() + rest + first.toLowerCase() + "ay";
            }
    }
}
</code>```

I assumed that the input has at least one character.

Body:
This is my attempt at a simple Pig Latin Word Translator in Java.  If the word starts with a consonant, the consonant is moved to the end of the word and "ay" is added.  If the word starts with a vowel then way is added to the end of the word.  I have difficulty understanding as to why my program is having issues with vowels.

Example:

apple is translated to ppleaay instead of appleway
Yet, van is translated to anvay as it should.

public class PigLatin
{
    public static String translate (String original) {
        String vowels = "aeiouAEIOU";
        String latin = "";
        for (int i = 0; i < vowels.length() - 1; i++) {
            if (original.charAt(0) == vowels.charAt(i)) {
                latin = original + "way";
            }else {
                latin = original.substring(1) + original.charAt(0) + "ay";
            }
        }
        return latin;
    }

    public static void main(String[] args) {

        System.out.print("What is the word to be translated: ");
        String origWord = IO.readString();
        String newWord = translate(origWord);
        System.out.print("The translated word is: " + newWord);
    }
}

Body:
The problem is that the if is inside of the for loop. You want that the else branch is only executed if the first character is neither 'a' nor 'e' nor 'i' etc.

This is a simpler way to get the correct result:

public static String translate(String original) {
    switch (original.toLowerCase().charAt(0)) { // transform to lowercase to simplify code
        case 'a':
        case 'e':
        case 'i':
        case 'o':
        case 'u':
            return original + "way";
        default:
            return original.substring(1) + original.charAt(0) + "ay";
    }
}

If you have to transform uppercase words properly:

public static String translate(String original) {
    switch (original.toLowerCase().charAt(0)) { // transform to lowercase to simplify code
        case 'a':
        case 'e':
        case 'i':
        case 'o':
        case 'u':
            return original + "way";
        default:
            if (original.charAt(0) >= 'a' || original.length() == 1) {
                // lowercase word or word with only 1 character
                return original.substring(1) + original.charAt(0) + "ay";
            } else {
                // uppercase, at least 2 characters
                String first = "" + original.charAt(0);
                String second = "" + original.charAt(1);
                String rest = original.substring(2);
                return second.toUpperCase() + rest + first.toLowerCase() + "ay";
            }
    }
}

I assumed that the input has at least one character.