问:
Tkinter text widget adding tabs to selected text
I am trying to create a text editor for python using tkinter. When the user highlights lines of text and presses tab, I want the program to add a tab in front of each line of selected text, similar to what Idle does. This is the function I have so far:

```<code>    self.TextBox.bind('<KeyPress-Tab>', self.tabtext)

def tabtext(self, e):
    try:
        untabbed = self.TextBox.selection_get() # get selected text
        lines = untabbed.split('\n') # splits into a list of lines
        tabbed = ''

        for i in range(len(lines)):
            lines[i] = '    ' + lines[i] # adds tabs to each line

        tabbed = '\n'.join(lines) # joins list with newline character

        old = self.TextBox.get("1.0", tk.END) # gets old text
        new = old.replace(untabbed, tabbed) # replaces all instances of  highlighted
# text with new text

        self.TextBox.delete('1.0', tk.END) # deletes old text
        self.TextBox.insert(tkinter.END, new) # adds new text

        return 'break' # prevents it from deletion

    except:
        return
</code>```

This code works, however if the selected text appears in the text box more than once, it will add tabs to each instance of the selected code. Is there any way to resolve this, maybe involving finding the position of the selected text. Any help would be greatly appreciated.

答:
You can just replace the selected code rather that deleting and re-inserting all of the text.

The first step is to get the index of the start of the line for the selection:

```<code>index = self.TextBox.index("sel.first linestart")
</code>```

Next, delete all of the lines in the selection:

```<code>self.TextBox.delete("sel.first linestart", "sel.last lineend")
</code>```

Finally, insert the new text

```<code>    self.TextBox.insert(index, tabbed)
</code>```

Alternate method

Though, if all you're doing is inserting tags, you don't need to delete-and-replace. You can also just insert a tab for every line in the selected range. All you have to do is iterate over the lines. It would look something like this:

```<code>def tabtext(self, e):
    last = self.TextBox.index("sel.last linestart")
    index = self.TextBox.index("sel.first linestart")
    while self.TextBox.compare(index,"<=", last):
        self.TextBox.insert(index, "    ")
        index = self.TextBox.index("%s + 1 line" % index)
    return "break"
</code>```

Body:
I am trying to create a text editor for python using tkinter. When the user highlights lines of text and presses tab, I want the program to add a tab in front of each line of selected text, similar to what Idle does. This is the function I have so far:

    self.TextBox.bind('<KeyPress-Tab>', self.tabtext)

def tabtext(self, e):
    try:
        untabbed = self.TextBox.selection_get() # get selected text
        lines = untabbed.split('\n') # splits into a list of lines
        tabbed = ''

        for i in range(len(lines)):
            lines[i] = '    ' + lines[i] # adds tabs to each line

        tabbed = '\n'.join(lines) # joins list with newline character

        old = self.TextBox.get("1.0", tk.END) # gets old text
        new = old.replace(untabbed, tabbed) # replaces all instances of  highlighted
# text with new text

        self.TextBox.delete('1.0', tk.END) # deletes old text
        self.TextBox.insert(tkinter.END, new) # adds new text

        return 'break' # prevents it from deletion

    except:
        return

This code works, however if the selected text appears in the text box more than once, it will add tabs to each instance of the selected code. Is there any way to resolve this, maybe involving finding the position of the selected text. Any help would be greatly appreciated.

Body:
You can just replace the selected code rather that deleting and re-inserting all of the text.

The first step is to get the index of the start of the line for the selection:

index = self.TextBox.index("sel.first linestart")

Next, delete all of the lines in the selection:

self.TextBox.delete("sel.first linestart", "sel.last lineend")

Finally, insert the new text

    self.TextBox.insert(index, tabbed)

Alternate method

Though, if all you're doing is inserting tags, you don't need to delete-and-replace. You can also just insert a tab for every line in the selected range. All you have to do is iterate over the lines. It would look something like this:

def tabtext(self, e):
    last = self.TextBox.index("sel.last linestart")
    index = self.TextBox.index("sel.first linestart")
    while self.TextBox.compare(index,"<=", last):
        self.TextBox.insert(index, "    ")
        index = self.TextBox.index("%s + 1 line" % index)
    return "break"


来源: stackexchange

问:
BufferNotEnough Could not create SSL/TLS secure channel
Some times we receive the error "The request was aborted: Could not create SSL/TLS secure channel.."
I tried to investigate this issue, and the trace log I got for this is:

```<code>System.Net Information: 0 : [4356] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=**BufferNotEnough**).
System.Net Error: 0 : [4356] Exception in HttpWebRequest#37434592:: - The request was aborted: Could not create SSL/TLS secure channel..
System.Net Error: 0 : [4356] Exception in HttpWebRequest#37434592::EndGetRequestStream - The request was aborted: Could not create SSL/TLS secure channel..
</code>```

What does it mean BufferNotEnough for this case?

Thanks.

答: This seems to be a bug in HttpWebRequest in .NET 4.6.1 - see https://connect.microsoft.com/VisualStudio/feedback/details/2777134/tls-1-2-handshake-error</p>

ContentLicense: CC BY-SA 3.0

Body:
Some times we receive the error "The request was aborted: Could not create SSL/TLS secure channel.."
I tried to investigate this issue, and the trace log I got for this is:

System.Net Information: 0 : [4356] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=**BufferNotEnough**).
System.Net Error: 0 : [4356] Exception in HttpWebRequest#37434592:: - The request was aborted: Could not create SSL/TLS secure channel..
System.Net Error: 0 : [4356] Exception in HttpWebRequest#37434592::EndGetRequestStream - The request was aborted: Could not create SSL/TLS secure channel..

What does it mean BufferNotEnough for this case?

Thanks.


问:
How to show choices of field in another table(model) value?
How to show choices of field in another table value?
I want to Nutritionalkey show on the NutritionalValues choice field</p>

```<code>class Nutritionalkey(models.Model):
key = models.CharField(max_length=1000)

def __unicode__(self):
    return self.key

class NutritionalValues(models.Model):
  key = models.CharField(max_length=100, choices=Nutritionalkey.key)
  value=models.FloatField(null=True, blank=True, default=None)
  product=models.ForeignKey(Product,null=True, blank=True)

  class Meta:
      verbose_name_plural = 'NutritionalValues'
      verbose_name = 'NutritionalValue'

  def __unicode__(self):
      return '%s %s' % (self.product.productName,self.key)
</code>```

答:
As django doc says:

But if you find yourself hacking choices to be dynamic, you’re
  probably better off using a proper database table with a ForeignKey.

You should then have:

```<code>class NutritionalValues(models.Model):
    key = models.ForeignKey(Nutritionalkey)
    ...
</code>```

Body:
How to show choices of field in another table value?
I want to Nutritionalkey show on the NutritionalValues choice field

class Nutritionalkey(models.Model):
key = models.CharField(max_length=1000)

def __unicode__(self):
    return self.key

class NutritionalValues(models.Model):
  key = models.CharField(max_length=100, choices=Nutritionalkey.key)
  value=models.FloatField(null=True, blank=True, default=None)
  product=models.ForeignKey(Product,null=True, blank=True)

  class Meta:
      verbose_name_plural = 'NutritionalValues'
      verbose_name = 'NutritionalValue'

  def __unicode__(self):
      return '%s %s' % (self.product.productName,self.key)

Body:
As django doc says:

But if you find yourself hacking choices to be dynamic, you’re
  probably better off using a proper database table with a ForeignKey.

You should then have:

class NutritionalValues(models.Model):
    key = models.ForeignKey(Nutritionalkey)
    ...


问:
C++ append int to wstring
Before(using ASCII) i was using std::string as buffer like this:

```<code>std::string test = "";
int value = 6;
test.append("some string");
test.append((char*)value, 4);
test.append("some string");
</code>```

with expected value in test:

"some srtring\x6\x0\x0\x0somestring"

Now i am tring to use Unicode and i wanna keep the same "code" but trubles happens:

```<code>std::wstring test = "";
int value = 6;
test.append("some string");
test.append((wchar_t*)value, 4); (buffer overflow cause reading 8 bytes)
test.append("some string");
</code>```

How can i append bytes like in std::string?
Doing:

```<code>std::wstring test = "";
int value = 6;
test.append("some string");
test.append((wchar_t*)value, 2);
test.append("some string");
</code>```

Solve partially the problem cause after i can't append bools.

EDIT:
i can even use wstringstream if a binary copy is applied.(normally not)

答:
You make a function that reads the stuff you want to put:

```<code>void putBytes(std::wstring& s, char* c, int numBytes)
{
    while (numBytes-- > 0)
        s += (wchar_t)*c++;
}
</code>```

Then you can call it:

```<code>int value = 65;
putBytes(s, reinterpret_cast<char*>(&value), sizeof(value));
</code>```

Title: C++ append int to wstring

Body:
Before(using ASCII) i was using std::string as buffer like this:

std::string test = "";
int value = 6;
test.append("some string");
test.append((char*)value, 4);
test.append("some string");

with expected value in test:

"some srtring\x6\x0\x0\x0somestring"

Now i am tring to use Unicode and i wanna keep the same "code" but trubles happens:

std::wstring test = "";
int value = 6;
test.append("some string");
test.append((wchar_t*)value, 4); (buffer overflow cause reading 8 bytes)
test.append("some string");

How can i append bytes like in std::string?
Doing:

std::wstring test = "";
int value = 6;
test.append("some string");
test.append((wchar_t*)value, 2);
test.append("some string");

Solve partially the problem cause after i can't append bools.

EDIT:
i can even use wstringstream if a binary copy is applied.(normally not)

Body:
You make a function that reads the stuff you want to put:

void putBytes(std::wstring& s, char* c, int numBytes)
{
    while (numBytes-- > 0)
        s += (wchar_t)*c++;
}

Then you can call it:

int value = 65;
putBytes(s, reinterpret_cast<char*>(&value), sizeof(value));


问:
Recurrence Approach : How can we generate all possibilities on braces?
How can we generate all possibilities on braces  ?

N value has given to us and we have to  generate all possibilities.

Examples:

1) if N == 1,  then only one possibility () .

2) if N==2, then possibilities are (()), ()()

3) if N==3, then possibilities are ((())), (())(),()()(), ()(()) ...

Note: left and right braces should match. I mean )( is INVALID for the N==1

Can we solve this problem by using recurrence approach ?

答:
From wikipedia -

A Dyck word is a string consisting of n X's and n Y's such that no initial segment of the string has more Y's than X's (see also Dyck language). For example, the following are the Dyck words of length 6:

```<code>XXXYYY     XYXXYY     XYXYXY     XXYYXY     XXYXYY.
</code>```

Re-interpreting the symbol X as an open parenthesis and Y as a close parenthesis, Cn counts the number of expressions containing n pairs of parentheses which are correctly matched:

```<code>((()))     ()(())     ()()()     (())()     (()())
</code>```

See also http://www.acta.sapientia.ro/acta-info/C1-1/info1-9.pdf

Abstract. A new algorithm to generate all Dyck words is presented,
  which is used in ranking and unranking Dyck words. We emphasize the
  importance of using Dyck words in encoding objects related to Catalan
  numbers. As a consequence of formulas used in the ranking algorithm
  we can obtain a recursive formula for the nth Catalan number.

Body:
From wikipedia -

A Dyck word is a string consisting of n X's and n Y's such that no initial segment of the string has more Y's than X's (see also Dyck language). For example, the following are the Dyck words of length 6:

XXXYYY     XYXXYY     XYXYXY     XXYYXY     XXYXYY.

Re-interpreting the symbol X as an open parenthesis and Y as a close parenthesis, Cn counts the number of expressions containing n pairs of parentheses which are correctly matched:

((()))     ()(())     ()()()     (())()     (()())

See also http://www.acta.sapientia.ro/acta-info/C1-1/info1-9.pdf

Abstract. A new algorithm to generate all Dyck words is presented,
  which is used in ranking and unranking Dyck words. We emphasize the
  importance of using Dyck words in encoding objects related to Catalan
  numbers. As a consequence of formulas used in the ranking algorithm
  we can obtain a recursive formula for the nth Catalan number.

ContentLicense: CC BY-SA 2.5


问:
Do I need test method that is inside the test class
So I have a sample method that I give him a day and it returns me the first and last day of a week in which the day:

```<code>public static final DatePeriod thisWeek(LocalDate date) {

    TemporalField dayOfWeek = WeekFields.of(Locale.FRANCE).dayOfWeek();
    LocalDate mon = date.with(dayOfWeek, 1);
    LocalDate sun = date.with(dayOfWeek, 7);

    return new DatePeriod(mon, sun);
}
</code>```

I have to write a JUnit test (and I did it):

```<code>@Test
public void testThisMonth_LocalDate() throws ParseException {
    System.out.println("thisMonth");
    for (String[] date : VALID_TEST_DATES) {
        LocalDate dateLocal = dateToLocal(date[0]);
        DatePeriod expResult = new DatePeriod(dateToLocal(date[5]), dateToLocal(date[6]));
        DatePeriod result = JavaTimeUtils.thisMonth(dateLocal);
        assertEquals(expResult.getLeft(), result.getLeft());
        assertEquals(expResult.getRight(), result.getRight());
    }
}
</code>```

So, because I used code in dateToLocal() multiple times, I decided to make it in method like this:

```<code>public LocalDate dateToLocal(String dateString) throws ParseException {   // Calendar to LocalDate
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    Calendar cal = Calendar.getInstance();
    Date initDate = df.parse(dateString);
    cal.setTime(initDate);
    LocalDate dateLocal = LocalDate.of(cal.get(Calendar.YEAR), Month.of(cal.get(Calendar.MONTH)+1), cal.get(Calendar.DAY_OF_MONTH));

    return dateLocal;
}
</code>```

And it works.
But that is not my question.
I was wondering is this the correct way to do things like this (method in this JUnit test), do I need to make Test for this method, do I have to move it in other class (outside the tests)? I know this is strange question, I've already searching in google, unsuccessfully. (maybe I can't  ask google right).
Thanks :)

答:
I'd say the rules for this are similar the same for test code and production code:

If you use a code pattern more than once within a class, extract it to a method

If you use it in more than one class in the same package, move the method to a utility class with package-level visibility

If you use it in multiple packages, move the utility class to a dedicated utility package, make it public

If you use the code in more than one project, move it to a team-specific library

If you find that your entire organization needs this functionality repeatedly, move it to a global library

If you find that the whole world needs it, open-source it

Basically: Make the code as visible as it needs to be, but not more

And yes, if you extract your code to a utility class (2nd bullet or below), then I'd expect a dedicated test / test suite for the code

Body:
So I have a sample method that I give him a day and it returns me the first and last day of a week in which the day:

public static final DatePeriod thisWeek(LocalDate date) {

    TemporalField dayOfWeek = WeekFields.of(Locale.FRANCE).dayOfWeek();
    LocalDate mon = date.with(dayOfWeek, 1);
    LocalDate sun = date.with(dayOfWeek, 7);

    return new DatePeriod(mon, sun);
}

I have to write a JUnit test (and I did it):

@Test
public void testThisMonth_LocalDate() throws ParseException {
    System.out.println("thisMonth");
    for (String[] date : VALID_TEST_DATES) {
        LocalDate dateLocal = dateToLocal(date[0]);
        DatePeriod expResult = new DatePeriod(dateToLocal(date[5]), dateToLocal(date[6]));
        DatePeriod result = JavaTimeUtils.thisMonth(dateLocal);
        assertEquals(expResult.getLeft(), result.getLeft());
        assertEquals(expResult.getRight(), result.getRight());
    }
}

So, because I used code in dateToLocal() multiple times, I decided to make it in method like this:

public LocalDate dateToLocal(String dateString) throws ParseException {   // Calendar to LocalDate
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    Calendar cal = Calendar.getInstance();
    Date initDate = df.parse(dateString);
    cal.setTime(initDate);
    LocalDate dateLocal = LocalDate.of(cal.get(Calendar.YEAR), Month.of(cal.get(Calendar.MONTH)+1), cal.get(Calendar.DAY_OF_MONTH));

    return dateLocal;
}

And it works.
But that is not my question.
I was wondering is this the correct way to do things like this (method in this JUnit test), do I need to make Test for this method, do I have to move it in other class (outside the tests)? I know this is strange question, I've already searching in google, unsuccessfully. (maybe I can't  ask google right).
Thanks :)


问:
Replacing an empty cell in one column based on corresponding value from another column?
I have this data frame:

```<code>df <- data.frame(number = c(1,2,3,1,3,4,5,2),
             name = c('dany', 'rand', 'tanya',
                      ' ', ' ', 'bruce', 'tony', ' '),
             grade = c('a', 'b', 'c', ' ', 'c', 'd', 'e', ' '))
</code>```

which looks like this:

```<code> > df
# A tibble: 8 × 3
number  name grade
 <dbl> <chr> <chr>
    1  dany     a
    2  rand     b
    3 tanya     c
    1
    3           c
    4 bruce     d
    5  tony     e
    2
</code>```

what I want is this:

```<code> > df
# A tibble: 8 × 3
number  name grade
 <dbl> <chr> <chr>
    1  dany     a
    2  rand     b
    3 tanya     c
    1  dany     a
    3 tanya     c
    4 bruce     d
    5  tony     e
    2  rand     b
</code>```

How do I accomplish this ?
how do I replace the empty spaces with the values corresponding to number column?

If possible, please explain how can I achieve this with dplyr(tidyverse).

答:
This is my solution assuming that there are only numbers with an existing full row somewhere: </p>

```<code>library(tidyverse)

df <- data_frame(number = c(1,2,3,1,3,4,5,2),
                 name = c('dany', 'rand', 'tanya',
                          ' ', ' ', 'bruce', 'tony', ' '),
                 grade = c('a', 'b', 'c', ' ', 'c', 'd', 'e', ' '))

master <- df %>%
  filter(name != " " & grade != "")
master <- master[!duplicated(master),]

only_number <- df %>%
  select(number)

df <- inner_join(only_number, master, by = c("number"))
</code>```

Body:
I have this data frame:

df <- data.frame(number = c(1,2,3,1,3,4,5,2),
             name = c('dany', 'rand', 'tanya',
                      ' ', ' ', 'bruce', 'tony', ' '),
             grade = c('a', 'b', 'c', ' ', 'c', 'd', 'e', ' '))

which looks like this:

 > df
# A tibble: 8 × 3
number  name grade
 <dbl> <chr> <chr>
    1  dany     a
    2  rand     b
    3 tanya     c
    1
    3           c
    4 bruce     d
    5  tony     e
    2

what I want is this:

 > df
# A tibble: 8 × 3
number  name grade
 <dbl> <chr> <chr>
    1  dany     a
    2  rand     b
    3 tanya     c
    1  dany     a
    3 tanya     c
    4 bruce     d
    5  tony     e
    2  rand     b

How do I accomplish this ?
how do I replace the empty spaces with the values corresponding to number column?

If possible, please explain how can I achieve this with dplyr(tidyverse).

Body:
This is my solution assuming that there are only numbers with an existing full row somewhere:

library(tidyverse)

df <- data_frame(number = c(1,2,3,1,3,4,5,2),
                 name = c('dany', 'rand', 'tanya',
                          ' ', ' ', 'bruce', 'tony', ' '),
                 grade = c('a', 'b', 'c', ' ', 'c', 'd', 'e', ' '))

master <- df %>%
  filter(name != " " & grade != "")
master <- master[!duplicated(master),]

only_number <- df %>%
  select(number)

df <- inner_join(only_number, master, by = c("number"))


问:
R Studio Server / Shiny Server Admin
I have 'inherited' from our previous resident data scientist, a RStudio Server setup on a remote virtual machine that we can use to host Shiny Apps.
I have basic experience on Unix i.e. Can mount files etc to the server from our Windows environment.
The issue I am having is, now our DS has left, any apps placed on the location will not run due his login no longer existing. The message to that effect is displayed on the browser when trying to run any app from the created directory.
Does this mean the instance of RStudio Server / Shiny Server run must run from or as a specified admin? If so, how would one go about changing this to be able to use apps again?
I have trawled the admin guide but am both confused and at a loss as to what is required.
Any help would be appreciated.

Regards

答:
See comment. Fixed this with a bit of googling and actually properly reading the awesome admin guide. Get to know vim if not already familiar and you are there.
Sudo, Sudo and more Sudo</p>

Title: R Studio Server / Shiny Server Admin


问:
Why should redux action types be in UPPER_CASE?
Is there any deeper reason why action types in redux should be strings in all upper case with underscores?

A string is just a string, right? Why not use the the names of action creators (typically in camelCase) also as the type of the actions created by them?

答:
capital letters for constants

It is just a convention which is common also in other other languages.

Interesting article on redux naming conventions:
https://decembersoft.com/posts/a-simple-naming-convention-for-action-creators-in-redux-js/


问:
Difference between two structure variable declaration?
I am doing hash implementation. I have sample program below.

```<code>#define HASHSIZE 25

struct HashTable {
        char key[50];
        char val[50];
};

int main() {

        struct HashTable *hashtab[HASHSIZE];  // declaration - 1

        struct HashTable hashtab2[HASHSIZE];  // declaration - 2
}
</code>```

declaration-1:

```<code>struct HashTable *hashtab[HASHSIZE];
</code>```

declaration-2:

```<code>struct HashTable hashtab2[HASHSIZE];
</code>```

As per my understanding, both declarations are seems to be doing same in memory layout of allocation. Like, allocating HASHSIZE of array of struct HashTable and variable pointing to the [0]th element of array of structs.

But, Still I feel that there is some difference that I might not be able to get it.

I want to know if there is a difference, how does one differ from another in memory layout (OR) allocation/accessing.

答:
As per my understanding, both declarations are seems to be doing same in memory layout of allocation.

This is demonstrably incorrect: they allocate structures of very different size (200 bytes vs. 2500 bytes on a 32-bit system).

Still I feel that there is some difference that I might not be able to get it.

The first one is an array of pointers. The second one is an array of structs. If you want to use the first array, and set anything into keys and vals, you need to allocate the struct first, for example, like this:

```<code>hashtab[pos] = malloc(sizeof(struct HashTable));
</code>```

You also need to dereference the pointer:

```<code>strcpy(hashtab[pos]->key, "hello"); // Note the -> operator
strcpy(hashtab[pos]->val, "world");
</code>```

On the other hand, hashtab2 has all its positions preallocated, and does not need dereferencing:

```<code>strcpy(hashtab2[pos].key, "hello"); // Using . instead of ->
strcpy(hashtab2[pos].val, "world");
</code>```

Body:
I am doing hash implementation. I have sample program below.

#define HASHSIZE 25

struct HashTable {
        char key[50];
        char val[50];
};

int main() {

        struct HashTable *hashtab[HASHSIZE];  // declaration - 1

        struct HashTable hashtab2[HASHSIZE];  // declaration - 2
}

declaration-1:

struct HashTable *hashtab[HASHSIZE];

declaration-2:

struct HashTable hashtab2[HASHSIZE];

As per my understanding, both declarations are seems to be doing same in memory layout of allocation. Like, allocating HASHSIZE of array of struct HashTable and variable pointing to the [0]th element of array of structs.

But, Still I feel that there is some difference that I might not be able to get it.

I want to know if there is a difference, how does one differ from another in memory layout (OR) allocation/accessing.

Body:
As per my understanding, both declarations are seems to be doing same in memory layout of allocation.

This is demonstrably incorrect: they allocate structures of very different size (200 bytes vs. 2500 bytes on a 32-bit system).

Still I feel that there is some difference that I might not be able to get it.

The first one is an array of pointers. The second one is an array of structs. If you want to use the first array, and set anything into keys and vals, you need to allocate the struct first, for example, like this:

hashtab[pos] = malloc(sizeof(struct HashTable));

You also need to dereference the pointer:

strcpy(hashtab[pos]->key, "hello"); // Note the -> operator
strcpy(hashtab[pos]->val, "world");

On the other hand, hashtab2 has all its positions preallocated, and does not need dereferencing:

strcpy(hashtab2[pos].key, "hello"); // Using . instead of ->
strcpy(hashtab2[pos].val, "world");


答:
There is no absolute way to do something, and everything depends on the project.

This topic is open to everybody's subjectivity.

IMO, if you use a block of code multiple times in a single test class, that block should be extracted in a local method.

If you use it in multiple test methods, you should look into inheritance or creating a small util class under test packages.

If the method is also needed in your main java code, it's then that you should write unit tests for it. The purpose of tests is to validate you runtime code. JUnit code is run pre-runtime.

Title: Do I need test method that is inside the test class


问:
Android Joda DateTime one hour off
I have a TimePickerDialog which lets the user pick a time. The TimePickerDialog has a onTimeSet method that gets called when the user finished picking the time.
I pass the arguments to a second method, setTime(int hour, int minute) which saves the values and displays a formatted time.
Here is a code snippet of the method:

```<code>java.text.DateFormat dateFormatter =
java.text.DateFormat.getTimeInstance(java.text.DateFormat.SHORT, Locale.getDefault());

DateTime dt = new DateTime();
dt = dt.hourOfDay().setCopy(hour);
dt = dt.minuteOfHour().setCopy(minute);
String text = dateFormatter.format(dt.toDate());
</code>```

The Problem is that (sometimes, not always) the hour value is off by one or maybe even two hours. I think the cause of the problem has something to do with timezones, but I do not know what the exact cause is. I also think that the problem is caused by the Joda DateTime object, since I did not have any issues before I implemented Joda time AND because it also gets saved with one hour off.
Any ideas what happens / how to fix it?

答:
For this answer, I'm using joda-time 2.7 (although it might work with previous versions).

I'm also assuming that your program only cares about hour and minute (I'm not an Android expert, but I saw docs from TimePickerDialog and it seems to be the case).

So, if you're manipulating only hour and minute, you don't need to use DateTime class (actually you shouldn't in this case).

That's because a DateTime object is "aware" of all date fields, including day, month, year and timezone. So, when you create a new DateTime(), it creates a new object with current date and time in your default timezone. And if the current date in default timezone is in summer time (aka daylight saving time), you can have these hour shifts.

(And I believe that Android takes the default timezone from the device's system, so it can vary according to the device running the code - at least that's how it works in computers, so it shouldn't be different for devices).

As you don't need to know day/month/year and timezone, you can use LocalTime class (org.joda.time.LocalTime) which is a class with only hour and minute fields (and seconds, if you want; if you don't care about seconds, they'll be set to zero). And the best part is: this class doesn't care about timezones, so 10:00 AM will always be 10:00 AM.

You also don't need to use java.text.DateFormat, as joda-time has its own formatters. So the code will be like this:

```<code>public void setTime(int hour, int minute) {
    // shortTime() is equivalent to DateFormat.SHORT
    DateTimeFormatter fmt = DateTimeFormat.shortTime().withLocale(Locale.getDefault());
    LocalTime time = new LocalTime(hour, minute);
    String text = fmt.print(time);
    System.out.println(text);
}
</code>```

Doing some tests (assuming default locale is en_US):

```<code>setTime(9, 30); // prints 9:30 AM
setTime(10, 0); // prints 10:00 AM
</code>```

PS: the output may vary according to your default Locale (which I also believe it comes from the device's system). If you want a fixed format (independent from locales), you can use DateTimeFormat.forPattern("h:mm a"), which also results in the output above (and when you use formatters this way, the default locale doesn't change the output).

Title: Android Joda DateTime one hour off

Body:
I have a TimePickerDialog which lets the user pick a time. The TimePickerDialog has a onTimeSet method that gets called when the user finished picking the time.
I pass the arguments to a second method, setTime(int hour, int minute) which saves the values and displays a formatted time.
Here is a code snippet of the method:

java.text.DateFormat dateFormatter =
java.text.DateFormat.getTimeInstance(java.text.DateFormat.SHORT, Locale.getDefault());

DateTime dt = new DateTime();
dt = dt.hourOfDay().setCopy(hour);
dt = dt.minuteOfHour().setCopy(minute);
String text = dateFormatter.format(dt.toDate());

The Problem is that (sometimes, not always) the hour value is off by one or maybe even two hours. I think the cause of the problem has something to do with timezones, but I do not know what the exact cause is. I also think that the problem is caused by the Joda DateTime object, since I did not have any issues before I implemented Joda time AND because it also gets saved with one hour off.
Any ideas what happens / how to fix it?

Body:
For this answer, I'm using joda-time 2.7 (although it might work with previous versions).

I'm also assuming that your program only cares about hour and minute (I'm not an Android expert, but I saw docs from TimePickerDialog and it seems to be the case).

So, if you're manipulating only hour and minute, you don't need to use DateTime class (actually you shouldn't in this case).

That's because a DateTime object is "aware" of all date fields, including day, month, year and timezone. So, when you create a new DateTime(), it creates a new object with current date and time in your default timezone. And if the current date in default timezone is in summer time (aka daylight saving time), you can have these hour shifts.

(And I believe that Android takes the default timezone from the device's system, so it can vary according to the device running the code - at least that's how it works in computers, so it shouldn't be different for devices).

As you don't need to know day/month/year and timezone, you can use LocalTime class (org.joda.time.LocalTime) which is a class with only hour and minute fields (and seconds, if you want; if you don't care about seconds, they'll be set to zero). And the best part is: this class doesn't care about timezones, so 10:00 AM will always be 10:00 AM.

You also don't need to use java.text.DateFormat, as joda-time has its own formatters. So the code will be like this:

public void setTime(int hour, int minute) {
    // shortTime() is equivalent to DateFormat.SHORT
    DateTimeFormatter fmt = DateTimeFormat.shortTime().withLocale(Locale.getDefault());
    LocalTime time = new LocalTime(hour, minute);
    String text = fmt.print(time);
    System.out.println(text);
}

Doing some tests (assuming default locale is en_US):

setTime(9, 30); // prints 9:30 AM
setTime(10, 0); // prints 10:00 AM

PS: the output may vary according to your default Locale (which I also believe it comes from the device's system). If you want a fixed format (independent from locales), you can use DateTimeFormat.forPattern("h:mm a"), which also results in the output above (and when you use formatters this way, the default locale doesn't change the output).


问:
How can I control which fields to serialize with YAML
For instance,

```<code>class Point
  attr_accessor :x, :y, :pointer_to_something_huge
end
</code>```

I only want to serialize x and y and leave everything else as nil.

答:
You should use #encode_with because #to_yaml_properties is deprecated:

```<code>def encode_with(coder)
  # remove @unwanted and @other_unwanted variable from the dump
  (instance_variables - [:@unwanted, :@other_unwanted]).each do |var|
    var = var.to_s                       # convert symbol to string
    coder[var.gsub('@', '')] = eval(var) # set key and value in coder hash
  end
end
</code>```

or you might prefer this if eval is too dangerous and you only need to filter out one instance var. All other vars need to have an accessor:

```<code>attr_accessor :keep_this, :unwanted

def encode_with(coder)
  # reject @unwanted var, all others need to have an accessor
  instance_variables.reject{|x|x==:@unwanted}.map(&:to_s).each do |var|
    coder[var[1..-1]] = send(var[1..-1])
  end
end
</code>```

Body:
For instance,

class Point
  attr_accessor :x, :y, :pointer_to_something_huge
end

I only want to serialize x and y and leave everything else as nil.

Body:
You should use #encode_with because #to_yaml_properties is deprecated:

def encode_with(coder)
  # remove @unwanted and @other_unwanted variable from the dump
  (instance_variables - [:@unwanted, :@other_unwanted]).each do |var|
    var = var.to_s                       # convert symbol to string
    coder[var.gsub('@', '')] = eval(var) # set key and value in coder hash
  end
end

or you might prefer this if eval is too dangerous and you only need to filter out one instance var. All other vars need to have an accessor:

attr_accessor :keep_this, :unwanted

def encode_with(coder)
  # reject @unwanted var, all others need to have an accessor
  instance_variables.reject{|x|x==:@unwanted}.map(&:to_s).each do |var|
    coder[var[1..-1]] = send(var[1..-1])
  end
end


问:
creating a form in excel using VBA
I am trying to creat a form in excel using VBA, but I am stuck at the Code. I need to find out the code to enter a data to my worksheet using VBA form . here is the code I am using, but doesn't work..

```<code>Private Sub cmdAdd_Click()

Dim LastRow As Range
Dim DPDIAdhocRequestTable As ListObject

With LastRow

    Cells(1, 2) = RequesterName.Value
    Cells(1, 3) = RequesterPhoneNumber.Value
    Cells(1, 4) = RequesterBureau.Value
    Cells(1, 5) = DateRequestMade.Value
    Cells(1, 6) = DateRequestDue.Value
    Cells(1, 7) = PurposeofRequest.Value
    Cells(1, 8) = ExpectedDataSaurce.Value
    Cells(1, 9) = Timeperiodofdatarequested.Value
    Cells(1, 10) = ReoccuringRequest.Value
    Cells(1, 11) = RequestNumber.Value
    Cells(1, 12) = AnalystAssigned.Value
    Cells(1, 13) = AnalystEstimatedDueDate.Value
    Cells(1, 14) = AnalystCompletedDate.Value
    Cells(1, 15) = SupervisiorName.Value

End With

End Sub
</code>```

can you help me to figure out the correct code for enter command?

thank you so much for your help.

答:
As @Adam said - you've created LastRow and not assigned it to anything.

 I'm guessing it's the next row you want to paste your data into, so it should be a Long holding the row number rather than an actual reference to the cell.

In the code below you could qualify the form controls by adding Me., for example Me.RequesterName.Value

https://msdn.microsoft.com/en-us/library/office/gg251792.aspx

```<code>Private Sub cmdAdd_Click()

    Dim wrkSht As Worksheet
    Dim LastRow As Long

    'The sheet you want the data to go into.
    Set wrkSht = ThisWorkbook.Worksheets("Sheet1")

    'You're after the last row number, rather than referencing the range so LastRow is a Long.
    'This looks for the last cell containing data in column A (the 1 in 'Cells(...)').
    LastRow = wrkSht.Cells(Rows.Count, 1).End(xlUp).Row + 1

    'With... End With block.  Cells is preceded by a '.' notation - indicating it's referencing the 'With wkrSht'#
    'https://msdn.microsoft.com/en-us/library/wc500chb.aspx
    With wrkSht

        'Using LastRow as row number in cell reference.
        .Cells(LastRow, 2) = RequesterName.Value

        'Before adding dates to the sheet you might want to check that the
        'user entered a date and not rubbish.
        .Cells(LastRow, 5) = DateRequestMade.Value
        'You could use CDATE to force it to a date - will try and coerce the entered text into a date.
        'Note - 1 will be changed to 01/01/1900 (so will need to add extra code to check it really is a date).
        .Cells(LastRow, 5) = CDate(DateRequestMade.Value)

    End With

End Sub
</code>```

Title: creating a form in excel using VBA

Body:
I am trying to creat a form in excel using VBA, but I am stuck at the Code. I need to find out the code to enter a data to my worksheet using VBA form . here is the code I am using, but doesn't work..

Private Sub cmdAdd_Click()

Dim LastRow As Range
Dim DPDIAdhocRequestTable As ListObject

With LastRow

    Cells(1, 2) = RequesterName.Value
    Cells(1, 3) = RequesterPhoneNumber.Value
    Cells(1, 4) = RequesterBureau.Value
    Cells(1, 5) = DateRequestMade.Value
    Cells(1, 6) = DateRequestDue.Value
    Cells(1, 7) = PurposeofRequest.Value
    Cells(1, 8) = ExpectedDataSaurce.Value
    Cells(1, 9) = Timeperiodofdatarequested.Value
    Cells(1, 10) = ReoccuringRequest.Value
    Cells(1, 11) = RequestNumber.Value
    Cells(1, 12) = AnalystAssigned.Value
    Cells(1, 13) = AnalystEstimatedDueDate.Value
    Cells(1, 14) = AnalystCompletedDate.Value
    Cells(1, 15) = SupervisiorName.Value

End With

End Sub

can you help me to figure out the correct code for enter command?

thank you so much for your help.

Body:
As @Adam said - you've created LastRow and not assigned it to anything.

 I'm guessing it's the next row you want to paste your data into, so it should be a Long holding the row number rather than an actual reference to the cell.

In the code below you could qualify the form controls by adding Me., for example Me.RequesterName.Value

https://msdn.microsoft.com/en-us/library/office/gg251792.aspx

Private Sub cmdAdd_Click()

    Dim wrkSht As Worksheet
    Dim LastRow As Long

    'The sheet you want the data to go into.
    Set wrkSht = ThisWorkbook.Worksheets("Sheet1")

    'You're after the last row number, rather than referencing the range so LastRow is a Long.
    'This looks for the last cell containing data in column A (the 1 in 'Cells(...)').
    LastRow = wrkSht.Cells(Rows.Count, 1).End(xlUp).Row + 1

    'With... End With block.  Cells is preceded by a '.' notation - indicating it's referencing the 'With wkrSht'#
    'https://msdn.microsoft.com/en-us/library/wc500chb.aspx
    With wrkSht

        'Using LastRow as row number in cell reference.
        .Cells(LastRow, 2) = RequesterName.Value

        'Before adding dates to the sheet you might want to check that the
        'user entered a date and not rubbish.
        .Cells(LastRow, 5) = DateRequestMade.Value
        'You could use CDATE to force it to a date - will try and coerce the entered text into a date.
        'Note - 1 will be changed to 01/01/1900 (so will need to add extra code to check it really is a date).
        .Cells(LastRow, 5) = CDate(DateRequestMade.Value)

    End With

End Sub


问:
JavaScript - Stop Bubbling
I wondered if someone could take a look at the following JS I need help on? What I want to happen is to be able to click the div and the alert box "Here" appear, which it does. I also want to be able to click the a and have the "Anchor" alert appear, which it does.

The problem is that the "Here" alert box then appears again. I've tried using .stopPropagation() but is not working as expected.

My code:

function testMessage() {
  alert("Here");
}

function anchorClick() {
  alert("Anchor");
  this.stopPropagation();
}

var products = document.getElementsByClassName('Wrapper')
var tags = document.getElementsByTagName('a')

for (let i = 0; i < products.length; i++) {
  products[i].onclick = function() {
    testMessage();
  }
}

for (let i = 0; i < tags.length; i++) {
  tags[i].onclick = function() {
    anchorClick();
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#Wrapper,
#Wrapper2 {
  height: 250px;
  width: 250px;
  background: #fff;
  cursor: pointer;
}</code>```

  Link1
  Link2
  Link3

  Link1
  Link2
  Link3

```

Please can you advise?

Cheers
Chris

答:
If you check the browser console, you'll find the following error:

Uncaught TypeError: this.stopPropagation is not a function

As you can see, this is not the object your're looking for but it's the window reference.

stopPropagation() is a method of the event object, see documentation here

See example:

function testMessage() {
  console.log("Here");
}

function anchorClick() {
  console.log("'this' references to window: " + this);
  console.log("Anchor");
  event.stopPropagation();
}

var products = document.getElementsByClassName('Wrapper')
var tags = document.getElementsByTagName('a')

for (let i = 0; i < products.length; i++) {
  products[i].onclick = function() {
    testMessage();
  }
}

for (let i = 0; i < tags.length; i++) {
  tags[i].onclick = function() {
    anchorClick();
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#Wrapper,
#Wrapper2 {
  height: 250px;
  width: 250px;
  background: #fff;
  cursor: pointer;
}</code>```

  Link1
  Link2
  Link3

  Link1
  Link2
  Link3

```

Title: JavaScript - Stop Bubbling

Body:
I wondered if someone could take a look at the following JS I need help on? What I want to happen is to be able to click the div and the alert box "Here" appear, which it does. I also want to be able to click the a and have the "Anchor" alert appear, which it does.

The problem is that the "Here" alert box then appears again. I've tried using .stopPropagation() but is not working as expected.

My code:

function testMessage() {
  alert("Here");
}

function anchorClick() {
  alert("Anchor");
  this.stopPropagation();
}

var products = document.getElementsByClassName('Wrapper')
var tags = document.getElementsByTagName('a')

for (let i = 0; i < products.length; i++) {
  products[i].onclick = function() {
    testMessage();
  }
}

for (let i = 0; i < tags.length; i++) {
  tags[i].onclick = function() {
    anchorClick();
  }
}

#Wrapper,
#Wrapper2 {
  height: 250px;
  width: 250px;
  background: #fff;
  cursor: pointer;
}

  Link1
  Link2
  Link3

  Link1
  Link2
  Link3

Please can you advise?

Cheers
Chris

Body:
If you check the browser console, you'll find the following error:

Uncaught TypeError: this.stopPropagation is not a function

As you can see, this is not the object your're looking for but it's the window reference.

stopPropagation() is a method of the event object, see documentation here

See example:

function testMessage() {
  console.log("Here");
}

function anchorClick() {
  console.log("'this' references to window: " + this);
  console.log("Anchor");
  event.stopPropagation();
}

var products = document.getElementsByClassName('Wrapper')
var tags = document.getElementsByTagName('a')

for (let i = 0; i < products.length; i++) {
  products[i].onclick = function() {
    testMessage();
  }
}

for (let i = 0; i < tags.length; i++) {
  tags[i].onclick = function() {
    anchorClick();
  }
}

#Wrapper,
#Wrapper2 {
  height: 250px;
  width: 250px;
  background: #fff;
  cursor: pointer;
}

<div class="Wrapper">
  <a href="#" class="anchor">Link1</a>
  <a href="#" class="anchor">Link2</a>
  <a href="#" class="anchor">Link3</a>
</div>

<div class="Wrapper">
  <a href="#" class="anchor">Link1</a>
  <a href="#" class="anchor">Link2</a>
  <a href="#" class="anchor">Link3</a>
</div>


问:
dx-select-box does not load when there is huge list of data - DevExtreme
I have a requirement where the data to be displayed in the select box can be as huge as 8000 records.

Currently when I try to bind the data to a dx-select-box using an array source, the control just crashes and it even hangs my browser.

Is there any way I can virtualize the data binding to load a handful of records at a time?

Note: I am using dev extreme angular2 library with 16.2.5 version

答:
Did you try to use the paginate option?

With this option selectbox will be able to render data step by step.

Usage:

```<code><dx-select-box
    [dataSource]="data"
    ...
></dx-select-box>
</code>```

TS:

```<code>import DataSource from 'devextreme/data/data_source';
@Component({
...
})
export class AppComponent {
    ...
    constructor(service: Service) {
        ...
        this.data = new DataSource({
            paginate: true,
            pageSize: 10,
            store: {
            type: "array",
                data: HUGE_ARRAY,
                key: "ID"
            }
        });
    }
}
</code>```

Body:
Did you try to use the paginate option?

With this option selectbox will be able to render data step by step.

Usage:

<dx-select-box
    [dataSource]="data"
    ...
></dx-select-box>

TS:

import DataSource from 'devextreme/data/data_source';
@Component({
...
})
export class AppComponent {
    ...
    constructor(service: Service) {
        ...
        this.data = new DataSource({
            paginate: true,
            pageSize: 10,
            store: {
            type: "array",
                data: HUGE_ARRAY,
                key: "ID"
            }
        });
    }
}


答:
The first is an array of pointers to HashTable structs - each element of the array is the address of a HashTable.  To use it, you'll need to allocate memory for a HashTable, then place the address of that memory into the array.  You'll need to do that for each element of the array.

The second is an array of HashTable structs - each element of the array is an actual HashTable struct, and the memory for it is allocated for you by the compiler.

Title: Difference between two structure variable declaration?


问:
Can i modify the Html.DisplayFor to show a substring of any charecter
I am working on an asp.net mvc 5.2.2. web application using Razor view engine. I am trying to modify the default Html.DisplayFor to show substring of 100 character followed by "..." on certain views ? so is this possible to achieved ?
Thanks

答: Personally my preference would be to create another read-only property in the model and have that return a truncated value. Probably using the truncate extension mentioned here.</p>


答: You don't need to test the test method (as others have pointed out). However, I would recommend storing the expected results as LocalDate instances rather than creating them on the fly from strings. That way you are safe from possible bugs in the conversion code.</p>


问:
Copy constructor called instead of Operator=
I’m trying to do a simple exercise now with a Matrix and I want to implement this operations: Matrix a, Matrix b, Matrix c(a), Matrix d = a, Matrix e = a + b. For the moment I keep it simple but later I want to do the same thing, but with dynamic allocation and later with smart pointers.

I declared an explicit copy constructor and I overloaded operator=, I also declared a destructor so I have the rule of three.

Here are my functions:

```<code>Matrix& Matrix::operator=(const Matrix& opEven)
{
    std::cout << "Operator = " << std::endl;
    for (int i = 0; i < ORD; i++)
    {
        for (int j = 0; j < ORD; j++)
        {
            arr1[i][j] = opEven.arr1[i][j];
        }
    }

    return *this;
}

Matrix::Matrix(const Matrix& obj)
{
    std::cout << "Constructing matrix using copy c-tor." << std::endl;
    for (int i = 0; i < ORD; i++)
    {
        for (int j = 0; j < ORD; j++)
        {
            arr1[i][j] = obj.arr1[i][j];
        }
    }
}
</code>```

The problem is that, when I try to use Matrix d = a my compiler use the copy constructor, not my operator=.

Output:

答:
When you call it like

```<code>Martix a;
Matrix b = a;
</code>```

it always uses copy constructor. Try this:

```<code>Matrix a;
Matrix b:
b = a;
</code>```

Basically, Matrix a = b; and Matrix a(b); is the same thing, because you are constructing matrix a using matrix b, so that causes a copy constructor call.

Body:
I’m trying to do a simple exercise now with a Matrix and I want to implement this operations: Matrix a, Matrix b, Matrix c(a), Matrix d = a, Matrix e = a + b. For the moment I keep it simple but later I want to do the same thing, but with dynamic allocation and later with smart pointers.

I declared an explicit copy constructor and I overloaded operator=, I also declared a destructor so I have the rule of three.

Here are my functions:

Matrix& Matrix::operator=(const Matrix& opEven)
{
    std::cout << "Operator = " << std::endl;
    for (int i = 0; i < ORD; i++)
    {
        for (int j = 0; j < ORD; j++)
        {
            arr1[i][j] = opEven.arr1[i][j];
        }
    }

    return *this;
}

Matrix::Matrix(const Matrix& obj)
{
    std::cout << "Constructing matrix using copy c-tor." << std::endl;
    for (int i = 0; i < ORD; i++)
    {
        for (int j = 0; j < ORD; j++)
        {
            arr1[i][j] = obj.arr1[i][j];
        }
    }
}

The problem is that, when I try to use Matrix d = a my compiler use the copy constructor, not my operator=.

Output:

Body:
When you call it like

Martix a;
Matrix b = a;

it always uses copy constructor. Try this:

Matrix a;
Matrix b:
b = a;

Basically, Matrix a = b; and Matrix a(b); is the same thing, because you are constructing matrix a using matrix b, so that causes a copy constructor call.


问:
How to make ui.R and server.R to import function and data from other file and plot in ShinyApp
I have a three parts of file that I want to use to make Shiny app.

coolplot.R

This is a code that stores function for plotting.

```<code>library(ggplot2)
library(tidyverse)
library(ggrepel)

#-------------------------
# Function
#-------------------------
plotit <- function (dat, x_thres, y_thres) {
  dat["Significant"] <- ifelse((dat$wt > x_thres |
                                  dat$mpg > y_thres ), 'NotSignif','Signif')
  p <- ggplot(dat, aes(wt, mpg)) +
       geom_point(alpha=0.8,size=2.75, aes(color=Significant)) +
       scale_color_manual(values=c("#B94024","#7D8D87")) +
       geom_vline(xintercept= x_thres, colour = '#B94024') +
       geom_hline(yintercept=y_thres, colour = '#B94024') +
       geom_text_repel(data=subset(dat, wt > x_thres | mpg > y_thres),
                       aes(wt,mpg,label=model),
                       box.padding = unit(0.35, "lines"),
                       point.padding = unit(0.3, "lines")
                       )  +
       theme(legend.position="none")

  return(p)

}

#-------------------------
# Begin main code
#-------------------------
# I literally want to use file as input not
# default mtcars variable
infile <- "https://gist.githubusercontent.com/seankross/a412dfbd88b3db70b74b/raw/5f23f993cd87c283ce766e7ac6b329ee7cc2e1d1/mtcars.csv"
dat <- read_delim(infile,delim=",", col_types = cols())
y_thres <- 25
x_thres <- 3
plotit(dat, x_thres, y_thres)
</code>```

The function basically takes the x-threshold and y-threshold
and make the plot like this:

Then I tried to construct the Shiny app that lets the user
slide through x-threshold and y-threshold based on the same input data
and calling the plotit function. As they slide the vertical, horizontal red lines, and labeling dots will change accordingly.

My  Shiny app files are these:

server.R

```<code>library(shiny)

# Define server logic for slider examples
function(input, output) {

  # Reactive expression to compose a data frame containing all of
  # the values
  sliderValues <- reactive({

    # Compose data frame
    data.frame(
      Name = c("X-threshold",
               "Y-threshold"
               ),
      Value = as.character(c(input$integer,
                             input$integer
                             )),
      stringsAsFactors=FALSE)
  })

  # Show the values using an HTML table
  output$values <- renderTable({
    sliderValues()
  })
}
</code>```

ui.R

```<code>library(shiny)

# Define UI for slider demo application
fluidPage(

  #  Application title
  titlePanel("Sliders"),

  # Sidebar with sliders that demonstrate various available
  # options
  sidebarLayout(
    sidebarPanel(
      # Simple integer interval
      sliderInput("integer", "X-threshold",
                  min=3, max=10, value=1),

      # Simple integer interval
      sliderInput("integer", "Y-threshold",
                  min=10, max=35, value=1)

    ),

    # Show a table summarizing the values entered
    mainPanel(
      tableOutput("values")
      # How can I output the plot from coolplot.R here????
    )
  )
)
</code>```

My question is how can I make ui.R import function from plot.R and
display the plot?

Currently it the Shiny looks like this (minus my comment), in RStudio.

答:
Is what you want? make sure your sliders have unique names please

```<code>library(ggplot2)
library(tidyverse)
library(ggrepel)
library(shiny)
#-------------------------
# Function
#-------------------------
plotit <- function (dat, x_thres, y_thres) {
  dat["Significant"] <- ifelse((dat$wt > x_thres |
                                  dat$mpg > y_thres ), 'NotSignif','Signif')
  p <- ggplot(dat, aes(wt, mpg)) +
    geom_point(alpha=0.8,size=2.75, aes(color=Significant)) +
    scale_color_manual(values=c("#B94024","#7D8D87")) +
    geom_vline(xintercept= x_thres, colour = '#B94024') +
    geom_hline(yintercept=y_thres, colour = '#B94024') +
    geom_text_repel(data=subset(dat, wt > x_thres | mpg > y_thres),
                    aes(wt,mpg,label=model),
                    box.padding = unit(0.35, "lines"),
                    point.padding = unit(0.3, "lines")
    )  +
    theme(legend.position="none")

  return(p)

}

#-------------------------
# Begin main code
#-------------------------
# I literally want to use file as input not
# default mtcars variable
infile <- "https://gist.githubusercontent.com/seankross/a412dfbd88b3db70b74b/raw/5f23f993cd87c283ce766e7ac6b329ee7cc2e1d1/mtcars.csv"
dat <- read_delim(infile,delim=",", col_types = cols())
y_thres <- 25
x_thres <- 3
plotit(dat, x_thres, y_thres)

ui <- shinyUI(
  fluidPage(

    #  Application title
    titlePanel("Sliders"),

    # Sidebar with sliders that demonstrate various available
    # options
    sidebarLayout(
      sidebarPanel(
        # Simple integer interval
        sliderInput("integer", "X-threshold",
                    min=3, max=10, value=1),

        # Simple integer interval
        sliderInput("integer2", "Y-threshold",
                    min=10, max=35, value=1)

      ),

      # Show a table summarizing the values entered
      mainPanel(
        tableOutput("values"),
        plotOutput("myplot")
        # How can I output the plot from coolplot.R here????
      )
    )
  )
)

server <- shinyServer(function(input, output, session) {
  # Reactive expression to compose a data frame containing all of
  # the values

  sliderValues <- reactive({

    # Compose data frame
    data.frame(Name = c("X-threshold", "Y-threshold"),
      Value = as.character(c(input$integer, input$integer2)),
      stringsAsFactors=FALSE)
  })

  # Show the values using an HTML table
  output$values <- renderTable({
    sliderValues()
  })

  output$myplot <- renderPlot({

    plotit(dat, input$integer, input$integer2)
  })

})

shinyApp(ui = ui, server = server)
</code>```

Edit: load the plot function from a file

coolplot.R

```<code>library(ggplot2)
library(tidyverse)
library(ggrepel)

#-------------------------
# Function
#-------------------------
#-------------------------
# Begin main code
#-------------------------
# I literally want to use file as input not
# default mtcars variable
infile <- "https://gist.githubusercontent.com/seankross/a412dfbd88b3db70b74b/raw/5f23f993cd87c283ce766e7ac6b329ee7cc2e1d1/mtcars.csv"
dat <- read_delim(infile,delim=",", col_types = cols())

plotit <- function (dat, x_thres, y_thres) {
  dat["Significant"] <- ifelse((dat$wt > x_thres |
                                  dat$mpg > y_thres ), 'NotSignif','Signif')
  p <- ggplot(dat, aes(wt, mpg)) +
    geom_point(alpha=0.8,size=2.75, aes(color=Significant)) +
    scale_color_manual(values=c("#B94024","#7D8D87")) +
    geom_vline(xintercept= x_thres, colour = '#B94024') +
    geom_hline(yintercept=y_thres, colour = '#B94024') +
    geom_text_repel(data=subset(dat, wt > x_thres | mpg > y_thres),
                    aes(wt,mpg,label=model),
                    box.padding = unit(0.35, "lines"),
                    point.padding = unit(0.3, "lines")
    )  +
    theme(legend.position="none")

  return(p)
}
</code>```

Shiny Part

```<code>   library(shiny)
    source("coolplot.R",local = TRUE)$value

    ui <- shinyUI(
      fluidPage(

        #  Application title
        titlePanel("Sliders"),

        # Sidebar with sliders that demonstrate various available
        # options
        sidebarLayout(
          sidebarPanel(
            # Simple integer interval
            sliderInput("integer", "X-threshold",
                        min=3, max=10, value=1),

            # Simple integer interval
            sliderInput("integer2", "Y-threshold",
                        min=10, max=35, value=1)

          ),

          # Show a table summarizing the values entered
          mainPanel(
            tableOutput("values"),
            plotOutput("myplot")
            # How can I output the plot from coolplot.R here????
          )
        )
      )
    )

    server <- shinyServer(function(input, output, session) {
      # Reactive expression to compose a data frame containing all of
      # the values

      # Add the source file of the plot if necessary

      sliderValues <- reactive({

        # Compose data frame
        data.frame(Name = c("X-threshold", "Y-threshold"),
          Value = as.character(c(input$integer, input$integer2)),
          stringsAsFactors=FALSE)
      })

      # Show the values using an HTML table
      output$values <- renderTable({
        sliderValues()
      })

      output$myplot <- renderPlot({

        plotit(dat, input$integer, input$integer2)
      })

    })

    shinyApp(ui = ui, server = server)
</code>```

Body:
I have a three parts of file that I want to use to make Shiny app.

coolplot.R

This is a code that stores function for plotting.

library(ggplot2)
library(tidyverse)
library(ggrepel)

#-------------------------
# Function
#-------------------------
plotit <- function (dat, x_thres, y_thres) {
  dat["Significant"] <- ifelse((dat$wt > x_thres |
                                  dat$mpg > y_thres ), 'NotSignif','Signif')
  p <- ggplot(dat, aes(wt, mpg)) +
       geom_point(alpha=0.8,size=2.75, aes(color=Significant)) +
       scale_color_manual(values=c("#B94024","#7D8D87")) +
       geom_vline(xintercept= x_thres, colour = '#B94024') +
       geom_hline(yintercept=y_thres, colour = '#B94024') +
       geom_text_repel(data=subset(dat, wt > x_thres | mpg > y_thres),
                       aes(wt,mpg,label=model),
                       box.padding = unit(0.35, "lines"),
                       point.padding = unit(0.3, "lines")
                       )  +
       theme(legend.position="none")

  return(p)

}

#-------------------------
# Begin main code
#-------------------------
# I literally want to use file as input not
# default mtcars variable
infile <- "https://gist.githubusercontent.com/seankross/a412dfbd88b3db70b74b/raw/5f23f993cd87c283ce766e7ac6b329ee7cc2e1d1/mtcars.csv"
dat <- read_delim(infile,delim=",", col_types = cols())
y_thres <- 25
x_thres <- 3
plotit(dat, x_thres, y_thres)

The function basically takes the x-threshold and y-threshold
and make the plot like this:

Then I tried to construct the Shiny app that lets the user
slide through x-threshold and y-threshold based on the same input data
and calling the plotit function. As they slide the vertical, horizontal red lines, and labeling dots will change accordingly.

My  Shiny app files are these:

server.R

library(shiny)

# Define server logic for slider examples
function(input, output) {

  # Reactive expression to compose a data frame containing all of
  # the values
  sliderValues <- reactive({

    # Compose data frame
    data.frame(
      Name = c("X-threshold",
               "Y-threshold"
               ),
      Value = as.character(c(input$integer,
                             input$integer
                             )),
      stringsAsFactors=FALSE)
  })

  # Show the values using an HTML table
  output$values <- renderTable({
    sliderValues()
  })
}

ui.R

library(shiny)

# Define UI for slider demo application
fluidPage(

  #  Application title
  titlePanel("Sliders"),

  # Sidebar with sliders that demonstrate various available
  # options
  sidebarLayout(
    sidebarPanel(
      # Simple integer interval
      sliderInput("integer", "X-threshold",
                  min=3, max=10, value=1),

      # Simple integer interval
      sliderInput("integer", "Y-threshold",
                  min=10, max=35, value=1)

    ),

    # Show a table summarizing the values entered
    mainPanel(
      tableOutput("values")
      # How can I output the plot from coolplot.R here????
    )
  )
)

My question is how can I make ui.R import function from plot.R and
display the plot?

Currently it the Shiny looks like this (minus my comment), in RStudio.

Body:
Is what you want? make sure your sliders have unique names please

library(ggplot2)
library(tidyverse)
library(ggrepel)
library(shiny)
#-------------------------
# Function
#-------------------------
plotit <- function (dat, x_thres, y_thres) {
  dat["Significant"] <- ifelse((dat$wt > x_thres |
                                  dat$mpg > y_thres ), 'NotSignif','Signif')
  p <- ggplot(dat, aes(wt, mpg)) +
    geom_point(alpha=0.8,size=2.75, aes(color=Significant)) +
    scale_color_manual(values=c("#B94024","#7D8D87")) +
    geom_vline(xintercept= x_thres, colour = '#B94024') +
    geom_hline(yintercept=y_thres, colour = '#B94024') +
    geom_text_repel(data=subset(dat, wt > x_thres | mpg > y_thres),
                    aes(wt,mpg,label=model),
                    box.padding = unit(0.35, "lines"),
                    point.padding = unit(0.3, "lines")
    )  +
    theme(legend.position="none")

  return(p)

}

#-------------------------
# Begin main code
#-------------------------
# I literally want to use file as input not
# default mtcars variable
infile <- "https://gist.githubusercontent.com/seankross/a412dfbd88b3db70b74b/raw/5f23f993cd87c283ce766e7ac6b329ee7cc2e1d1/mtcars.csv"
dat <- read_delim(infile,delim=",", col_types = cols())
y_thres <- 25
x_thres <- 3
plotit(dat, x_thres, y_thres)

ui <- shinyUI(
  fluidPage(

    #  Application title
    titlePanel("Sliders"),

    # Sidebar with sliders that demonstrate various available
    # options
    sidebarLayout(
      sidebarPanel(
        # Simple integer interval
        sliderInput("integer", "X-threshold",
                    min=3, max=10, value=1),

        # Simple integer interval
        sliderInput("integer2", "Y-threshold",
                    min=10, max=35, value=1)

      ),

      # Show a table summarizing the values entered
      mainPanel(
        tableOutput("values"),
        plotOutput("myplot")
        # How can I output the plot from coolplot.R here????
      )
    )
  )
)

server <- shinyServer(function(input, output, session) {
  # Reactive expression to compose a data frame containing all of
  # the values

  sliderValues <- reactive({

    # Compose data frame
    data.frame(Name = c("X-threshold", "Y-threshold"),
      Value = as.character(c(input$integer, input$integer2)),
      stringsAsFactors=FALSE)
  })

  # Show the values using an HTML table
  output$values <- renderTable({
    sliderValues()
  })

  output$myplot <- renderPlot({

    plotit(dat, input$integer, input$integer2)
  })

})

shinyApp(ui = ui, server = server)

Edit: load the plot function from a file

coolplot.R

library(ggplot2)
library(tidyverse)
library(ggrepel)

#-------------------------
# Function
#-------------------------
#-------------------------
# Begin main code
#-------------------------
# I literally want to use file as input not
# default mtcars variable
infile <- "https://gist.githubusercontent.com/seankross/a412dfbd88b3db70b74b/raw/5f23f993cd87c283ce766e7ac6b329ee7cc2e1d1/mtcars.csv"
dat <- read_delim(infile,delim=",", col_types = cols())

plotit <- function (dat, x_thres, y_thres) {
  dat["Significant"] <- ifelse((dat$wt > x_thres |
                                  dat$mpg > y_thres ), 'NotSignif','Signif')
  p <- ggplot(dat, aes(wt, mpg)) +
    geom_point(alpha=0.8,size=2.75, aes(color=Significant)) +
    scale_color_manual(values=c("#B94024","#7D8D87")) +
    geom_vline(xintercept= x_thres, colour = '#B94024') +
    geom_hline(yintercept=y_thres, colour = '#B94024') +
    geom_text_repel(data=subset(dat, wt > x_thres | mpg > y_thres),
                    aes(wt,mpg,label=model),
                    box.padding = unit(0.35, "lines"),
                    point.padding = unit(0.3, "lines")
    )  +
    theme(legend.position="none")

  return(p)
}

Shiny Part

   library(shiny)
    source("coolplot.R",local = TRUE)$value

    ui <- shinyUI(
      fluidPage(

        #  Application title
        titlePanel("Sliders"),

        # Sidebar with sliders that demonstrate various available
        # options
        sidebarLayout(
          sidebarPanel(
            # Simple integer interval
            sliderInput("integer", "X-threshold",
                        min=3, max=10, value=1),

            # Simple integer interval
            sliderInput("integer2", "Y-threshold",
                        min=10, max=35, value=1)

          ),

          # Show a table summarizing the values entered
          mainPanel(
            tableOutput("values"),
            plotOutput("myplot")
            # How can I output the plot from coolplot.R here????
          )
        )
      )
    )

    server <- shinyServer(function(input, output, session) {
      # Reactive expression to compose a data frame containing all of
      # the values

      # Add the source file of the plot if necessary

      sliderValues <- reactive({

        # Compose data frame
        data.frame(Name = c("X-threshold", "Y-threshold"),
          Value = as.character(c(input$integer, input$integer2)),
          stringsAsFactors=FALSE)
      })

      # Show the values using an HTML table
      output$values <- renderTable({
        sliderValues()
      })

      output$myplot <- renderPlot({

        plotit(dat, input$integer, input$integer2)
      })

    })

    shinyApp(ui = ui, server = server)


问:
Docusign Connect - Client is behind firewall
I need to configure docusign connect to push notifications to my application server, however it is behind a firewall.  I do have a proxy but I dont see any options for configuring a proxy in the connect settings.  Any advice on how to proceed with this?</p>

答:
There is no option to  configuring a proxy in the DocuSign connect settings.

Here are some of the requirements for DocuSign connect.

Your app must include a listener HTTPS URL that DocuSign can POST to.

This URL must be available on the public internet.

It can’t be blocked by a firewall.

Here is good DocuSign blog post which discusses options when your listener is behind a firewall. Here are some of the options posted in the blog post.

You can install your listener on a Heroku, Amazon, Azure or private server that is available on the internet.

you can use a service such as ngrok to tunnel the incoming requests to your machine which is behind your fire wall.

Your server can be located on your organization’s DMZ, providing access to the internet.

Your firewall can be opened (a “pinhole opening”) to enable the incoming notification requests from DocuSign to reach your listener.

You will need to work with your IT and InfoSec departments to determine the best answer for your configuration.


问:
Make histogram of pixel intensities without imhist
I have used the unique command to get the unique pixel intensities from my image. Then I tried to make a histogram using them, but it doesn't use all of the intensity values

```<code>I = imread('pout.tif');
[rows, columns] = size(I);
UniquePixels=unique(I);
hist=histogram(UniquePixels)
</code>```

答:
An alternative approach would be to use accumarray combined with unique.  I would specifically use the third output of unique to transform your data into a consecutive sequence of 1 up to N where N is the total number of unique intensities, then leverage the first output of unique that will give you the list of unique intensities.  Therefore, if the first output of unique is A and the output of accumarray is B, the effect is that at location B(i), this gives the total number of intensities of A(i).

Therefore:

```<code>[UniquePixels, ~, id] = unique(I);
histo = accumarray(id, 1);
</code>```

UniquePixels gives you all unique pixels while histo gives you the counts of each unique pixel corresponding to each element in UniquePixels.

Here's a quick example:

```<code>>> I = randi(255, 10, 10)

I =

    42   115    28   111   218   107   199    60   140   237
   203    22   246   233   159    13   100    91    76   198
    80    59     2    47    90   231    62   210   190   125
   135   233   198    68   131   241   103     4    49   112
    43    39   209    38   103   126    25    11   176   114
   154   211   222    35    20   125    34    44    47    79
    68   138    22   222    62    87   241   166    94   130
   167   255   102   148    32   230   244   187   160   131
   176    20    67   141    47    95   147   166   199   209
   191   113   205    37    62    29    16   115    21   203

>> [UniquePixels, ~, id] = unique(I);
>> histo = accumarray(id, 1);
>> [UniquePixels histo]

ans =

     2     1
     4     1
    11     1
    13     1
    16     1
    20     2
    21     1
    22     2
    25     1
    28     1
    29     1
    32     1
    34     1
    35     1
    37     1
    38     1
    39     1
    42     1
    43     1
    44     1
    47     3
    49     1
    59     1
    60     1
    62     3
    67     1
    68     2
    76     1
    79     1
    80     1
    87     1
    90     1
    91     1
    94     1
    95     1
   100     1
   102     1
   103     2
   107     1
   111     1
   112     1
   113     1
   114     1
   115     2
   125     2
   126     1
   130     1
   131     2
   135     1
   138     1
   140     1
   141     1
   147     1
   148     1
   154     1
   159     1
   160     1
   166     2
   167     1
   176     2
   187     1
   190     1
   191     1
   198     2
   199     2
   203     2
   205     1
   209     2
   210     1
   211     1
   218     1
   222     2
   230     1
   231     1
   233     2
   237     1
   241     2
   244     1
   246     1
   255     1
</code>```

If you double check the input example and the final output, you will see that only the unique pixels are shown combined with their counts.  Any bins that were zero in count are not shown.

Body:
I have used the unique command to get the unique pixel intensities from my image. Then I tried to make a histogram using them, but it doesn't use all of the intensity values

I = imread('pout.tif');
[rows, columns] = size(I);
UniquePixels=unique(I);
hist=histogram(UniquePixels)

Body:
An alternative approach would be to use accumarray combined with unique.  I would specifically use the third output of unique to transform your data into a consecutive sequence of 1 up to N where N is the total number of unique intensities, then leverage the first output of unique that will give you the list of unique intensities.  Therefore, if the first output of unique is A and the output of accumarray is B, the effect is that at location B(i), this gives the total number of intensities of A(i).

Therefore:

[UniquePixels, ~, id] = unique(I);
histo = accumarray(id, 1);

UniquePixels gives you all unique pixels while histo gives you the counts of each unique pixel corresponding to each element in UniquePixels.

Here's a quick example:

>> I = randi(255, 10, 10)

I =

    42   115    28   111   218   107   199    60   140   237
   203    22   246   233   159    13   100    91    76   198
    80    59     2    47    90   231    62   210   190   125
   135   233   198    68   131   241   103     4    49   112
    43    39   209    38   103   126    25    11   176   114
   154   211   222    35    20   125    34    44    47    79
    68   138    22   222    62    87   241   166    94   130
   167   255   102   148    32   230   244   187   160   131
   176    20    67   141    47    95   147   166   199   209
   191   113   205    37    62    29    16   115    21   203

>> [UniquePixels, ~, id] = unique(I);
>> histo = accumarray(id, 1);
>> [UniquePixels histo]

ans =

     2     1
     4     1
    11     1
    13     1
    16     1
    20     2
    21     1
    22     2
    25     1
    28     1
    29     1
    32     1
    34     1
    35     1
    37     1
    38     1
    39     1
    42     1
    43     1
    44     1
    47     3
    49     1
    59     1
    60     1
    62     3
    67     1
    68     2
    76     1
    79     1
    80     1
    87     1
    90     1
    91     1
    94     1
    95     1
   100     1
   102     1
   103     2
   107     1
   111     1
   112     1
   113     1
   114     1
   115     2
   125     2
   126     1
   130     1
   131     2
   135     1
   138     1
   140     1
   141     1
   147     1
   148     1
   154     1
   159     1
   160     1
   166     2
   167     1
   176     2
   187     1
   190     1
   191     1
   198     2
   199     2
   203     2
   205     1
   209     2
   210     1
   211     1
   218     1
   222     2
   230     1
   231     1
   233     2
   237     1
   241     2
   244     1
   246     1
   255     1

If you double check the input example and the final output, you will see that only the unique pixels are shown combined with their counts.  Any bins that were zero in count are not shown.


问:
Metric and Imperial internal representation
I want to use metric and Imperial distance units in an application. One way of doing this is tagging a number with the unit. I don't want to go this route.

I want to use one internal representation that can exactly hold imperial down to 1/64 of an inch and 0.2mm. I have come up with 8128 RSU (really small units) that is divisible by 64 and 254, which does what I want.

This is close to 2^13, and it has got me wondering if there is a more optimal way of doing this?

Any ideas?

答: A slightly simpler solution might be to use "Other small units" so that 1 OSU = 1/320 mm. With this convention, 1/64" would be 127 OSU and 0.2mm would be 64 OSU. Since 127 and 64 are relative primes, this is the lowest denominator you can get. </p>


问:
Getting OOM with processing .xls using PHPExcel
I'm aware of How to read large worksheets from large Excel files (27MB+) with PHPExcel? and I've tried to implement the chunked reading that is discussed in that question however I'm still suffering from a OOM errror. The file itself is just under 5Mb, 9000+ rows (yes, it's over 9000!) ranging from A to V.

I'd rather not have the user do any editing on this file before uploading and processing it, as currently it's all a manual process and I'd like to completely replace it with a automated one. The file is of xls format, identified as Excel5 via PHPExcel.

my PHP memory limit is currently set to 128M, running on Ubuntu Server.

No matter what chunk size I set, I end up OOM'ing eventually. With larger chunk sizes it actually runs better (as in I can manage up to around row 7000) if I set the chunk size to 200, when set to 1 it OOM's around row 370. So I believe that 'something' is being stored, or loaded into memory in each iteration of the chunk reading and then not dropped again eventually causing the OOM but I can't see where this is happening.

I'm very much an amateur programmer, this is just something I'm doing on the side in my managed service role at work to try and make our lives easier.

The whole point of this code is to read the excel file, filter out the 'crap' and then save it out as CSV (Right now I'm just dumping it to screen instead of a CSV). At the rate things are going I'm getting tempted to call excel2csv via the php script and then try and clean up the CSV instead... But that feels like giving up when I maybe rather close to a solution.

```<code><?php

error_reporting(E_ALL);
set_time_limit(0);
date_default_timezone_set('Europe/London');

require_once 'Classes/PHPExcel/IOFactory.php';

class chunkReadFilter implements PHPExcel_Reader_IReadFilter
{
        private $_startRow = 0;
        private $_endRow = 0;
        private $_columns = array();

        /**  Set the list of rows that we want to read  */
        public function setRows($startRow, $chunkSize, $columns) {
                $this->_startRow        = $startRow;
                $this->_endRow          = $startRow + $chunkSize;
                $this->_columns         = $columns;
        }
        public function readCell($column, $row, $worksheetName = '') {
                //  Only read the heading row, and the rows that are configured in $this->_startRow$
                if ($row >= $this->_startRow && $row < $this->_endRow) {
                        if(in_array($column,$this->_columns)) {
                                return true;
                        }
                }
                return false;
        }
}
$target_dir = "uploads/";
$file_name = $_POST["file_name"];

$full_path = $target_dir . $file_name;

echo "Processing ". $file_name . '; <br>';

ob_flush();
flush();

/** /** As files maybe large in memory, use a temp file to handle them
$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;
$cacheSettings = array( 'memoryCacheSize' => '8MB');
PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
**/

$inputFileName = $full_path;

echo 'Excel reader started<br/>';

/** First we should get the type of file **/

$filetype = PHPExcel_IOFactory::identify($inputFileName);

echo 'File of type: ' . $filetype . ' found<br/>';

/** Load $inputFileName to a PHPExcel Object  - https://github.com/PHPOffice/PHPExcel/blob/develop/$

/**  Define how many rows we want to read for each "chunk"  **/
$chunkSize = 1;
/**  Create a new Instance of our Read Filter  **/
$chunkFilter = new chunkReadFilter();

$objReader = PHPExcel_IOFactory::createReader($filetype);

/**  Tell the Reader that we want to use the Read Filter that we've Instantiated  **/
$objReader->setReadFilter($chunkFilter);
/**  Loop to read our worksheet in "chunk size" blocks  **/
for ($startRow = 2; $startRow <= 65000; $startRow += $chunkSize) {
        $endRow = $startRow+$chunkSize-1;
        echo 'Loading WorkSheet using configurable filter for headings row 1 and for rows ',$startR$
        /**  Tell the Read Filter, the limits on which rows we want to read this iteration  **/
        $chunkFilter->setRows($startRow,$chunkSize,range('A','T'));
        /**  Load only the rows that match our filter from $inputFileName to a PHPExcel Object  **/
        $objPHPExcel = $objReader->load($inputFileName);
        //      Do some processing here
//      $sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
        $sheetData = $objPHPExcel->getActiveSheet()->rangeToArray("A$startRow:T$endRow");
        var_dump($sheetData);
        // Clear the variable to not go over memory!
        $objPHPExcel->disconnectWorksheets();
        unset ($sheetData);
        unset ($objPHPExcel);
        ob_flush();
        flush();

        echo '<br /><br />';
}

/**  This loads the entire file,  crashing with OOM

try {
        $objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
        echo 'loaded sheet into memory<br>';
} catch(PHPExcel_Reader_Exception $e) {
    die('Error loading file: '.$e->getMessage());
}

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');

echo 'Saving sheet as CSV<br>';

    $objWriter->setSheetIndex(0);
    $objWriter->save('./uploads/'.$file_name.'.csv');
    echo 'Processed 1 sheet';
    ob_flush();
flush();

**/

echo "<body><table>\n\n";

/**
$f = fopen($file_name, "r");
while (($line = fgetcsv($f)) !== false) {
        echo "<tr>";
        foreach ($line as $cell) {
                echo "<td>" . htmlspecialchars($cell) . "</td>";
        }
        echo "</tr>\n";
}
fclose($f);
**/

echo "\n</table></body></html>";

?>
</code>```

The error as indicated in the apache logs is:

```<code>[Fri Mar 31 15:35:27.982697 2017] [:error] [pid 1059] [client 10.0.2.2:53866] PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 45056 bytes) in /var/www/html/Classes/PHPExcel/Shared/OLERead.php on line 93, referer: http://localhost:8080/upload.php
</code>```

答:
```<code>unset ($objPHPExcel);
</code>```

If you check the PHPExcel documentation, this won't cleanly unset $objPHPExcel because of cyclic references between the spreadsheet, worksheet and cells, and will result in memory leaks. The recommendation is to disconnect these cyclic references first.

```<code>$objPHPExcel->disconnectWorksheets();
unset($objPHPExcel);
</code>```

There will still be some memory leakage, but it should allow more memory to be freed up between chunks

Body:
I'm aware of How to read large worksheets from large Excel files (27MB+) with PHPExcel? and I've tried to implement the chunked reading that is discussed in that question however I'm still suffering from a OOM errror. The file itself is just under 5Mb, 9000+ rows (yes, it's over 9000!) ranging from A to V.

I'd rather not have the user do any editing on this file before uploading and processing it, as currently it's all a manual process and I'd like to completely replace it with a automated one. The file is of xls format, identified as Excel5 via PHPExcel.

my PHP memory limit is currently set to 128M, running on Ubuntu Server.

No matter what chunk size I set, I end up OOM'ing eventually. With larger chunk sizes it actually runs better (as in I can manage up to around row 7000) if I set the chunk size to 200, when set to 1 it OOM's around row 370. So I believe that 'something' is being stored, or loaded into memory in each iteration of the chunk reading and then not dropped again eventually causing the OOM but I can't see where this is happening.

I'm very much an amateur programmer, this is just something I'm doing on the side in my managed service role at work to try and make our lives easier.

The whole point of this code is to read the excel file, filter out the 'crap' and then save it out as CSV (Right now I'm just dumping it to screen instead of a CSV). At the rate things are going I'm getting tempted to call excel2csv via the php script and then try and clean up the CSV instead... But that feels like giving up when I maybe rather close to a solution.

<?php

error_reporting(E_ALL);
set_time_limit(0);
date_default_timezone_set('Europe/London');

require_once 'Classes/PHPExcel/IOFactory.php';

class chunkReadFilter implements PHPExcel_Reader_IReadFilter
{
        private $_startRow = 0;
        private $_endRow = 0;
        private $_columns = array();

        /**  Set the list of rows that we want to read  */
        public function setRows($startRow, $chunkSize, $columns) {
                $this->_startRow        = $startRow;
                $this->_endRow          = $startRow + $chunkSize;
                $this->_columns         = $columns;
        }
        public function readCell($column, $row, $worksheetName = '') {
                //  Only read the heading row, and the rows that are configured in $this->_startRow$
                if ($row >= $this->_startRow && $row < $this->_endRow) {
                        if(in_array($column,$this->_columns)) {
                                return true;
                        }
                }
                return false;
        }
}
$target_dir = "uploads/";
$file_name = $_POST["file_name"];

$full_path = $target_dir . $file_name;

echo "Processing ". $file_name . ';
';

ob_flush();
flush();

/** /** As files maybe large in memory, use a temp file to handle them
$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;
$cacheSettings = array( 'memoryCacheSize' => '8MB');
PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
**/

$inputFileName = $full_path;

echo 'Excel reader started
';

/** First we should get the type of file **/

$filetype = PHPExcel_IOFactory::identify($inputFileName);

echo 'File of type: ' . $filetype . ' found
';

/** Load $inputFileName to a PHPExcel Object  - https://github.com/PHPOffice/PHPExcel/blob/develop/$

/**  Define how many rows we want to read for each "chunk"  **/
$chunkSize = 1;
/**  Create a new Instance of our Read Filter  **/
$chunkFilter = new chunkReadFilter();

$objReader = PHPExcel_IOFactory::createReader($filetype);

/**  Tell the Reader that we want to use the Read Filter that we've Instantiated  **/
$objReader->setReadFilter($chunkFilter);
/**  Loop to read our worksheet in "chunk size" blocks  **/
for ($startRow = 2; $startRow <= 65000; $startRow += $chunkSize) {
        $endRow = $startRow+$chunkSize-1;
        echo 'Loading WorkSheet using configurable filter for headings row 1 and for rows ',$startR$
        /**  Tell the Read Filter, the limits on which rows we want to read this iteration  **/
        $chunkFilter->setRows($startRow,$chunkSize,range('A','T'));
        /**  Load only the rows that match our filter from $inputFileName to a PHPExcel Object  **/
        $objPHPExcel = $objReader->load($inputFileName);
        //      Do some processing here
//      $sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
        $sheetData = $objPHPExcel->getActiveSheet()->rangeToArray("A$startRow:T$endRow");
        var_dump($sheetData);
        // Clear the variable to not go over memory!
        $objPHPExcel->disconnectWorksheets();
        unset ($sheetData);
        unset ($objPHPExcel);
        ob_flush();
        flush();

        echo '

';
}

/**  This loads the entire file,  crashing with OOM

try {
        $objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
        echo 'loaded sheet into memory
';
} catch(PHPExcel_Reader_Exception $e) {
    die('Error loading file: '.$e->getMessage());
}

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');

echo 'Saving sheet as CSV
';

    $objWriter->setSheetIndex(0);
    $objWriter->save('./uploads/'.$file_name.'.csv');
    echo 'Processed 1 sheet';
    ob_flush();
flush();

**/

echo "
\n\n";

/**
$f = fopen($file_name, "r");
while (($line = fgetcsv($f)) !== false) {
        echo "
";
        foreach ($line as $cell) {
                echo "" . htmlspecialchars($cell) . "	";
        }
        echo "
\n";
}
fclose($f);
**/

echo "\n
";

?>

The error as indicated in the apache logs is:

[Fri Mar 31 15:35:27.982697 2017] [:error] [pid 1059] [client 10.0.2.2:53866] PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 45056 bytes) in /var/www/html/Classes/PHPExcel/Shared/OLERead.php on line 93, referer: http://localhost:8080/upload.php

Body:
unset ($objPHPExcel);

If you check the PHPExcel documentation, this won't cleanly unset $objPHPExcel because of cyclic references between the spreadsheet, worksheet and cells, and will result in memory leaks. The recommendation is to disconnect these cyclic references first.

$objPHPExcel->disconnectWorksheets();
unset($objPHPExcel);

There will still be some memory leakage, but it should allow more memory to be freed up between chunks


问:
android: no such instance field
I'm trying to get data thru AsyncTask with web service.
I have no idea why as I declared global variable 'arrayList1' and it has been initialized, but I'm getting error for the 'arrayList1' and it skipped doin the new AsyncTask.</p>

```<code>private Context mContext;
private ArrayList arrayList1;
private ArrayList<List> mData;
private ListView mListView;
private ListViewAdapter mAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

mContext = getApplicationContext();
mListView = (ListView)findViewById(R.id.listView1);
mData = new ArrayList<List>();
mData = LoadListView();
}

public ArrayList<List> LoadListView(Void...params) {
    arrayList1 = new ArrayList();
    //here error occurred.
    new AsyncTask<Void, Void, ArrayList<List>>() {
        @Override
        protected ArrayList<List> doInBackground(Void...params) {
            arrayList1 = GetData();
            //GetData() is another function will return a arraylist from web service.
            return arrayList1;
        }

        @Override
        protected void onPostExecute(ArrayList<List> arrayList) {
            mAdapter = new ListViewAdapter(arrayList, mContext);
            mAdapter.notifyDataSetChanged();
            mListView.setAdapter(mAdapter);
        }
    }.execute((Void[]) params); //error occurred skipped directly to here.

    return arrayList1;
}
</code>```

答:
I guess you are creating two different object's in one reference, try this code:</p>

```<code>private Context mContext;
private ArrayList<List> mData;
private ListView mListView;
private ListViewAdapter mAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mContext = getApplicationContext();
    mListView = (ListView)findViewById(R.id.listView1);
    mData = new ArrayList<List>();
    LoadListView();
}

public void LoadListView(Void...params) {

    //here error occurred.
    new AsyncTask<Void, Void, ArrayList<List>>() {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected ArrayList<List> doInBackground(Void...params) {
            mData.clear();
            mData.addAll(GetData());
            //GetData() is another function will return a arraylist from web service.
            return mData;
        }

        @Override
        protected void onPostExecute(ArrayList<List> arrayList) {
            mAdapter = new ListViewAdapter(arrayList, mContext);
            mAdapter.notifyDataSetChanged();
            mListView.setAdapter(mAdapter);
        }
    }.execute((Void[]) params); //error occurred skipped directly to here.

}
</code>```

Title: android: no such instance field

Body:
I'm trying to get data thru AsyncTask with web service.
I have no idea why as I declared global variable 'arrayList1' and it has been initialized, but I'm getting error for the 'arrayList1' and it skipped doin the new AsyncTask.

private Context mContext;
private ArrayList arrayList1;
private ArrayList<List> mData;
private ListView mListView;
private ListViewAdapter mAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

mContext = getApplicationContext();
mListView = (ListView)findViewById(R.id.listView1);
mData = new ArrayList<List>();
mData = LoadListView();
}

public ArrayList<List> LoadListView(Void...params) {
    arrayList1 = new ArrayList();
    //here error occurred.
    new AsyncTask<Void, Void, ArrayList<List>>() {
        @Override
        protected ArrayList<List> doInBackground(Void...params) {
            arrayList1 = GetData();
            //GetData() is another function will return a arraylist from web service.
            return arrayList1;
        }

        @Override
        protected void onPostExecute(ArrayList<List> arrayList) {
            mAdapter = new ListViewAdapter(arrayList, mContext);
            mAdapter.notifyDataSetChanged();
            mListView.setAdapter(mAdapter);
        }
    }.execute((Void[]) params); //error occurred skipped directly to here.

    return arrayList1;
}

Body:
I guess you are creating two different object's in one reference, try this code:

private Context mContext;
private ArrayList<List> mData;
private ListView mListView;
private ListViewAdapter mAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mContext = getApplicationContext();
    mListView = (ListView)findViewById(R.id.listView1);
    mData = new ArrayList<List>();
    LoadListView();
}

public void LoadListView(Void...params) {

    //here error occurred.
    new AsyncTask<Void, Void, ArrayList<List>>() {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected ArrayList<List> doInBackground(Void...params) {
            mData.clear();
            mData.addAll(GetData());
            //GetData() is another function will return a arraylist from web service.
            return mData;
        }

        @Override
        protected void onPostExecute(ArrayList<List> arrayList) {
            mAdapter = new ListViewAdapter(arrayList, mContext);
            mAdapter.notifyDataSetChanged();
            mListView.setAdapter(mAdapter);
        }
    }.execute((Void[]) params); //error occurred skipped directly to here.

}