问:
Sort data in a text file in alphabetical order - Java
I want the output to list the userNameGenerator in alphabetical order. I converted the HashSet into an ArrayList because sets cannot be sorted, so I changed it to an ArrayList to sort out the list in alphabetical order. I used Collections.sort to sort the list of strings in alphabetical order, however, the output is still
the same.

Code I used for alphabetical order:

```<code>List sortedList = new ArrayList(personFile);
Collections.sort(sortedList);
System.out.println();
</code>```

Output:

```<code>Dompteuse -> Imran Sullivan,
Deservedness -> Eadie Jefferson,
Ostracize -> Eadie Jefferson,
Abattoir -> Angel Whitehouse,
Choreography -> Imran Sullivan,Taylor Vargas,Priya Oliver,
Goodfella -> Khalil Person,Eadie Jefferson,
Frolicwas -> Taylor Vargas,
DarknianIdeal -> Sophia Jeffery,Clyde Calderon,Taylor Vargas,Liyah Navarro,
Cremaster -> Aryan Hess,
Reliable -> Imran Sullivan,Aryan Hess,Angel Whitehouse,Priya Oliver,
Hootenany -> Clyde Calderon,
Acrimony -> Taylor Vargas,
</code>```

Full Code:

```<code>import java.util.*;
import java.io.*;

public class Codes {
    public static void main(String[] args) {
        List<Codes2> personFile = new ArrayList<>();

        try {
            BufferedReader br = new BufferedReader(new FileReader("person-data.txt"));
            String fileRead = br.readLine();
            while (fileRead != null) {
                String[] personData = fileRead.split(":");
                String personName = personData[0];
                String userNameGenerator = personData[1];
                Codes2 personObj = new Codes2(personName, userNameGenerator);
                personFile.add(personObj);
                fileRead = br.readLine();
            }
            br.close();
        }

        catch (FileNotFoundException ex) {
            System.out.println("File not found!");
        }

        catch (IOException ex) {
            System.out.println("An error has occured: " + ex.getMessage());
        }

        Set<String> newStrSet = new HashSet<>();
        for(int i = 0; i < personFile.size(); i++){
            String[] regionSplit = personFile.get(i).getUserNameGenerator().split(", ");
            for(int j = 0; j < regionSplit.length; j++){
                newStrSet.add(regionSplit[j]);
            }
        }

        for (String s: newStrSet) {
            System.out.printf("%s -> ", s);
            for (Codes2 p: personFile) {
                if (p.getUserNameGenerator().contains(s)) {
                    System.out.printf("%s, ", p.getPersonName());
                }
            }
            List sortedList = new ArrayList(personFile);
            Collections.sort(sortedList);
            System.out.println();
        }
    }
}
</code>```

Person Class:

```<code>public class Codes2 implements Comparable<Codes2> {
    private String personName;
    private String userNameGenerator;

    public Codes2(String personName, String userNameGenerator) {
        this.personName = personName;
        this.userNameGenerator = userNameGenerator;
    }

    public String getPersonName() {
        return personName;
    }

    public String getUserNameGenerator() {
        return userNameGenerator;
    }

    @Override
    public int compareTo(Codes2 o) {
        return getUserNameGenerator().compareTo(o.getUserNameGenerator());
    }

    public int compare(Object lOCR1, Object lOCR2) {
        return ((Codes2)lOCR1).userNameGenerator
                .compareTo(((Codes2)lOCR2).userNameGenerator);
    }
}
</code>```

Reference: Simple way to sort strings in the (case sensitive) alphabetical order

答:
As @phatfingers commented, a TreeSet will respect the natural order of the entries in the set.

Since Codes2 already implements Comparable, you could simply replace your original HashSet with a TreeSet and call it a day.

Note this from the TreeSet documentation, however:

Note that the ordering maintained by a set (whether or not an explicit
  comparator is provided) must be consistent with equals if it is to
  correctly implement the Set interface. (See Comparable or Comparator
  for a precise definition of consistent with equals.) This is so
  because the Set interface is defined in terms of the equals operation,
  but a TreeSet instance performs all element comparisons using its
  compareTo (or compare) method, so two elements that are deemed equal
  by this method are, from the standpoint of the set, equal. The
  behavior of a set is well-defined even if its ordering is inconsistent
  with equals; it just fails to obey the general contract of the Set
  interface. (emphasis added)

What this means is that, while simply using a TreeSet probably work by itself, you may still want to consider overriding equals() and hashCode() in your Codes2 class so that the ordering behavior is consistent with equals.

Body:
I want the output to list the userNameGenerator in alphabetical order. I converted the HashSet into an ArrayList because sets cannot be sorted, so I changed it to an ArrayList to sort out the list in alphabetical order. I used Collections.sort to sort the list of strings in alphabetical order, however, the output is still
the same.

Code I used for alphabetical order:

List sortedList = new ArrayList(personFile);
Collections.sort(sortedList);
System.out.println();

Output:

Dompteuse -> Imran Sullivan,
Deservedness -> Eadie Jefferson,
Ostracize -> Eadie Jefferson,
Abattoir -> Angel Whitehouse,
Choreography -> Imran Sullivan,Taylor Vargas,Priya Oliver,
Goodfella -> Khalil Person,Eadie Jefferson,
Frolicwas -> Taylor Vargas,
DarknianIdeal -> Sophia Jeffery,Clyde Calderon,Taylor Vargas,Liyah Navarro,
Cremaster -> Aryan Hess,
Reliable -> Imran Sullivan,Aryan Hess,Angel Whitehouse,Priya Oliver,
Hootenany -> Clyde Calderon,
Acrimony -> Taylor Vargas,

Full Code:

import java.util.*;
import java.io.*;

public class Codes {
    public static void main(String[] args) {
        List<Codes2> personFile = new ArrayList<>();

        try {
            BufferedReader br = new BufferedReader(new FileReader("person-data.txt"));
            String fileRead = br.readLine();
            while (fileRead != null) {
                String[] personData = fileRead.split(":");
                String personName = personData[0];
                String userNameGenerator = personData[1];
                Codes2 personObj = new Codes2(personName, userNameGenerator);
                personFile.add(personObj);
                fileRead = br.readLine();
            }
            br.close();
        }

        catch (FileNotFoundException ex) {
            System.out.println("File not found!");
        }

        catch (IOException ex) {
            System.out.println("An error has occured: " + ex.getMessage());
        }

        Set<String> newStrSet = new HashSet<>();
        for(int i = 0; i < personFile.size(); i++){
            String[] regionSplit = personFile.get(i).getUserNameGenerator().split(", ");
            for(int j = 0; j < regionSplit.length; j++){
                newStrSet.add(regionSplit[j]);
            }
        }

        for (String s: newStrSet) {
            System.out.printf("%s -> ", s);
            for (Codes2 p: personFile) {
                if (p.getUserNameGenerator().contains(s)) {
                    System.out.printf("%s, ", p.getPersonName());
                }
            }
            List sortedList = new ArrayList(personFile);
            Collections.sort(sortedList);
            System.out.println();
        }
    }
}

Person Class:

public class Codes2 implements Comparable<Codes2> {
    private String personName;
    private String userNameGenerator;

    public Codes2(String personName, String userNameGenerator) {
        this.personName = personName;
        this.userNameGenerator = userNameGenerator;
    }

    public String getPersonName() {
        return personName;
    }

    public String getUserNameGenerator() {
        return userNameGenerator;
    }

    @Override
    public int compareTo(Codes2 o) {
        return getUserNameGenerator().compareTo(o.getUserNameGenerator());
    }

    public int compare(Object lOCR1, Object lOCR2) {
        return ((Codes2)lOCR1).userNameGenerator
                .compareTo(((Codes2)lOCR2).userNameGenerator);
    }
}

Reference: Simple way to sort strings in the (case sensitive) alphabetical order


来源: stackexchange

问:
No webhook calls for deleted draft envelopes
I saw this question Deleted Draft Envelopes have inaccurate status about deleted drafts, but I wanted to check if that's also true for webhooks.

If I create Draft Envelope in DocuSign from my application, and then user deletes that Envelope in DocuSign, will any webhook event fire?

These are the event notifications that I have specified when Draft Envelope is created or Envelope is sent:

```<code>{
  "eventNotification": {
    "envelopeEvents": [
      { "envelopeEventStatusCode": "completed" },
      { "envelopeEventStatusCode": "declined"  },
      { "envelopeEventStatusCode": "voided"    }
    ]
  }
}
</code>```

I receive no webhook calls when draft is deleted.

But I do receive webhook calls from Docusign when Envelope is sent and

completed

declined

voided

答:
The behavior that's described in the other SO post that you've linked to (Deleted Draft Envelopes have inaccurate status) is 'by design'.  That is, when a new Envelope is created/saved (but not sent), it's considered a draft Envelope and its status will be created. If the draft Envelope is subsequently deleted without ever being sent, its status will still be created -- there is no distinct status value that indicates a deleted draft Envelope.

Since webhooks fire in response to change in Envelope (or Recipient) status, and there is no change in status when a draft Envelope is deleted, you will never receive a webhook notification when a draft Envelope is deleted.

The behavior you've described in your post is 'by design' (as expected) re the event notifications that you've specified and the webhook calls you're receiving in response to the specified Envelope events.

ContentLicense: CC BY-SA 3.0

Body:
I saw this question Deleted Draft Envelopes have inaccurate status about deleted drafts, but I wanted to check if that's also true for webhooks.

If I create Draft Envelope in DocuSign from my application, and then user deletes that Envelope in DocuSign, will any webhook event fire?

These are the event notifications that I have specified when Draft Envelope is created or Envelope is sent:

{
  "eventNotification": {
    "envelopeEvents": [
      { "envelopeEventStatusCode": "completed" },
      { "envelopeEventStatusCode": "declined"  },
      { "envelopeEventStatusCode": "voided"    }
    ]
  }
}

I receive no webhook calls when draft is deleted.

But I do receive webhook calls from Docusign when Envelope is sent and

completed

declined

voided


问:
Why different inferred dtype of pandas.Series with defined index?
Why do the following 2 statements generate a different dtype?

```<code>pd.Series({0: 1001, 1: 1002, 2: 1003})

0     1001
1     1002
2     1003
dtype: int64

pd.Series({0: 1001, 2: 1002, 4: 1003}, index=range(3))

0    1001.0
1       NaN
2    1002.0
dtype: float64
</code>```

The second Series replaces the dict index by a new range. I don't see why it should generate a different dtype?

答: NaN is used to represent missing data. NaN is also a floating-point value. So for a Series to contain NaN, it must have a dtype capable of holding floating-point values (such as float64 or object, but not int64).

Body:
Why do the following 2 statements generate a different dtype?

pd.Series({0: 1001, 1: 1002, 2: 1003})

0     1001
1     1002
2     1003
dtype: int64

pd.Series({0: 1001, 2: 1002, 4: 1003}, index=range(3))

0    1001.0
1       NaN
2    1002.0
dtype: float64

The second Series replaces the dict index by a new range. I don't see why it should generate a different dtype?


问:
Using nested IF/AND statements in Sheets in a single cell
I'm trying to create a formula that looks at a cell and determines what range the cell is between and then fills another cell with a specific value depending on the target cell's value. This is the formula I've created:

```<code>=IF(AND(C4>0,C4<5,1,IF(AND(C4>=5,C4<8,2,IF(C4>=8,3)))))
</code>```

Where C4 is the number of hours an employee worked in one day. I'm trying to determine if they were eligible for 1, 2 or 3 10 minute breaks and assign that value to C6.

What I'm getting is this message:

Error

Wrong number of arguments to IF. Expected between 2 and 3 arguments,
  but got 1 arguments.

How do I fix this?

答:
IF() function should have two parameters and optionally a third one.

IF(logical_expression, value_if_true, value_if_false)

Body:
I'm trying to create a formula that looks at a cell and determines what range the cell is between and then fills another cell with a specific value depending on the target cell's value. This is the formula I've created:

=IF(AND(C4>0,C4<5,1,IF(AND(C4>=5,C4<8,2,IF(C4>=8,3)))))

Where C4 is the number of hours an employee worked in one day. I'm trying to determine if they were eligible for 1, 2 or 3 10 minute breaks and assign that value to C6.

What I'm getting is this message:

Error

Wrong number of arguments to IF. Expected between 2 and 3 arguments,
  but got 1 arguments.

How do I fix this?


问:
Finding n-grams in tm does not work following package updates
I had some text-mining code in R using the tm package that was working well.  Then, I updated both R along with the tm and R-Weka packages.  Now, the code does not work, and I am not sure why.

My original guide for the code came from: https://gist.github.com/benmarwick/6127413

Neither this code (linked above) nor my code (below) gives the desired results at this point.  When my code executed successfully (under previous versions of the packages),
it provide n-grams that involved a specific, key word.  It would also provide an ordered list of words according to their distance from the key word within the set of n-grams.

There are two specific problems:

One tm feature that is generating an error each time (that may be causing the next/second problem) is the PlainTextDocument.  That line of code is:

eventdocs <- tm_map(eventdocs, PlainTextDocument)

The next line of code is:

```<code>eventdtm <- DocumentTermMatrix(eventdocs)
</code>```

When trying to create the document-text matrix (eventdtm), the code gives the error:

Error in simple_triplet_matrix(i, j, v, nrow = length(terms), ncol = length(corpus),  :
  'i, j' invalid

I have updated everything, including java, and still this error is arising.

I remarked-out the PlainTextDocument code as the text I am using is already in .txt format, because I found some who said this step was not necessary.  When I do this, the document-text matrix is formed (or seems to be formed accurately). But I would like to resolve this error because I previously encountered problems when that line did not execute.

But, regardless of this, there seems to be a problem in the formation of the n-grams.  The first block is the most suspect to me.  I am not sure the NGramTokenizer is doing what it should.

That code is:

```<code>span <- 4
span1 <- 1 + span * 2
ngramTokenizer <- function(x) NGramTokenizer(x, Weka_control(min = span1, max = span1))
dtmevents <- TermDocumentMatrix(eventdocs, control = list(tokenize = ngramTokenizer))

#find ngrams that have the key word of interest
word <- "keyword"
subset_ngrams <- dtmevents$dimnames$Terms[grep(word, dtmevents$dimnames$Terms)]

subset_ngrams <- subset_ngrams[sapply(subset_ngrams, function(i) {
tmp <- unlist(strsplit(i, split=" "))
tmp <- tmp[length(tmp) - span]
tmp} == word)]

allwords <- paste(subset_ngrams, collapse = " ")
uniques <- unique(unlist(strsplit(allwords, split=" ")))
</code>```

The uniques set of words is just the key word of interest, with all of the other high-frequency collocates removed (at this point, I know the code is not working).  Any help or leads would be appreciated.  It took a long time to get things working originally.  Then, with the updates, I'm out of action.  Thank you.

答:
It's tm package version issue.
You need to install version 0.6-2.
Solutions:

Code - faster:

require(devtools)
install_version("tm", version = "0.6-2", repos = "http://cran.r-project.org")

If that doesn't work, download the package and install it manually.

Body:
I had some text-mining code in R using the tm package that was working well.  Then, I updated both R along with the tm and R-Weka packages.  Now, the code does not work, and I am not sure why.

My original guide for the code came from: https://gist.github.com/benmarwick/6127413

Neither this code (linked above) nor my code (below) gives the desired results at this point.  When my code executed successfully (under previous versions of the packages),
it provide n-grams that involved a specific, key word.  It would also provide an ordered list of words according to their distance from the key word within the set of n-grams.

There are two specific problems:

One tm feature that is generating an error each time (that may be causing the next/second problem) is the PlainTextDocument.  That line of code is:

eventdocs <- tm_map(eventdocs, PlainTextDocument)

The next line of code is:

eventdtm <- DocumentTermMatrix(eventdocs)

When trying to create the document-text matrix (eventdtm), the code gives the error:

Error in simple_triplet_matrix(i, j, v, nrow = length(terms), ncol = length(corpus),  :
  'i, j' invalid

I have updated everything, including java, and still this error is arising.

I remarked-out the PlainTextDocument code as the text I am using is already in .txt format, because I found some who said this step was not necessary.  When I do this, the document-text matrix is formed (or seems to be formed accurately). But I would like to resolve this error because I previously encountered problems when that line did not execute.

But, regardless of this, there seems to be a problem in the formation of the n-grams.  The first block is the most suspect to me.  I am not sure the NGramTokenizer is doing what it should.

That code is:

span <- 4
span1 <- 1 + span * 2
ngramTokenizer <- function(x) NGramTokenizer(x, Weka_control(min = span1, max = span1))
dtmevents <- TermDocumentMatrix(eventdocs, control = list(tokenize = ngramTokenizer))

#find ngrams that have the key word of interest
word <- "keyword"
subset_ngrams <- dtmevents$dimnames$Terms[grep(word, dtmevents$dimnames$Terms)]

subset_ngrams <- subset_ngrams[sapply(subset_ngrams, function(i) {
tmp <- unlist(strsplit(i, split=" "))
tmp <- tmp[length(tmp) - span]
tmp} == word)]

allwords <- paste(subset_ngrams, collapse = " ")
uniques <- unique(unlist(strsplit(allwords, split=" ")))

The uniques set of words is just the key word of interest, with all of the other high-frequency collocates removed (at this point, I know the code is not working).  Any help or leads would be appreciated.  It took a long time to get things working originally.  Then, with the updates, I'm out of action.  Thank you.


问:
What is the difference between MobileFirst Services Starter and Mobile Foundation service in IBM Cloud(Bluemix)
What is the difference between MobileFirst Services Starter and Mobile Foundation service in IBM Cloud(Bluemix).

Is Mobilefist Services Starter also contain Mobilefirst service
As I can see Mobilefirst is present in Mobile foundation services.

答:
https://console.bluemix.net/developer/mobile (easiest way to get started for mobile)

The MobileFirst Services Starter is a boilerplate Node.js app which includes a few mobile services (App ID, Push Notifcations, Mobile Analytics, and Cloudant - classic MBaaS pattern). This boilerplate does not include Mobile Foundation as one of the services.

Mobile Foundation is another mobile service which provides a way to quickly set up a MobileFirst server environment on the IBM Cloud. You can then develop, test, and manage mobile apps from this cloud environment.


问:
Stuck in a while loop in python
I'm very new to python so bear with me. I have this code below which I've inserted a while loop to make sure every time a name is given it checks to verify that name is in the csv and then if it isn't it gives and error and asks for a new name. My problem is that I can't seem to get out of the loop. Even with a new name that I know for a fact is in the csv it still sticks in the loop. My question is how can I get this code to run through a loop and verify the name is in there? any help would be great. I am even open to changing the entire code if there's a better way to write this.

Here's what I got:

```<code>import csv

full_name = input('Enter your full name: ').lower()

with open('Report1.csv') as csvfile:
    hour_summation = {}
    read_csv = csv.reader(csvfile, delimiter=',')
    for row in read_csv:
        while (' '.join((row[0], row[1]))).lower() != full_name.strip().lower():
            print('Name is not in system')
            full_name = input('Enter your full name: ').lower()
        if(' '.join((row[0], row[1]))).lower() == full_name.strip().lower():
            hour_summation[row[2]] = hour_summation.get(row[2], 0) + int(float(row[3]))
print('This is {} full hours report:'.format(full_name))
for k, v in hour_summation.items():
    print(k + ': ' + str(v) + ' hours')
</code>```

Here's the result when I give an input:
fyi. Steve Miller is not in the csv file so that first response is correct. However, Sri Mantri is in the file and it should continue on and print out all the listings under her name.

```<code>Enter your full name: Steve Miller
Name is not in system
Enter your full name: Sri Mantri
Name is not in system
</code>```

Here's what the output should look like when the code runs.

```<code>Enter your full name: Sri mantri
This is sri mantri full hours report:
Beeline Blank: 28 hours
SRV-0001 Service Requests for Base and Direct Services: 4 hours
SUP-0001 Support Requests with a CISM Ticket: 129 hours
SUP-2503 Web Application Maintenance & Support: 72 hours
0026184229 Margin Controlling Java Rewrite: 4 hours
0033472751 PRE-AFE 2017 - CMS Enhancements: 2 hours
0033472863 PRE-AFE 2017 - BPM Enhancements: 67 hours
APP-10008 Pre-Series (Non-Mainframe): 4 hours
APP-10146 Logistics (Non-Mainframe): 3 hours
APP-10195 Vehicle Labor System (Mainframe): 3 hours
APP-10354 Web PartsPro (Non-Mainframe): 1 hours
APP-10431 VIPService (Non-Mainframe): 1 hours
APP-10432 VIPService (Mainframe): 3 hours
APP-10536 Truck Invoice Adjustments (Mainframe): 2 hours
</code>```

and the csv looks like this:

```<code>First Name  Last Name   Activity    Hours
Sri Mantri  SUP-2503 Web Application Maintenance & Support  11
Sri Mantri  SUP-2503 Web Application Maintenance & Support  3
Sri Mantri  SUP-2503 Web Application Maintenance & Support  5
Sri Mantri  SUP-2503 Web Application Maintenance & Support  2
Jeff    Moore   SUP-2503 Web Application Maintenance & Support  3
David   Ayers   SUP-2507  NAFTA MFTS OS Support 10
Prasanth    Musunuru    0020826809 Vertex 6.0 at the NDC    4
Prasanth    Musunuru    0020826809 Vertex 6.0 at the NDC    3
Prasanth    Musunuru    0020826809 Vertex 6.0 at the NDC    1
Prasanth    Musunuru    0020826809 Vertex 6.0 at the NDC    1
Jeff    Moore   0024480049 Fuel Tanks (infrastructure) - time tracking  1
Jeff    Moore   0024480049 Fuel Tanks (infrastructure) - time tracking  1
Jeff    Moore   0024480049 Fuel Tanks (infrastructure) - time tracking  4
</code>```

答:
```<code>import csv

full_name = input('Enter your full name: ').lower()
bucle = True
with open('Report1.csv') as csvfile:
    hour_summation = {}
    read_csv = csv.reader(csvfile, delimiter=',')
    while bucle:
        for row in read_csv:
            if(' '.join((row[0], row[1]))).lower() == full_name.strip().lower():
                hour_summation[row[2]] = hour_summation.get(row[2], 0) + int(float(row[3]))
                bucle = False
        if bucle:
            print('Name is not in system')
            full_name = input('Enter your full name: ').lower()
            csvfile.seek(0)

print('This is {} full hours report:'.format(full_name))
for k, v in hour_summation.items():
print(k + ': ' + str(v) + ' hours')
</code>```

Title: Stuck in a while loop in python

Body:
I'm very new to python so bear with me. I have this code below which I've inserted a while loop to make sure every time a name is given it checks to verify that name is in the csv and then if it isn't it gives and error and asks for a new name. My problem is that I can't seem to get out of the loop. Even with a new name that I know for a fact is in the csv it still sticks in the loop. My question is how can I get this code to run through a loop and verify the name is in there? any help would be great. I am even open to changing the entire code if there's a better way to write this.

Here's what I got:

import csv

full_name = input('Enter your full name: ').lower()

with open('Report1.csv') as csvfile:
    hour_summation = {}
    read_csv = csv.reader(csvfile, delimiter=',')
    for row in read_csv:
        while (' '.join((row[0], row[1]))).lower() != full_name.strip().lower():
            print('Name is not in system')
            full_name = input('Enter your full name: ').lower()
        if(' '.join((row[0], row[1]))).lower() == full_name.strip().lower():
            hour_summation[row[2]] = hour_summation.get(row[2], 0) + int(float(row[3]))
print('This is {} full hours report:'.format(full_name))
for k, v in hour_summation.items():
    print(k + ': ' + str(v) + ' hours')

Here's the result when I give an input:
fyi. Steve Miller is not in the csv file so that first response is correct. However, Sri Mantri is in the file and it should continue on and print out all the listings under her name.

Enter your full name: Steve Miller
Name is not in system
Enter your full name: Sri Mantri
Name is not in system

Here's what the output should look like when the code runs.

Enter your full name: Sri mantri
This is sri mantri full hours report:
Beeline Blank: 28 hours
SRV-0001 Service Requests for Base and Direct Services: 4 hours
SUP-0001 Support Requests with a CISM Ticket: 129 hours
SUP-2503 Web Application Maintenance & Support: 72 hours
0026184229 Margin Controlling Java Rewrite: 4 hours
0033472751 PRE-AFE 2017 - CMS Enhancements: 2 hours
0033472863 PRE-AFE 2017 - BPM Enhancements: 67 hours
APP-10008 Pre-Series (Non-Mainframe): 4 hours
APP-10146 Logistics (Non-Mainframe): 3 hours
APP-10195 Vehicle Labor System (Mainframe): 3 hours
APP-10354 Web PartsPro (Non-Mainframe): 1 hours
APP-10431 VIPService (Non-Mainframe): 1 hours
APP-10432 VIPService (Mainframe): 3 hours
APP-10536 Truck Invoice Adjustments (Mainframe): 2 hours

and the csv looks like this:

First Name  Last Name   Activity    Hours
Sri Mantri  SUP-2503 Web Application Maintenance & Support  11
Sri Mantri  SUP-2503 Web Application Maintenance & Support  3
Sri Mantri  SUP-2503 Web Application Maintenance & Support  5
Sri Mantri  SUP-2503 Web Application Maintenance & Support  2
Jeff    Moore   SUP-2503 Web Application Maintenance & Support  3
David   Ayers   SUP-2507  NAFTA MFTS OS Support 10
Prasanth    Musunuru    0020826809 Vertex 6.0 at the NDC    4
Prasanth    Musunuru    0020826809 Vertex 6.0 at the NDC    3
Prasanth    Musunuru    0020826809 Vertex 6.0 at the NDC    1
Prasanth    Musunuru    0020826809 Vertex 6.0 at the NDC    1
Jeff    Moore   0024480049 Fuel Tanks (infrastructure) - time tracking  1
Jeff    Moore   0024480049 Fuel Tanks (infrastructure) - time tracking  1
Jeff    Moore   0024480049 Fuel Tanks (infrastructure) - time tracking  4


问:
MapStruct and Lombok not working together
Tech Stack being used :

Java 8
MapStruct : 1.2.0.Final
Lombok: 1.16.18
IDE: IntelliJ - Lombok Plugin already installed

Initially, I faced issues when I removed getters and setters and added @Getter and @Setter annotation, mapstruct is not able to find the property and says: Unknown property "id" in result type com.vg.once.dto.OneDto. Did you mean "null"?

I came to know that Lombok 1.16.14 or newer along with MapStruct 1.2.0.Beta1 or newer are compatible and can work together, but my versions are newer then the desired still the issue is arising.

One more solution that I have already tried is running Lombok's Delombok plugin, but still, the same issue is arising.

Below are the project files :

The Entity Object: One.java:

```<code>import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class One {

    private int id;
    private Integer version;
    private int projectId;
    private String title;
    private String code;
    private int sortOrder;

}
</code>```

The DTO Object: OneDTO.java :

```<code>import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class OneDto {

    private int id;
    private Integer version;
    private int projectId;
    private String title;
    private String code;
    private int sortOrder;

}
</code>```

Mapper Class : OneMapper.java

```<code>import org.mapstruct.Mapper;
import org.mapstruct.Mapping;

import com.vg.once.dto.OneDto;
import com.vg.once.entity.One;

@Mapper
public interface OneMapper {

    @Mapping(target="id", source="one.id")
    OneDto createOne (One one);

}
</code>```

pom.xml

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <groupId>com.vg</groupId>
  <artifactId>mapstruct</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>Mapstruct-test</name>

    <properties>
        <java.version>1.8</java.version>
        <org.mapstruct.version>1.2.0.Final</org.mapstruct.version>
        <org.projectlombok.version>1.16.18</org.projectlombok.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${org.projectlombok.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct-jdk8</artifactId>
            <version>${org.mapstruct.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
         <plugin>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok-maven-plugin</artifactId>
                <version>1.16.18.1</version>
                <executions>
                    <execution>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>delombok</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <sourceDirectory>src/main/java</sourceDirectory>
                    <addOutputDirectory>false</addOutputDirectory>
                    <outputDirectory>${project.build.directory}/delombok</outputDirectory>
                    <encoding>UTF-8</encoding>
                    <skip>false</skip>
                    <verbose>false</verbose>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.1</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                    <annotationProcessorPaths>
                        <path>
                            <groupId>org.mapstruct</groupId>
                            <artifactId>mapstruct-processor</artifactId>
                            <version>${org.mapstruct.version}</version>
                        </path>
                    </annotationProcessorPaths>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

Build Trace:

```<code>[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Mapstruct-test 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- lombok-maven-plugin:1.16.18.1:delombok (default) @ mapstruct ---
[INFO] Delombok complete.
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ mapstruct ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.6.1:compile (default-compile) @ mapstruct ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[INFO] Compiling 5 source files to /home/vivekgupta/Documents/workspaces/mapstruct-test/mapstruct/target/classes
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /home/vivekgupta/Documents/workspaces/mapstruct-test/mapstruct/src/main/java/com/vg/once/mapper/OneMapper.java:[12,9] Unknown property "id" in result type com.vg.once.dto.OneDto. Did you mean "null"?
[INFO] 1 error
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.637 s
[INFO] Finished at: 2017-12-06T19:23:53+05:30
[INFO] Final Memory: 19M/235M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.6.1:compile (default-compile) on project mapstruct: Compilation failure
[ERROR] /home/vivekgupta/Documents/workspaces/mapstruct-test/mapstruct/src/main/java/com/vg/once/mapper/OneMapper.java:[12,9] Unknown property "id" in result type com.vg.once.dto.OneDto. Did you mean "null"?
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
</code>```

please share how can i get this working using both Lombok and MapStruct together?

答:
The reason why it does not work is because Maven only uses the MapStruct processor and not the Lombok one. The annotationProcessorPaths tells maven which processors it should use.

The delombok does nothing as you are ending up with 2 files per class and I think that the maven compiler does not see them.

You have 2 options:

Option 1: Add the lombok dependency in the annotationProcessorPaths

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.6.1</version>
    <configuration>
        <source>${java.version}</source>
        <target>${java.version}</target>
        <annotationProcessorPaths>
            <path>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>${org.projectlombok.version}</version>
            </path>
            <!-- This is needed when using Lombok 1.18.16 and above -->
            <path>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok-mapstruct-binding</artifactId>
                <version>0.2.0</version>
            </path>
            <!-- Mapstruct should follow the lombok path(s) -->
            <path>
                <groupId>org.mapstruct</groupId>
                <artifactId>mapstruct-processor</artifactId>
                <version>${org.mapstruct.version}</version>
            </path>
        </annotationProcessorPaths>
    </configuration>
</plugin>
</code>```

Option 2:

Add the mapstruct-processor dependency to your dependencies and remove the annotationProcessorPaths. This way the maven compiler will pick up all the annotation processors that are in your dependencies.

I would advise in using Option 1, as with that you can be certain that you are not using some MapStruct transitive dependencies and internal classes in your code.

Edit:

To make sure that the IntelliJ annotation processing also works you will have to add the mapstruct-processor as a provided dependency due to IDEA-150621. IntelliJ in the moment does not use the annotationProcessorPaths from Maven to configure the project correctly.

Edit 2:

Add information and comment about lombok-mapstruct-binding needed from Lombok 1.18.16.

ContentLicense: CC BY-SA 4.0

Body:
Tech Stack being used :

Java 8
MapStruct : 1.2.0.Final
Lombok: 1.16.18
IDE: IntelliJ - Lombok Plugin already installed

Initially, I faced issues when I removed getters and setters and added @Getter and @Setter annotation, mapstruct is not able to find the property and says: Unknown property "id" in result type com.vg.once.dto.OneDto. Did you mean "null"?

I came to know that Lombok 1.16.14 or newer along with MapStruct 1.2.0.Beta1 or newer are compatible and can work together, but my versions are newer then the desired still the issue is arising.

One more solution that I have already tried is running Lombok's Delombok plugin, but still, the same issue is arising.

Below are the project files :

The Entity Object: One.java:

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class One {

    private int id;
    private Integer version;
    private int projectId;
    private String title;
    private String code;
    private int sortOrder;

}

The DTO Object: OneDTO.java :

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class OneDto {

    private int id;
    private Integer version;
    private int projectId;
    private String title;
    private String code;
    private int sortOrder;

}

Mapper Class : OneMapper.java

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;

import com.vg.once.dto.OneDto;
import com.vg.once.entity.One;

@Mapper
public interface OneMapper {

    @Mapping(target="id", source="one.id")
    OneDto createOne (One one);

}

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <groupId>com.vg</groupId>
  <artifactId>mapstruct</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>Mapstruct-test</name>

    <properties>
        <java.version>1.8</java.version>
        <org.mapstruct.version>1.2.0.Final</org.mapstruct.version>
        <org.projectlombok.version>1.16.18</org.projectlombok.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${org.projectlombok.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct-jdk8</artifactId>
            <version>${org.mapstruct.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
         <plugin>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok-maven-plugin</artifactId>
                <version>1.16.18.1</version>
                <executions>
                    <execution>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>delombok</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <sourceDirectory>src/main/java</sourceDirectory>
                    <addOutputDirectory>false</addOutputDirectory>
                    <outputDirectory>${project.build.directory}/delombok</outputDirectory>
                    <encoding>UTF-8</encoding>
                    <skip>false</skip>
                    <verbose>false</verbose>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.1</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                    <annotationProcessorPaths>
                        <path>
                            <groupId>org.mapstruct</groupId>
                            <artifactId>mapstruct-processor</artifactId>
                            <version>${org.mapstruct.version}</version>
                        </path>
                    </annotationProcessorPaths>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Build Trace:

[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Mapstruct-test 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- lombok-maven-plugin:1.16.18.1:delombok (default) @ mapstruct ---
[INFO] Delombok complete.
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ mapstruct ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.6.1:compile (default-compile) @ mapstruct ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[INFO] Compiling 5 source files to /home/vivekgupta/Documents/workspaces/mapstruct-test/mapstruct/target/classes
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /home/vivekgupta/Documents/workspaces/mapstruct-test/mapstruct/src/main/java/com/vg/once/mapper/OneMapper.java:[12,9] Unknown property "id" in result type com.vg.once.dto.OneDto. Did you mean "null"?
[INFO] 1 error
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.637 s
[INFO] Finished at: 2017-12-06T19:23:53+05:30
[INFO] Final Memory: 19M/235M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.6.1:compile (default-compile) on project mapstruct: Compilation failure
[ERROR] /home/vivekgupta/Documents/workspaces/mapstruct-test/mapstruct/src/main/java/com/vg/once/mapper/OneMapper.java:[12,9] Unknown property "id" in result type com.vg.once.dto.OneDto. Did you mean "null"?
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

please share how can i get this working using both Lombok and MapStruct together?

Body:
The reason why it does not work is because Maven only uses the MapStruct processor and not the Lombok one. The annotationProcessorPaths tells maven which processors it should use.

The delombok does nothing as you are ending up with 2 files per class and I think that the maven compiler does not see them.

You have 2 options:

Option 1: Add the lombok dependency in the annotationProcessorPaths

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.6.1</version>
    <configuration>
        <source>${java.version}</source>
        <target>${java.version}</target>
        <annotationProcessorPaths>
            <path>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>${org.projectlombok.version}</version>
            </path>
            <!-- This is needed when using Lombok 1.18.16 and above -->
            <path>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok-mapstruct-binding</artifactId>
                <version>0.2.0</version>
            </path>
            <!-- Mapstruct should follow the lombok path(s) -->
            <path>
                <groupId>org.mapstruct</groupId>
                <artifactId>mapstruct-processor</artifactId>
                <version>${org.mapstruct.version}</version>
            </path>
        </annotationProcessorPaths>
    </configuration>
</plugin>

Option 2:

Add the mapstruct-processor dependency to your dependencies and remove the annotationProcessorPaths. This way the maven compiler will pick up all the annotation processors that are in your dependencies.

I would advise in using Option 1, as with that you can be certain that you are not using some MapStruct transitive dependencies and internal classes in your code.

Edit:

To make sure that the IntelliJ annotation processing also works you will have to add the mapstruct-processor as a provided dependency due to IDEA-150621. IntelliJ in the moment does not use the annotationProcessorPaths from Maven to configure the project correctly.

Edit 2:

Add information and comment about lombok-mapstruct-binding needed from Lombok 1.18.16.


问:
Returning frequencies of words in a dictionary
I think I have the right idea on how to solve this function, but I'm not sure
why I don't get the desired results shown in the docstring. Can anyone please help me fix this?</p>

```<code>def list_to_dict(word_list):
'''(list of str) -> dict
Given a list of str (a list of English words) return a dictionary that keeps
track of word length and frequency of length. Each key is a word length and
the corresponding value is the number of words in the given list of that
length.
>>> d = list_to_dict(['This', 'is', 'some', 'text'])
>>> d == {2:1, 4:3}
True
>>> d = list_to_dict(['A', 'little', 'sentence', 'to', 'create', 'a',
'dictionary'])
>>> d == {1:2, 6:2, 8:1, 2:1, 10:1}
True
'''
d = {}
count = 0
for i in range(len(word_list)):
length = len(i)
if length not in d:
    count = count + length
    d[length] = {count}
    count += 1
return d
</code>```

答:
You can use dictionary comprehension to iterate over s, which now contains the length of its original elements:

```<code>s = ['A', 'little', 'sentence', 'to', 'create', 'a', 'dictionary']
final_s = {i:len([b for b in s if len(b) == i]) for i in map(len, s)}
</code>```

Output:

```<code>{1: 2, 6: 2, 8: 1, 2: 1, 10: 1}
</code>```

Simply:

```<code>new_d = {}
for i in s:
    new_d[len(i)] = 0
for i in s:
    new_d[len(i)] += 1
</code>```

Output:

```<code>{8: 1, 1: 2, 2: 1, 10: 1, 6: 2}
</code>```

Body:
I think I have the right idea on how to solve this function, but I'm not sure
why I don't get the desired results shown in the docstring. Can anyone please help me fix this?

def list_to_dict(word_list):
'''(list of str) -> dict
Given a list of str (a list of English words) return a dictionary that keeps
track of word length and frequency of length. Each key is a word length and
the corresponding value is the number of words in the given list of that
length.
>>> d = list_to_dict(['This', 'is', 'some', 'text'])
>>> d == {2:1, 4:3}
True
>>> d = list_to_dict(['A', 'little', 'sentence', 'to', 'create', 'a',
'dictionary'])
>>> d == {1:2, 6:2, 8:1, 2:1, 10:1}
True
'''
d = {}
count = 0
for i in range(len(word_list)):
length = len(i)
if length not in d:
    count = count + length
    d[length] = {count}
    count += 1
return d

Body:
You can use dictionary comprehension to iterate over s, which now contains the length of its original elements:

s = ['A', 'little', 'sentence', 'to', 'create', 'a', 'dictionary']
final_s = {i:len([b for b in s if len(b) == i]) for i in map(len, s)}

Output:

{1: 2, 6: 2, 8: 1, 2: 1, 10: 1}

Simply:

new_d = {}
for i in s:
    new_d[len(i)] = 0
for i in s:
    new_d[len(i)] += 1

Output:

{8: 1, 1: 2, 2: 1, 10: 1, 6: 2}


问:
Position element at top right of wrapped text
The following simple scenario illustrates the desired result when the text is not wrapped:

.container {
  height: 300px;
  width: 600px;
}
.container h1 {
  margin-right: 300px;
  position: relative;
}
.container .above {
  font-size: 0.5em;
  position: absolute;
  top: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <h1>
    The Wrapped Text
    <span class="above">Above</span>
  </h1>
</div></code>```

If the margin-right on the
 element is increased slightly (forcing the text to wrap) the Above text is no longer positioned as desired.

.container {
  height: 300px;
  width: 600px;
}
.container h1 {
  margin-right: 350px;
  position: relative;
}
.container .above {
  font-size: 0.5em;
  position: absolute;
  top: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <h1>
    The Wrapped Text
    <span class="above">Above</span>
  </h1>
</div></code>```

It's vertical position is correct, but horizontally it is aligned relative to the right edge of the last word. Is there a way to horizontally align the Above  relative to the right edge of the last word on the longest line? This way the Above text would remain at the top right of the text block at all times (wrapped or single line).

答:
You can try combining display:flex on .container h1 and vertical-align: super on .container .above.

.container {
  height: 300px;
  width: 600px;
}
.container h1 {
  display: flex;
  margin-right: 350px;
  position: relative;
}
.container .above {
  font-size: 0.5em;
  vertical-align: super;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <h1>
    The Wrapped Text
    <span class="above">Above</span>
  </h1>
</div></code>```

Body:
The following simple scenario illustrates the desired result when the text is not wrapped:

.container {
  height: 300px;
  width: 600px;
}
.container h1 {
  margin-right: 300px;
  position: relative;
}
.container .above {
  font-size: 0.5em;
  position: absolute;
  top: 0;
}

    The Wrapped Text
    Above

If the margin-right on the
 element is increased slightly (forcing the text to wrap) the Above text is no longer positioned as desired.

.container {
  height: 300px;
  width: 600px;
}
.container h1 {
  margin-right: 350px;
  position: relative;
}
.container .above {
  font-size: 0.5em;
  position: absolute;
  top: 0;
}

    The Wrapped Text
    Above

It's vertical position is correct, but horizontally it is aligned relative to the right edge of the last word. Is there a way to horizontally align the Above  relative to the right edge of the last word on the longest line? This way the Above text would remain at the top right of the text block at all times (wrapped or single line).

Body:
You can try combining display:flex on .container h1 and vertical-align: super on .container .above.

.container {
  height: 300px;
  width: 600px;
}
.container h1 {
  display: flex;
  margin-right: 350px;
  position: relative;
}
.container .above {
  font-size: 0.5em;
  vertical-align: super;
}

<div class="container">
  <h1>
    The Wrapped Text
    <span class="above">Above</span>
  </h1>
</div>


问:
vue reload child component
I'm using vue, version 2.5.8

I want to reload child component's, or reload parent and then force children components to reload.

I was trying to use this.$forceUpdate() but this is not working.

Do You have any idea how to do this?

答:
If the children are dynamically created by a v-for or something, you could clear the array and re-assign it, and the children would all be re-created.

To simply have existing components respond to a signal, you want to pass an event bus as a prop, then emit an event to which they will respond. The normal direction of events is up, but it is sometimes appropriate to have them go down.

new Vue({
  el: '#app',
  data: {
    bus: new Vue()
  },
  components: {
    child: {
      template: '#child-template',
      props: ['bus'],
      data() {
        return {
          value: 0
        };
      },
      methods: {
        increment() {
          this.value += 1;
        },
        reset() {
          this.value = 0;
        }
      },
      created() {
        this.bus.$on('reset', this.reset);
      }
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="app">
  <child :bus="bus">
  </child>
  <child :bus="bus">
  </child>
  <child :bus="bus">
  </child>
  <button @click="() => bus.$emit('reset')">Reset</button>
</div>

<template id="child-template">
  <div>
  {{value}} <button @click="increment">More!</button>
  </div>
</template></code>```

Title: vue reload child component

Body:
If the children are dynamically created by a v-for or something, you could clear the array and re-assign it, and the children would all be re-created.

To simply have existing components respond to a signal, you want to pass an event bus as a prop, then emit an event to which they will respond. The normal direction of events is up, but it is sometimes appropriate to have them go down.

new Vue({
  el: '#app',
  data: {
    bus: new Vue()
  },
  components: {
    child: {
      template: '#child-template',
      props: ['bus'],
      data() {
        return {
          value: 0
        };
      },
      methods: {
        increment() {
          this.value += 1;
        },
        reset() {
          this.value = 0;
        }
      },
      created() {
        this.bus.$on('reset', this.reset);
      }
    }
  }
});

<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="app">
  <child :bus="bus">
  </child>
  <child :bus="bus">
  </child>
  <child :bus="bus">
  </child>
  <button @click="() => bus.$emit('reset')">Reset</button>
</div>

<template id="child-template">
  <div>
  {{value}} <button @click="increment">More!</button>
  </div>
</template>


问:
Builder Vs Decorator pattern
From When would you use the Builder Pattern?,

It is said that builder pattern is appropriate for Pizza example.

Why not Decorator ?
by treating Cheese, Pepperoni, Bacon as additional decorations on a base pizza.

Is it for the reason that Cheese/Pepperoni have to be built seperately. I don't think, they need to be built seperately as they can be available readymade.

Pls clarify.
Am also looking for a good real-world example of decorator pattern and reason why it is the apt for that particular example. Thank you.

答:
You are confusing two very different things. GoF classifies Builder as a creational pattern, while Decorator is a structural pattern. They are described as follows (Gamma et al, page 1):

Builder (97) Separate the construction of a complex object from its representation so that the same construction process can create different representations.

Decorator (175) Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

Note the emphasis on the decorator. It's a flexible alternative to subclassing. Subclassing is used to model an is-a relationship. Cheese is not a pizza. The pizza is composed of a number of ingredients, and that is usually modeled using composition.

The builder pattern is relevant here because there are such a vast number of ingredients that the need arises to construct them in a standardized way.

To take a real world example of a decorator, I recently wanted to log the queries executed using jdbc in my java application. I accomplished this by implementing a class called LoggingConnection which extended the Connection interface.

```<code>public class LoggingConnection implements Connection
{
    public static class LogEntry
    {
        public String sql;
        public int invocationCount;
        public double avgTime;
        public double maxTime;
    }

    private Connection delegate;

    private Map<String, LogEntry> log;

    public LoggingConnection(Connection delegate)
    {
        this.delegate = delegate;
        this.log = new HashMap<String, LogEntry>();
    }

    public Map<String, LogEntry> getLog()
    {
        return log;
    }

    @Override
    public void clearWarnings()
    throws SQLException
    {
        delegate.clearWarnings();
    }

    @Override
    public void close()
    throws SQLException
    {
        delegate.close();
    }

    // forwarding declarations to all other methods declared in the interface
    ...
}
</code>```

This allows me to pass a concrete implemention of a connection, and extend its functionality at runtime. Subclassing would be problematic in this context, because you don't necessarily know what connection object is actually returned. This is because it's constructed for you using the DriverManager factory:

```<code>Connection conn = DriverManger.getConnection(dsn);
</code>```

The conn object is in this case an implementation contained in the driver, which I generelly don't know the name of. The beuty of the decorator approach is that I don't have to know, and that it isn't tied to a specific implementation.

ContentLicense: CC BY-SA 2.5

Title: Builder Vs Decorator pattern

Body:
You are confusing two very different things. GoF classifies Builder as a creational pattern, while Decorator is a structural pattern. They are described as follows (Gamma et al, page 1):

Builder (97) Separate the construction of a complex object from its representation so that the same construction process can create different representations.

Decorator (175) Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

Note the emphasis on the decorator. It's a flexible alternative to subclassing. Subclassing is used to model an is-a relationship. Cheese is not a pizza. The pizza is composed of a number of ingredients, and that is usually modeled using composition.

The builder pattern is relevant here because there are such a vast number of ingredients that the need arises to construct them in a standardized way.

To take a real world example of a decorator, I recently wanted to log the queries executed using jdbc in my java application. I accomplished this by implementing a class called LoggingConnection which extended the Connection interface.

public class LoggingConnection implements Connection
{
    public static class LogEntry
    {
        public String sql;
        public int invocationCount;
        public double avgTime;
        public double maxTime;
    }

    private Connection delegate;

    private Map<String, LogEntry> log;

    public LoggingConnection(Connection delegate)
    {
        this.delegate = delegate;
        this.log = new HashMap<String, LogEntry>();
    }

    public Map<String, LogEntry> getLog()
    {
        return log;
    }

    @Override
    public void clearWarnings()
    throws SQLException
    {
        delegate.clearWarnings();
    }

    @Override
    public void close()
    throws SQLException
    {
        delegate.close();
    }

    // forwarding declarations to all other methods declared in the interface
    ...
}

This allows me to pass a concrete implemention of a connection, and extend its functionality at runtime. Subclassing would be problematic in this context, because you don't necessarily know what connection object is actually returned. This is because it's constructed for you using the DriverManager factory:

Connection conn = DriverManger.getConnection(dsn);

The conn object is in this case an implementation contained in the driver, which I generelly don't know the name of. The beuty of the decorator approach is that I don't have to know, and that it isn't tied to a specific implementation.


问:
File upload with Meteor + React failing silently
Im using React and Meteor. I need to allow users to upload profile images.

Ive installed these packages:

```<code>cfs:standard-packages
cfs:filesystem
</code>```

Ive defined my collection in images.js:

```<code>export const Images = new FS.Collection('images', {
  stores: [new FS.Store.FileSystem('images', { path: '~/uploads' })],
});
</code>```

This file isn't imported into the server JavaScript.

It is imported into my React component (code below). My console.log does log the file and doesn't show me any errors. I also dont see any errors in Meteor's terminal.

```<code>import { Images } from '../../../api/images';

  const imgFormSubmit = e => {
    e.preventDefault();

    const file = e.target.profile.files[0];
    console.log(file);

    Images.insert(file, function(err, fileObj) {
      //If !err, we have inserted new doc with ID fileObj._id, and
      //kicked off the data upload using HTTP
    });
  };
</code>```

However when I look at MongoDB there isnt any table called images so nothing has been saved. I also don't have any file or uploads folder added to my filesystem.

I have autopublish and insecure packages enabled.

答:
If you want to defined a managed collection you need to do it in both your client and server code. cfs might be a bit unobvious because it doesn't take the form of a normal collection definition but it's doing it under the hood.

You need to import images.js into your server startup code.

Body:
Im using React and Meteor. I need to allow users to upload profile images.

Ive installed these packages:

cfs:standard-packages
cfs:filesystem

Ive defined my collection in images.js:

export const Images = new FS.Collection('images', {
  stores: [new FS.Store.FileSystem('images', { path: '~/uploads' })],
});

This file isn't imported into the server JavaScript.

It is imported into my React component (code below). My console.log does log the file and doesn't show me any errors. I also dont see any errors in Meteor's terminal.

import { Images } from '../../../api/images';

  const imgFormSubmit = e => {
    e.preventDefault();

    const file = e.target.profile.files[0];
    console.log(file);

    Images.insert(file, function(err, fileObj) {
      //If !err, we have inserted new doc with ID fileObj._id, and
      //kicked off the data upload using HTTP
    });
  };

However when I look at MongoDB there isnt any table called images so nothing has been saved. I also don't have any file or uploads folder added to my filesystem.

I have autopublish and insecure packages enabled.


问:
Role-based access control (RBAC) vs. Claims-based access control (CBAC) in ASP.NET MVC
What are the main benefits of using CBAC vs. RBAC? When is it better to use CBAC and when is it better to use RBAC? </p>

<p>I'm trying to understand the general concepts of the CBAC model but the general idea is still not clear for me. </p>

答:
It is also possible to manages roles in a claims manner.

Instead of creating authorisation roles that reflect a business role, create roles that reflect action roles, e.g. CreateCustomer, EditCustomer, DeleteCustomer. Annotate methods as required.

It is not a simple matter to map individuals to a set of action roles, especially as the role list gets larger. Therefore, you'll need to manage the business roles at a lower level of granularity (e.g. Sales, Marketing) and map the business Role to the action roles required. I.e., add a user to a business role and it maps them to the required (action) roles in the existing authorisation table.

You can even override the business role and add a person to an action role directly.

Because you build on top of what already works, you don't undo the existing Authorisation process. You need only a few more tables to implement this approach

Body:
What are the main benefits of using CBAC vs. RBAC? When is it better to use CBAC and when is it better to use RBAC?

I'm trying to understand the general concepts of the CBAC model but the general idea is still not clear for me.


问:
How to pass array as variable outside the wp_query loop in php
Is there a way to pass an array as a variable out of the wp_query loop? I want to collect post meta from the four posts — next week and the following three weeks. To keep the code clean, I thought it'd be easiest to capture the variable and use the data later in the form.

```<code>// Capture next week's week number
$nextweek = date("W", strtotime( "+1 week"));

// Query all custom post types
$menu_args = array(
    'post_type'=>'single_menu',
    'posts_per_page' => -1,
    'orderby' => 'title',
    'order' => 'ASC'
    );

    $menu = new WP_Query( $menu_args ); if ( $menu->have_posts() ) : while ( $menu->have_posts() ) : $menu->the_post();

    // Get custom fields
    $menuids = array( get_post_field( 'week', $post->id ) );
    $titles = array( get_post( $post->id )->post_title );
    $choosefrom = array( get_post_field( 'menu_listing', $post->id ) );
    $selection = array( get_post_field( $checkout_menu, $post->id ) );

    // Create new array with custom fields
    $result = array();
    foreach ( $menuids as $id => $menuid ) {
        $result[$menuid] = array(
            'title'  => $titles[$id],
            'offering'  => $choosefrom[$id],
            'menu' => $selection[$id],
            'delivery'    => 0,
        );
    }

    // Return the arrays for specified weeks
    for ($i = $nextweek; $i<$nextweek+4; $i++) {
    if ( $result[$menuid] == $result[$i] ) {
        print_r( $result );
    }
    }

    endwhile;
    endif;
</code>```

print_r() returns the correct results, my $results array for the next four weeks. However, when I create a variable and call it outside the loop, like below, I only get the last/fourth $result in the array:

```<code>    for ($i = $nextweek; $i<$nextweek+4; $i++) {
    if ( $result[$menuid] == $result[$i] ) {

        $payload = $result;
    }
  }

endwhile;
endif;

print_r( $payload );
</code>```

Same thing happens when I create a new array like so:

```<code>    $payload = array();
    for ($i = $nextweek; $i<$nextweek+4; $i++) {
    if ( $result[$menuid] == $result[$i] ) {

        $payload[] = $result;
    }
  }

endwhile;
endif;

print_r( $payload );
</code>```

If I concatenate the variable like $payload .= $result;, I get ArrayArrayArrayArray returned.

I know I can echo the form inside loop, but would rather take the array as a data variable if at all possible. Am I missing something easy?

答:
$result initialized every loop iteration. Your $result contain only one item. Same think for $payload variable.
Outside of while loop you have only the last item. Good luck</p>

Body:
Is there a way to pass an array as a variable out of the wp_query loop? I want to collect post meta from the four posts — next week and the following three weeks. To keep the code clean, I thought it'd be easiest to capture the variable and use the data later in the form.

// Capture next week's week number
$nextweek = date("W", strtotime( "+1 week"));

// Query all custom post types
$menu_args = array(
    'post_type'=>'single_menu',
    'posts_per_page' => -1,
    'orderby' => 'title',
    'order' => 'ASC'
    );

    $menu = new WP_Query( $menu_args ); if ( $menu->have_posts() ) : while ( $menu->have_posts() ) : $menu->the_post();

    // Get custom fields
    $menuids = array( get_post_field( 'week', $post->id ) );
    $titles = array( get_post( $post->id )->post_title );
    $choosefrom = array( get_post_field( 'menu_listing', $post->id ) );
    $selection = array( get_post_field( $checkout_menu, $post->id ) );

    // Create new array with custom fields
    $result = array();
    foreach ( $menuids as $id => $menuid ) {
        $result[$menuid] = array(
            'title'  => $titles[$id],
            'offering'  => $choosefrom[$id],
            'menu' => $selection[$id],
            'delivery'    => 0,
        );
    }

    // Return the arrays for specified weeks
    for ($i = $nextweek; $i<$nextweek+4; $i++) {
    if ( $result[$menuid] == $result[$i] ) {
        print_r( $result );
    }
    }

    endwhile;
    endif;

print_r() returns the correct results, my $results array for the next four weeks. However, when I create a variable and call it outside the loop, like below, I only get the last/fourth $result in the array:

    for ($i = $nextweek; $i<$nextweek+4; $i++) {
    if ( $result[$menuid] == $result[$i] ) {

        $payload = $result;
    }
  }

endwhile;
endif;

print_r( $payload );

Same thing happens when I create a new array like so:

    $payload = array();
    for ($i = $nextweek; $i<$nextweek+4; $i++) {
    if ( $result[$menuid] == $result[$i] ) {

        $payload[] = $result;
    }
  }

endwhile;
endif;

print_r( $payload );

If I concatenate the variable like $payload .= $result;, I get ArrayArrayArrayArray returned.

I know I can echo the form inside loop, but would rather take the array as a data variable if at all possible. Am I missing something easy?


问:
can I use an object's property in the object's method without using `this`
In following code, why I cannot access b without this keyword. I am using nodejs to run the code

```<code>var o = {
    a: 0,
    b:0,
    m1: function(){
        return this.a+b; //this doesn't compile
    },
}
console.log(o.m1())
</code>```

答:
Change this.a + b; to this.a + this.b;. There is no variable b but there is a property of the object with that name

var o = {
    a: 1,
    b: 4,
    m1: function(){
        return this.a + this.b;
    },
}
console.log(o.m1())```

Body:
In following code, why I cannot access b without this keyword. I am using nodejs to run the code

var o = {
    a: 0,
    b:0,
    m1: function(){
        return this.a+b; //this doesn't compile
    },
}
console.log(o.m1())


答:
The IF statement works as follows:
IF(logic_test, value_if true, value_if_false)

Your first IF statement has only the logic_test part (the output of AND). so you have to provide the other parameters.

Title: Using nested IF/AND statements in Sheets in a single cell


问:
BlackBerry simulator settings for VPN
I want to test a project from the BlackBerry simulator, but our webservice runs on an external server that can only be accessed using the vpn from our PC's.
I can access the webservice from the Android simulator without doing anything special. However I cannot access the webservice from the BlackBerry simulator -- not even from the browser of the simulator -- though I am able to connect to other services on the web from the BlackBerry simulator.

What kind settings are there to fix this?

答:
There's a network setting for the simulator that might be useful for situations like this. You could try manually assigning the vpn ip address you were given.

```<code>/ip-address={string}
</code>```

IP address of the simulated handheld. This should be left blank under normal circumstances. If running on a PC with multiple IP addresses, one can be specified here to cause the simulator to use it.

Cheers

Ray

Title: BlackBerry simulator settings for VPN

Body:
There's a network setting for the simulator that might be useful for situations like this. You could try manually assigning the vpn ip address you were given.

/ip-address={string}

IP address of the simulated handheld. This should be left blank under normal circumstances. If running on a PC with multiple IP addresses, one can be specified here to cause the simulator to use it.

Cheers

Ray


问:
How to re-index multiple Elastic Search types into a new index with a single type?
I am upgrading from ElasticSearch 5.6 to 6.0 and I have standard logstash-* indexes. In those indexes I have multiple (doc) types "attachmentsDbStats" and "attachmentsFileStats" which have the same schema. The only difference is the value of _type and type. I have created a new index attachments-* where the type is "attachement" and I want to reindex documents of both types into the new index. Obviously b/c of the new single type restriction in 6.0, both need to have the same type. I have update all of the documents in my old index such that the "type" field has a value "attachment." When I run reindex I am not able to upload the documents due to the restriction on the single type. I have attempted to update the _type field in the old indexes but that is immutable. Any ideas how to reindex and convert the type during the conversion?</p>

答:
Thank you for the tip. Fixing some of the spelling errors I had above this did the trick:</p>

```<code> POST _reindex {
  "source": {
    "index": "logstash-*",
    "query": {
      "bool": {
        "must": {
          "term": {
            "type": "attachments"
          }
        }
      }
    }
  },
  "dest": {
    "index": "attachments.old"
  },
  "script": {
    "source": "ctx._id = ctx._type + '-' + ctx._id; ctx._source.type = ctx._type; ctx._type = 'attachments';"
  }
}
</code>```

Body:
Thank you for the tip. Fixing some of the spelling errors I had above this did the trick:

 POST _reindex {
  "source": {
    "index": "logstash-*",
    "query": {
      "bool": {
        "must": {
          "term": {
            "type": "attachments"
          }
        }
      }
    }
  },
  "dest": {
    "index": "attachments.old"
  },
  "script": {
    "source": "ctx._id = ctx._type + '-' + ctx._id; ctx._source.type = ctx._type; ctx._type = 'attachments';"
  }
}


问:
How can I draw a single svg path with variable width stroking?
How can I draw this shape using a single svg path?

答:
You can do it with a single path, but currently there's no such thing as variable width stroke. Instead, such a shape can be drawn using fill on a path criss-crossing itself:

#hide-stroke:checked ~ svg path {
  stroke: none;
}

svg {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="hide-stroke" type="checkbox" />
<label for="hide-stroke">Hide stroke</label>

<svg xmlns="http://www.w3.org/2000/svg" width="600" height="300" viewBox="0,0 200,100" >
   <path d="M20,80  q26,-100 53,-25  q26,75 53,0  q26,-90 53,0  q-26,-70 -45,-10  q-26,80 -70,0  q-25,-40 -37,0"
         fill="black" stroke-width="1" stroke="limegreen" />
</svg></code>```

Body:
You can do it with a single path, but currently there's no such thing as variable width stroke. Instead, such a shape can be drawn using fill on a path criss-crossing itself:

#hide-stroke:checked ~ svg path {
  stroke: none;
}

svg {
  display: block;
}

<input id="hide-stroke" type="checkbox" />
<label for="hide-stroke">Hide stroke</label>

<svg xmlns="http://www.w3.org/2000/svg" width="600" height="300" viewBox="0,0 200,100" >
   <path d="M20,80  q26,-100 53,-25  q26,75 53,0  q26,-90 53,0  q-26,-70 -45,-10  q-26,80 -70,0  q-25,-40 -37,0"
         fill="black" stroke-width="1" stroke="limegreen" />
</svg>


问:
Shell is variable a number
Good evening,
I want to write a script that will say if its argument is a number or not, however I get this:

```<code>a: 4: Syntax error: "(" unexpected (expecting ")")
</code>```

At first I tried like this:

```
    #!/bin/bash
    case "$1" in
        0x* ) echo hex ;;
        ''|*[!0-9]*) echo dec ;;
        * ) echo wtf ;;
    esac
```

Later I have found this bit:

```
    if ! [[ "$yournumber" =~ ^[0-9]+$ ]] ; then
       exec >&2; echo "error: Not a number"; exit 1
    fi
```

Well, none of them works, I call for help!

答:
How about this as a base;

expr >>/dev/null  "$i" : '0[xX][0-9a-fA-f][0-9a-fA-F]$' && echo hex;
expr >>/dev/null  "$i" : '0[0-7]$' && echo oct;
expr >>/dev/null  "$i" : '[0-9][0-9]*$' && echo dec;

Title: Shell is variable a number

Body:
Good evening,
I want to write a script that will say if its argument is a number or not, however I get this:

a: 4: Syntax error: "(" unexpected (expecting ")")

At first I tried like this:

    #!/bin/bash
    case "$1" in
        0x* ) echo hex ;;
        ''|*[!0-9]*) echo dec ;;
        * ) echo wtf ;;
    esac

Later I have found this bit:

    if ! [[ "$yournumber" =~ ^[0-9]+$ ]] ; then
       exec >&2; echo "error: Not a number"; exit 1
    fi

Well, none of them works, I call for help!


问:
What is the best way pull updated changes into the Docker containers that already deployed?
I had to perform these steps to deploy my Nodejs/Angular site to AWS via DockerCloud

Write Dockerfile

Build Docker Images base on my Dockerfiles

Push those images to Docker Hub

Create Node Cluster on DockerCloud Account

Write Docker stack file on DockerCloud

Run the stack on DockerCloud

See the instance running in AWS, and can see my site

If we require a small thing changes that require a pull from my project repo.
BUT we already deployed our dockers as you may know.

What is the best way pull those changes into the Docker containers that already deployed ?

I hope we don’t have to :

Rebuild our Docker Images

Re-push those images to Docker Hub

Re-create our Node Cluster on DockerCloud

Re-write our docker stack file on DockerCloud

Re-run the stack on DockerCloud

I was thinking

SSH into a VM that has the Docker running

```<code>git pull
npm start
</code>```

Am I on the right track?

答:
You can use docker service update --image https://docs.docker.com/engine/reference/commandline/service_update/#options
I have not experience with AWS but I think you can build and update automatically.

Body:
I had to perform these steps to deploy my Nodejs/Angular site to AWS via DockerCloud

Write Dockerfile

Build Docker Images base on my Dockerfiles

Push those images to Docker Hub

Create Node Cluster on DockerCloud Account

Write Docker stack file on DockerCloud

Run the stack on DockerCloud

See the instance running in AWS, and can see my site

If we require a small thing changes that require a pull from my project repo.
BUT we already deployed our dockers as you may know.

What is the best way pull those changes into the Docker containers that already deployed ?

I hope we don’t have to :

Rebuild our Docker Images

Re-push those images to Docker Hub

Re-create our Node Cluster on DockerCloud

Re-write our docker stack file on DockerCloud

Re-run the stack on DockerCloud

I was thinking

SSH into a VM that has the Docker running

git pull
npm start

Am I on the right track?


问:
JSF locale issue
I have a situation where when a user selects a language from a drop down, I want the the application locale to change accordingly. Capturing locale is not difficult, but how to set the locale for all pages there after.

I have configuration set in resource bundles and faces-config.xml

答:
I believe this is what you are looking for:</p>

```<code>FacesContext context = FacesContext.getCurrentInstance();
context.getViewRoot().setLocale(locale);
</code>```

Title: JSF locale issue

Body:
I believe this is what you are looking for:

FacesContext context = FacesContext.getCurrentInstance();
context.getViewRoot().setLocale(locale);


问:
Pushing MailGun webhook onto AWS SQS
I need to process MailGun webhooks. I did implement a solution directly on our web servers to process the webhooks, but MailGun generates so many calls from a large campaign that it effectively becomes a DOS attack.

One solution I've been looking at is using AWS API Gateway to a Lambda function to then push onto an SQS queue. We can then poll the queue at a rate we can manage. Unfortunately we can't get this to work as AWS API Gateway does not support multipart/form-data content types (which some of the webhooks are). This means that our SQS messages are not well formatted / structured. The best we can do is use the $util.escapeJavaScript($input.body) function in the mapping template to create an SQS message that contains the raw string of the webhook content (with escaped javascript chars) that is effectively unparsable i.e. we can't get data out of it.

I've had a go at using Zapier to process the webhook and push directly on the SQS queue. This can parse the various content types effectively and create a nicely structured message for us, but the cost of the service is not viable.

Has anybody managed this problem in another way? Are there solutions to API Gateway not parsing the content properly? I've deliberately stayed away from MailGuns event polling API as it involves significant delays before the polled data can be 'trusted' (according to MailGun).

Basically, is there another way of getting a nicely parsed message from content types multipart/form-data and application/x-www-form-urlencoded onto the queue?

Any ideas would be much appreciated!

To add, this link higlights issues with APS Gateway and multipart\form-data content:
API Gateway - Post multipart\form-data

答:
Not sure if you ever came to a solution, but I have this working with the following settings.

Setup your API Gateway method to use "Use Lambda Proxy integration"

In your lambda (I use node.js) use busboy to work through the multi-part submission from the mailgun webhook. (use this post for help with busboy Busboy help)

Make sure that any code you are going to execute after all busboy is complete is executed in the 'finish' portion of the busboy code.

Title: Pushing MailGun webhook onto AWS SQS


问:
Load .csv files into dictionary and print keys and values separately
I am having troubles figuring out how to store multiple .csv files into a dictionary and then print the keys and values separately. I have to take 6 .csv files all containing different information and load them into a dictionary(s) and then write a code so that I am able to isolate the key from the various values its associated with so that I can print ie. "animal" eats "prey1, prey2, etc".

I think I have to do each file separately, so 6 different loops to get the right output for each list of key/values, but everything I've tried has given me an error message.
Here is an examples of a csv file and the expected output:

file1.csv:

```<code>Rabbit,Grass
Snake,Mouse
Mouse,Grass
</code>```

Output:

```<code>Predator and prey:
"Rabbit eats grass"
"Snake eats mouse"
"Mouse eats grass"
</code>```

this is the code I have so far for one file:

```<code>import sys
import csv

inf = open("file1.csv", "r")
reader = csv.reader(inf)

data = {}
for row in reader:
    for i in data.keys():
        print(data[i], "eats", i)
</code>```

I know its not right but I'm not sure how to isolate a key in a dictionary when its a .csv file. I am new to coding so any help would be greatly appreciated! :)
I am using python3.
thanks!!

答:
You should checkout pandas.
Very good for this sort of thing.

```<code>df = pd.read_csv('file1.csv', names=['Predator','Prey'])
df['statement'] = df.Predator + ' eats ' + df.Prey

for s in df.statement:
    print(s)
</code>```

If you want a dict of {'predator':'prey'} you could do

```<code>dic = {pred:prey for pred,prey in df[['Predator','Prey']].values}
</code>```

Body:
I am having troubles figuring out how to store multiple .csv files into a dictionary and then print the keys and values separately. I have to take 6 .csv files all containing different information and load them into a dictionary(s) and then write a code so that I am able to isolate the key from the various values its associated with so that I can print ie. "animal" eats "prey1, prey2, etc".

I think I have to do each file separately, so 6 different loops to get the right output for each list of key/values, but everything I've tried has given me an error message.
Here is an examples of a csv file and the expected output:

file1.csv:

Rabbit,Grass
Snake,Mouse
Mouse,Grass

Output:

Predator and prey:
"Rabbit eats grass"
"Snake eats mouse"
"Mouse eats grass"

this is the code I have so far for one file:

import sys
import csv

inf = open("file1.csv", "r")
reader = csv.reader(inf)

data = {}
for row in reader:
    for i in data.keys():
        print(data[i], "eats", i)

I know its not right but I'm not sure how to isolate a key in a dictionary when its a .csv file. I am new to coding so any help would be greatly appreciated! :)
I am using python3.
thanks!!

Body:
You should checkout pandas.
Very good for this sort of thing.

df = pd.read_csv('file1.csv', names=['Predator','Prey'])
df['statement'] = df.Predator + ' eats ' + df.Prey

for s in df.statement:
    print(s)

If you want a dict of {'predator':'prey'} you could do

dic = {pred:prey for pred,prey in df[['Predator','Prey']].values}


问:
iOS video not playing (play button crossed out)
I'm trying to play a video from URL, but when I run the code, all I can see is the play button crossed out.

here is the code:

```<code>import UIKit
import AVFoundation
import AVKit
class ViewController: UIViewController {
    override func viewDidLoad() {
    super.viewDidLoad()

    @IBAction func playVideo(_ sender: Any) {
        let videoURL = URL(string: "http://techslides.com/demos/sample-videos/small.mp4")
        let player = AVPlayer(url: videoURL!)
        let playerControler = AVPlayerViewController()
        playerControler.player = player
        present(playerControler, animated: true) {
        player.play()

    }

}
</code>```

Xcode 9.1
Swift 4

Any idea what is wrong?

答:
You need to edit your .plist file to be able to get video by given http URL

App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.

Add this code to your .plist xml, or simply try to load https: video:

```<code><key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
    <key>NSExceptionDomains</key>
    <dict>
        <key>example.com</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSIncludesSubdomains</key>
            <true/>
        </dict>
    </dict>
</dict>
</code>```

Body:
I'm trying to play a video from URL, but when I run the code, all I can see is the play button crossed out.

here is the code:

import UIKit
import AVFoundation
import AVKit
class ViewController: UIViewController {
    override func viewDidLoad() {
    super.viewDidLoad()

    @IBAction func playVideo(_ sender: Any) {
        let videoURL = URL(string: "http://techslides.com/demos/sample-videos/small.mp4")
        let player = AVPlayer(url: videoURL!)
        let playerControler = AVPlayerViewController()
        playerControler.player = player
        present(playerControler, animated: true) {
        player.play()

    }

}

Xcode 9.1
Swift 4

Any idea what is wrong?

Body:
You need to edit your .plist file to be able to get video by given http URL

App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.

Add this code to your .plist xml, or simply try to load https: video:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
    <key>NSExceptionDomains</key>
    <dict>
        <key>example.com</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSIncludesSubdomains</key>
            <true/>
        </dict>
    </dict>
</dict>


问:
Create generic data filter on pandas dataframe in Python
I am trying to create a generic filter on some data. Consider a boiled down example:

```<code>my_data = pd.DataFrame(some_data)
my_filter = {"value": 100, "direction": ">"}
</code>```

now I want to leverage numpy's where to do something like:

```<code>np.where(my_data (...) my_filter["value"])
</code>```

where, as "(...)", I want my_filter["direction"]. Sure, I can use something like "eval(...)" by putting together an appropriate string.

Question But I was wondering if there is a way to do this without eval(...)?

Follow-up on "already answered" claim: The key here is that I need the direction to be generic. Sub-selecting data based on values is easy "np.where(my_data == my_filter["value"])", e.g.

答:
Here is an example applied with your data from Select data frame by dict passing in parameters or comprehension list python pandas</p>

```<code>import pandas as pd

df = pd.DataFrame(dict(value=[100,200],direction=['>','<']))
my_filter = {"value":100, "direction": ">"}

# Apply
mask = (df[list(my_filter)] == pd.Series(my_filter)).all(axis=1)
df[mask]
</code>```

Body:
I am trying to create a generic filter on some data. Consider a boiled down example:

my_data = pd.DataFrame(some_data)
my_filter = {"value": 100, "direction": ">"}

now I want to leverage numpy's where to do something like:

np.where(my_data (...) my_filter["value"])

where, as "(...)", I want my_filter["direction"]. Sure, I can use something like "eval(...)" by putting together an appropriate string.

Question But I was wondering if there is a way to do this without eval(...)?

Follow-up on "already answered" claim: The key here is that I need the direction to be generic. Sub-selecting data based on values is easy "np.where(my_data == my_filter["value"])", e.g.

Body:
Here is an example applied with your data from Select data frame by dict passing in parameters or comprehension list python pandas

import pandas as pd

df = pd.DataFrame(dict(value=[100,200],direction=['>','<']))
my_filter = {"value":100, "direction": ">"}

# Apply
mask = (df[list(my_filter)] == pd.Series(my_filter)).all(axis=1)
df[mask]


问:
Alpakka JMS Transaction
I'm playing with Alpakka and its JMS connector to dequeue data from Oracle AQ. I could come up with the very basic implementation below by following this guide.

My question is how I can make it transactional, so that I can guarantee that my message won't be lost if an exception is thrown.

```<code>object ConsumerApp extends App {
    implicit val system: ActorSystem = ActorSystem("actor-system")
    implicit val materializer: ActorMaterializer = ActorMaterializer()

    val connectionFactory = AQjmsFactory.getConnectionFactory(getOracleDataSource())

    val out = JmsSource.textSource(
        JmsSourceSettings(connectionFactory).withQueue("My_Queue")
    )

    val sink = Sink.foreach { message: String =>
        println("in sink: " + message)
        throw new Exception("") // !!! MESSAGE IS LOST !!!
    }

    out.runWith(sink, materializer)
}
</code>```

If it was PL/SQL, the solution would be like this:

```<code>DECLARE
  dequeue_options            DBMS_AQ.DEQUEUE_OPTIONS_T;
  message_properties         DBMS_AQ.MESSAGE_PROPERTIES_T;
  message_handle             RAW (44);
  msg                        SYS.AQ$_JMS_TEXT_MESSAGE;
BEGIN
  DBMS_AQ.dequeue (
      queue_name           => 'My_Queue',
      dequeue_options      => dequeue_options,
      message_properties   => message_properties,
      payload              => msg,
      msgid                => message_handle
  );

  -- do something with the message

  COMMIT;
END;
</code>```

答:
The default behavior when a stream stage fails is to shut down the entire stream. You'll have to decide how you want to handle errors in the stream. One approach, for example, is to restart the stream with a backoff strategy.

Also, since you're using the Alpakka JMS connector, set the acknowledgement mode to ClientAcknowledge (this is available since Alpakka 0.15). With this configuration, messages that aren't acknowledged can be delivered again through the JMS source. For example:

```<code>val jmsSource: Source[Message, NotUsed] = JmsSource(
  JmsSourceSettings(connectionFactory)
    .withQueue("My_Queue")
    .withAcknowledgeMode(AcknowledgeMode.ClientAcknowledge)
)

val result = jmsSource
  .map {
    case textMessage: TextMessage =>
      val text = textMessage.getText
      textMessage.acknowledge()
      text
  }
  .runForeach(println)
</code>```

Title: Alpakka JMS Transaction

Body:
I'm playing with Alpakka and its JMS connector to dequeue data from Oracle AQ. I could come up with the very basic implementation below by following this guide.

My question is how I can make it transactional, so that I can guarantee that my message won't be lost if an exception is thrown.

object ConsumerApp extends App {
    implicit val system: ActorSystem = ActorSystem("actor-system")
    implicit val materializer: ActorMaterializer = ActorMaterializer()

    val connectionFactory = AQjmsFactory.getConnectionFactory(getOracleDataSource())

    val out = JmsSource.textSource(
        JmsSourceSettings(connectionFactory).withQueue("My_Queue")
    )

    val sink = Sink.foreach { message: String =>
        println("in sink: " + message)
        throw new Exception("") // !!! MESSAGE IS LOST !!!
    }

    out.runWith(sink, materializer)
}

If it was PL/SQL, the solution would be like this:

DECLARE
  dequeue_options            DBMS_AQ.DEQUEUE_OPTIONS_T;
  message_properties         DBMS_AQ.MESSAGE_PROPERTIES_T;
  message_handle             RAW (44);
  msg                        SYS.AQ$_JMS_TEXT_MESSAGE;
BEGIN
  DBMS_AQ.dequeue (
      queue_name           => 'My_Queue',
      dequeue_options      => dequeue_options,
      message_properties   => message_properties,
      payload              => msg,
      msgid                => message_handle
  );

  -- do something with the message

  COMMIT;
END;

Body:
The default behavior when a stream stage fails is to shut down the entire stream. You'll have to decide how you want to handle errors in the stream. One approach, for example, is to restart the stream with a backoff strategy.

Also, since you're using the Alpakka JMS connector, set the acknowledgement mode to ClientAcknowledge (this is available since Alpakka 0.15). With this configuration, messages that aren't acknowledged can be delivered again through the JMS source. For example:

val jmsSource: Source[Message, NotUsed] = JmsSource(
  JmsSourceSettings(connectionFactory)
    .withQueue("My_Queue")
    .withAcknowledgeMode(AcknowledgeMode.ClientAcknowledge)
)

val result = jmsSource
  .map {
    case textMessage: TextMessage =>
      val text = textMessage.getText
      textMessage.acknowledge()
      text
  }
  .runForeach(println)


问:
Openshift 3: How to create a cron job?
I have been trying to create a cron job on my Openshift 3 Starter app.  I have read the docs HERE but I guess I'm not understanding them correctly.

I would like run a simple python tcron.py  script that prints out a timestamp  every minute.  I have tried the following to set up the cron job.

```<code> oc run tcron --schedule="* * * * *" --image=python --restart=OnFailure -- python vscan/tcron.py
</code>```

The above command gives me the error:

```<code> Error from server (Forbidden): User "<MY EMAIL ACCOUNT>" cannot create cronjobs.batch in the namespace "vscan": User "<MY EMAIL ACCOUNT>" cannot create cronjobs.batch in project "vscan" (post cronjobs.batch)
</code>```

What is the correct way of creating a cron job on openshift 3 starter?

答:
Jobs are only available in the OpenShift Online Pro environments. You can see what you get in Starter compared to Pro at:

https://www.openshift.com/pricing/index.html

Title: Openshift 3: How to create a cron job?

Body:
I have been trying to create a cron job on my Openshift 3 Starter app.  I have read the docs HERE but I guess I'm not understanding them correctly.

I would like run a simple python tcron.py  script that prints out a timestamp  every minute.  I have tried the following to set up the cron job.

 oc run tcron --schedule="* * * * *" --image=python --restart=OnFailure -- python vscan/tcron.py

The above command gives me the error:

 Error from server (Forbidden): User "<MY EMAIL ACCOUNT>" cannot create cronjobs.batch in the namespace "vscan": User "<MY EMAIL ACCOUNT>" cannot create cronjobs.batch in project "vscan" (post cronjobs.batch)

What is the correct way of creating a cron job on openshift 3 starter?


问:
Make an API call inside of another API call?
I basically need to combine data from two different API calls. Here is what I have right now:

```<code>    var url= "https://website.com/api.json";
    $.ajax({
        url: url,
        type: "GET",
        dataType: 'json',
        headers: {'X-API-Key': 'xxxxxx'},
        success: function(data){

            var api = data.results[0].api;

            for (var i=0;i<api.length;++i)
            var api2url = api[i].api2url;

            {
                $('tbody').append('<tr><td>'+api[i].thing+'</td></tr>');
            }
        }
    });
</code>```

The above works.

The problem is that I also need data from https://website.com/api2.json (which will come from data from the api1 call). I need my final code to look like:

$('tbody').append('
+api[i].thing+'
');

答:
Easiest way forward would be to make that API call in the success callback of your first API call.  Might look something like:</p>

```<code>var url= "https://website.com/api.json";
$.ajax({
    url: url,
    type: "GET",
    dataType: 'json',
    headers: {'X-API-Key': 'xxxxxx'},
    success: function(data){
      // now you have closure over results from api call one
      $.ajax({
        url: 'apiURL2', // or something
        type: "GET",
        dataType: 'json',
        headers: {'X-API-Key': data.results.apiKey // or something },
        success: function(moreData){

        var api = data.results[0].api;

        for (var i=0;i<api.length;++i)
        {
            $('tbody').append('<tr><td>'+api[i].thing+ moreData.thing'</td></tr>');
        }
    }
  })
});
</code>```

Body:
I basically need to combine data from two different API calls. Here is what I have right now:

    var url= "https://website.com/api.json";
    $.ajax({
        url: url,
        type: "GET",
        dataType: 'json',
        headers: {'X-API-Key': 'xxxxxx'},
        success: function(data){

            var api = data.results[0].api;

            for (var i=0;i<api.length;++i)
            var api2url = api[i].api2url;

            {
                $('tbody').append('
'+api[i].thing+'
');
            }
        }
    });

The above works.

The problem is that I also need data from https://website.com/api2.json (which will come from data from the api1 call). I need my final code to look like:

$('tbody').append('
+api[i].thing+'
');

Body:
Easiest way forward would be to make that API call in the success callback of your first API call.  Might look something like:

var url= "https://website.com/api.json";
$.ajax({
    url: url,
    type: "GET",
    dataType: 'json',
    headers: {'X-API-Key': 'xxxxxx'},
    success: function(data){
      // now you have closure over results from api call one
      $.ajax({
        url: 'apiURL2', // or something
        type: "GET",
        dataType: 'json',
        headers: {'X-API-Key': data.results.apiKey // or something },
        success: function(moreData){

        var api = data.results[0].api;

        for (var i=0;i<api.length;++i)
        {
            $('tbody').append('<tr><td>'+api[i].thing+ moreData.thing'</td></tr>');
        }
    }
  })
});