问:
How to call SOAP WS from Oracle DB 11.2 with payload more than 32000 chars?
Colleagues, hello. I need to call SOAP web service from Oracle DB where payload consists of file in base64 encoding. The problem is that i have limitation in payload size - 32 000 chars (varchar type). Examples, here and here. So it means that i can not call web service where payload is quite huge. Have anybody examples where payload increases the limitation of varchar2 type. Than you.  </p>

答:
To go over the 32k characters limitation, you can try to use a CLOB with utl_http. Here is a procedure to do it :

```<code>PROCEDURE write_clob_to_http_request(pc_clob IN OUT NOCOPY CLOB)
IS
    ln_offset      NUMBER := 1;
    ln_i           NUMBER := 1;
    ln_amount      NUMBER := 32767;
    ln_clob_length NUMBER := dbms_lob.getlength(pc_clob);
    lv_buffer      VARCHAR2(32767);

    luh_http_request utl_http.req;
BEGIN

    luh_http_request := utl_http.begin_request('http://SoapServiceLocation' , 'POST', 'HTTP/1.1');
    utl_http.set_header(luh_http_request, 'Content-Type', lv_http_content_type);
    utl_http.set_header(luh_http_request, 'Content-Length', LENGTH(pc_content));
    utl_http.set_header(luh_http_request, 'SOAPAction', 'http://SoapServiceLocation');

    IF dbms_lob.isopen(pc_clob) != 1 THEN
        dbms_lob.open(pc_clob, 0);
    END IF;

    WHILE ( ln_offset < ln_clob_length )
    LOOP
        dbms_lob.read(pc_clob, ln_amount, ln_offset, lv_buffer);
        UTL_HTTP.write_text(luh_http_request, lv_buffer);
        ln_offset := ln_offset + ln_amount;
        ln_i := ln_i + 1;
    END LOOP;

    IF dbms_lob.isopen(pc_clob) = 1 THEN
        dbms_lob.close(pc_clob);
    END IF;

    luh_http_response := utl_http.get_response(luh_http_request);
    utl_http.read_text(luh_http_response, pc_content);
    utl_http.end_response(luh_http_response);
END write_clob_to_http_request;
</code>```

You can easily create a CLOB by concatenating VARCHAR2 variables:

```<code>pc_content CLOB := TO_CLOB('a string') || TO_CLOB('another string)...;
</code>```

Body:
To go over the 32k characters limitation, you can try to use a CLOB with utl_http. Here is a procedure to do it :

PROCEDURE write_clob_to_http_request(pc_clob IN OUT NOCOPY CLOB)
IS
    ln_offset      NUMBER := 1;
    ln_i           NUMBER := 1;
    ln_amount      NUMBER := 32767;
    ln_clob_length NUMBER := dbms_lob.getlength(pc_clob);
    lv_buffer      VARCHAR2(32767);

    luh_http_request utl_http.req;
BEGIN

    luh_http_request := utl_http.begin_request('http://SoapServiceLocation' , 'POST', 'HTTP/1.1');
    utl_http.set_header(luh_http_request, 'Content-Type', lv_http_content_type);
    utl_http.set_header(luh_http_request, 'Content-Length', LENGTH(pc_content));
    utl_http.set_header(luh_http_request, 'SOAPAction', 'http://SoapServiceLocation');

    IF dbms_lob.isopen(pc_clob) != 1 THEN
        dbms_lob.open(pc_clob, 0);
    END IF;

    WHILE ( ln_offset < ln_clob_length )
    LOOP
        dbms_lob.read(pc_clob, ln_amount, ln_offset, lv_buffer);
        UTL_HTTP.write_text(luh_http_request, lv_buffer);
        ln_offset := ln_offset + ln_amount;
        ln_i := ln_i + 1;
    END LOOP;

    IF dbms_lob.isopen(pc_clob) = 1 THEN
        dbms_lob.close(pc_clob);
    END IF;

    luh_http_response := utl_http.get_response(luh_http_request);
    utl_http.read_text(luh_http_response, pc_content);
    utl_http.end_response(luh_http_response);
END write_clob_to_http_request;

You can easily create a CLOB by concatenating VARCHAR2 variables:

pc_content CLOB := TO_CLOB('a string') || TO_CLOB('another string)...;


来源: stackexchange

问:
Using array_push() to add elements to an array in the form of 'key => object'
I have a set of objects I want to put into an array and I want to distinguish them with keys.

The initial code I wrote was:

```<code>array_push($array[$key], new myObj(param1, param2, etc));
</code>```

When I run it I get the warning:

```<code>PHP Warning:  array_push() expects parameter 1 to be array, null given in file.php on line 56
</code>```

I added a var_dump() to see what was actually happening and it was filling the array with each element '$key => null'  as suggested by the error.

If I remove the [$key] from the line then it fills the array with instances of myObj as expected so I know that the constructor is functioning correctly and not really returning 'null'.

答:
Try:</p>

```<code>$array[$key] = new myObj(param1, param2, etc);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a set of objects I want to put into an array and I want to distinguish them with keys.

The initial code I wrote was:

array_push($array[$key], new myObj(param1, param2, etc));

When I run it I get the warning:

PHP Warning:  array_push() expects parameter 1 to be array, null given in file.php on line 56

I added a var_dump() to see what was actually happening and it was filling the array with each element '$key => null'  as suggested by the error.

If I remove the [$key] from the line then it fills the array with instances of myObj as expected so I know that the constructor is functioning correctly and not really returning 'null'.

Body:
Try:

$array[$key] = new myObj(param1, param2, etc);


问:
Caching the mean of a Vector in R
I am learning R and came across some code as part of the practice assignment.

```<code> makeVector <- function(x = numeric()) {
         m <- NULL
         set <- function(y) {
                x <<- y
                m <<- NULL
        }
        get <- function() x
        setmean <- function(mean) m <<- mean
        getmean <- function() m
        list(set = set, get = get,
             setmean = setmean,
             getmean = getmean)
 }
</code>```

The documentation says:

The function, makeVector creates a special "vector", which is
really a list containing a function to

set the value of the vector

get the value of the vector

set the value of the mean

get the value of the mean

But i can not understand how the function works except for the point that it is assigning mean value to the variable m in that particular environment.

答:
This answer is an excerpt from an article I originally wrote in 2016 as a Community Mentor in the Johns Hopkins University R Programming course: Demystifying makeVector().

Overall Design of makeVector() and cachemean()

The cachemean.R file contains two functions, makeVector() and cachemean(). The first function in the file, makeVector() creates an R object that stores a vector and its mean. The second function, cachemean() requires an argument that is returned by makeVector() in order to retrieve the mean from the cached value that is stored in the makeVector() object's environment.

What's going on in makeVector()?

The key concept to understand in makeVector() is that it builds a set of functions and returns the functions within a list to the parent environment. That is,

```<code>    myVector <- makeVector(1:15)
</code>```

results in an object, myVector, that contains four functions: set(), get(), setmean(), and getmean().  It also includes the two data objects, x and m.

Due to lexical scoping, myVector contains a complete copy of the environment for makeVector(), including any objects that are defined within makeVector() at design time (i.e., when it was coded). A diagram of the environment hierarchy makes it clear what is accessible within myVector.

Illustrated as a hierarchy, the global environment contains the makeVector() environment. All other content is present in the makeVector() environment, as illustrated below.

Since each function has its own environment in R, the hierarchy illustrates that the objects x and m are siblings of the four functions, get(), set(), getmean(), and setmean().

Once the function is run and an object of type makeVector() is instantiated (that is, created), the environment containing myVector looks like:

Notice that the object x contains the vector 1:15, even though myVector$set() has not been executed. This is the case because the value 1:15 was passed as an argument into the makeVector() function.  What explains this behavior?

When an R function returns an object that contains functions to its parent environment (as is the case with a call like myVector <- makeVector(1:15)), not only does myVector have access to the specific functions in its list, but it also retains access to the entire environment defined by makeVector(), including the original argument used to start the function.

Why is this the case? myVector contains pointers to functions that are within the makeVector() environment after the function ends, so these pointers prevent the memory consumed by makeVector() from being released by the garbage collector. Therefore, the entire makeVector() environment stays in memory, and myVector can access its functions as well as any data in that environment that is referenced in its functions.

This feature explains why x (the argument initialized on the original function call) is accessible by subsequent calls to functions on myVector such as myVector$get(), and it also explains why the code works without having to explicitly issue myVector$set() to set the value of x.

makeVector() step by step

Now, let's break the behavior of the function down, step by step.

Step 1: Initialize objects

The first thing that occurs in the function is the initialization of two objects, x and m.

```<code>makeVector(x = numeric()) {
  m <- NULL
  ...
}
</code>```

Notice that x is initialized as a function argument, so no further initialization is required within the function. m is set to NULL, initializing it as an object within the makeVector() environment to be used by later code in the function.

Furthermore, the formals part of the function declaration define the default value of x as an empty numeric vector. Initialization of the vector with a default value is important because without a default value, data <- x$get() generates the following error message.

```<code> Error in x$get() : argument "x" is missing, with no default
</code>```

Step 2: Define the "behaviors" or functions for objects of type makeVector()

After initializing key objects that store key information within makeVector(), the code provides four basic behaviors that are typical for data elements within an object-oriented program. They're called "getters and settters," and more formally known as mutator and accessor methods.  As one might expect, "getters" are program modules that retrieve (access) data within an object, and "setters" are program modules that set (mutate) the data values within an object.

First makeVector() defines the set() function. Most of the "magic" in makeVector() takes place in the set() function.

```<code>set <- function(y) {
    x <<- y
    m <<- NULL
}
</code>```

set() takes an argument that is named as y. It is assumed that this value is a numeric vector, but is not stated directly in the function formals. For the purposes of the set() function, it doesn't matter whether this argument is called y, aVector or any object name other than x. Why? Since there is an x object already defined in the makeVector() environment, using the same object name would make the code more difficult to understand.

Within set() we use the <<- form of the assignment operator, which assigns the value on the right side of the operator to an object in the parent environment named by the object on the left side of the operator.

When set() is executed, it does two things:

Assign the input argument to the x object in the parent environment, and

Assign the value of NULL to the m object in the parent environment. This line of code clears any value of m that had been cached by a prior execution of cachemean().

Therefore, if there is already a valid mean cached in m, whenever x is reset, the value of m cached in the memory of the object is cleared, forcing subsequent calls to cachemean() to recalculate the mean rather than retrieving the wrong value from cache.

Notice that the two lines of code in set() do exactly the same thing as the first two lines in the main function: set the value of x, and NULL the value of m.

Second, makeVector() defines the getter for the vector x.

```<code>get <- function() x
</code>```

Again, this function takes advantage of the lexical scoping features in R. Since the symbol x is not defined within get(), R retrieves it from the parent environment of makeVector().

Third, makeVector() defines the setter for the mean m.

```<code>setmean <- function(mean) m <<- mean
</code>```

Since m is defined in the parent environment and we need to access it after setmean() completes, the code uses the <<- form of the assignment operator to assign the input argument to the value of m in the parent environment.

Finally, makeVector() defines the getter for the mean m. Just like the getter for x, R takes advantage of lexical scoping to find the correct symbol m to retrieve its value.

```<code>getmean <- function() m
</code>```

At this point we have getters and setters defined for both of the data objects within our makeVector() object.

Step 3: Create a new object by returning a list()

Here is the other part of the "magic" in the operations of the makeVector() function. The last section of code assigns each of these functions as an element within a list(), and returns it to the parent environment.

```<code>list(set = set, get = get,
     setmean = setmean,
     getmean = getmean)
</code>```

When the function ends, it returns a fully formed object of type makeVector() to be used by downstream R code. One other important subtlety about this code is that each element in the list is named. That is, each element in the list is created with a elementName = value syntax, as follows:

```<code>    list(set = set,          # gives the name 'set' to the set() function defined above
         get = get,          # gives the name 'get' to the get() function defined above
         setmean = setmean,  # gives the name 'setmean' to the setmean() function defined above
         getmean = getmean)  # gives the name 'getmean' to the getmean() function defined above
</code>```

Naming the list elements is what allows us to use the $ form of the extract operator to access the functions by name rather than using the [[ form of the extract operator, as in myVector[[2]](), to get the contents of the vector.

Here it's important to note that the cachemean() function REQUIRES an input argument of type makeVector(). If one passes a regular vector to the function, as in

```<code> aResult <- cachemean(1:15)
</code>```

the function call will fail with an error explaining that cachemean() was unable to access $getmean() on the input argument because $ does not work with atomic vectors. This is accurate, because a primitive vector is not a list, nor does it contain a $getmean() function, as illustrated below.

```<code>makeVector(x = numeric()) {
  m <- NULL
  ...
}
</code>```0

Explaining cachemean()

Without cachemean(), the makeVector() function is incomplete. Why? As designed, cachemean() is required to populate or retrieve the mean from an object of type makeVector().

```<code>makeVector(x = numeric()) {
  m <- NULL
  ...
}
</code>```1

Like makeVector(), cachemean() starts with a single argument, x, and an ellipsis that allows the caller to pass additional arguments into the function.

Next, the function attempts to retrieve a mean from the object passed in as the argument. First, it calls the getmean() function on the input object.

```<code>makeVector(x = numeric()) {
  m <- NULL
  ...
}
</code>```2

Then it checks to see whether the result is NULL. Since makeVector() sets the cached mean to NULL whenever a new vector is set into the object, if the value here is not equal to NULL, we have a valid, cached mean and can return it to the parent environment

```<code>     if(!is.null(m)) {
          message("getting cached data")
          return(m)
     }
</code>```

If the result of !is.null(m) is FALSE, cachemean() gets the vector from the input object, calculates a mean(), uses the setmean() function on the input object to set the mean in the input object, and then returns the value of the mean to the parent environment by printing the mean object.

```<code>     data <- x$get()
     m <- mean(data, ...)
     x$setmean(m)
     m
</code>```

Note that cachemean() is the only place where the mean() function is executed, which is why makeVector() is incomplete without cachemean().

Putting the Pieces Together: How the functions work at runtime

Now that we've explained the design of each of these functions, here is an illustration of how they work when used in an R script.

```<code>  aVector <- makeVector(1:10)
  aVector$get()               # retrieve the value of x
  aVector$getmean()           # retrieve the value of m, which should be NULL
  aVector$set(30:50)          # reset value with a new vector
  cachemean(aVector)          # notice mean calculated is mean of 30:50, not 1:10
  aVector$getmean()           # retrieve it directly, now that it has been cached
</code>```

Conclusion: what makes cachemean() work?

To summarize, the lexical scoping assignment in R Programming takes advantage of lexical scoping and the fact that functions that return objects of type list() also allow access to any other objects defined in the environment of the original function. In the specific instance of makeVector() this means that subsequent code can access the values of x or m through the use of getters and setters. This is how cachemean() is able to calculate and store the mean for the input argument if it is of type makeVector(). Because list elements in makeVector() are defined with names, we can access these functions with the $ form of the extract operator.

For additional commentary that explains how the assignment uses features of the S3 object system, please review makeCacheMatrix() as an Object.

Appendix A: What's the Point of this Assignment?

Once students get through the assignment, they frequently ask questions about its value and purpose. A good article explaining the value of lexical scoping in statistical computing is Lexical Scoping and Statistical Computing, written by Robert Gentleman and Ross Ihaka at the University of Auckland.

Appendix B: cachemean.R

Here is the entire listing for cachemean.R.

```<code>makeVector <- function(x = numeric()) {
     m <- NULL
     set <- function(y) {
          x <<- y
          m <<- NULL
     }
     get <- function() x
     setmean <- function(mean) m <<- mean
     getmean <- function() m
     list(set = set, get = get,
          setmean = setmean,
          getmean = getmean)
}
cachemean <- function(x, ...) {
     m <- x$getmean()
     if(!is.null(m)) {
          message("getting cached data")
          return(m)
     }
     data <- x$get()
     m <- mean(data, ...)
     x$setmean(m)
     m
}
</code>```

Appendix C: Frequently Asked Questions

Q: Why doesn't cachemean() return the cached value? My code looks like:

```<code> cachemean(makeVector(1:100))
 cachemean(makeVector(1:100))
</code>```

A: Code written this way creates two different objects of type makeVector(), so the two calls to cachemean() initialize the means of each instance, rather than caching and retrieving from a single instance. Another way of illustrating how the above code operates is as follows.

Notice how the first call to cachemean() sets the cache, and the second call retrieves data from it.

Q: Why is set() never used in the code?

A: set() is included so that once an object of type makeVector() is created, its value can be changed without initializing another instance of the object. It is unnecessary the first time an object of type makeVector() is instantiated. Why? First, the value of x is set as a function argument, as in makeVector(1:30). Then, the first line of code in the function sets m <- NULL, simultaneously allocating memory for m and setting it to NULL. When a reference to this object is passed to the parent environment when the function ends, both x and m are available to be accessed by their respective get and set functions.

The following code illustrates the use of set().

Q: Why is x set with a default value in makeVector()?

A: Since x is an argument, the only place where one can set a default for it is in the formals. The type of error returned by cachemean() when a default value is not set,

```<code>  Error in x$get() : argument "x" is missing, with no default
</code>```

is undesirable. Our code should directly handle error conditions rather than relying on the underlying error handling in R.

It's perfectly valid to create an object of type makeVector() without populating its value during initialization. makeVector() includes a setter function so one can set its value after the object is created. However, the object must have valid data, a numeric vector, prior to executing cachemean().

Ideally, cachemean() would include logic to validate that x is not empty prior to calculating a mean. The default setting of x enables cachemean() to return NaN, which is a reasonable result.

References

Chi, Yau -- R-Tutor Named List Members, retrieved July 20, 2016.

Wickham, Hadley -- Advanced-R Functions, retrieved July 17, 2016.

Wickham, Hadley -- Advanced-R Scoping Issues, retrieved July 17, 2016.

ContentLicense: CC BY-SA 3.0

Title: Caching the mean of a Vector in R

Body:
I am learning R and came across some code as part of the practice assignment.

 makeVector <- function(x = numeric()) {
         m <- NULL
         set <- function(y) {
                x <<- y
                m <<- NULL
        }
        get <- function() x
        setmean <- function(mean) m <<- mean
        getmean <- function() m
        list(set = set, get = get,
             setmean = setmean,
             getmean = getmean)
 }

The documentation says:

The function, makeVector creates a special "vector", which is
really a list containing a function to

set the value of the vector

get the value of the vector

set the value of the mean

get the value of the mean

But i can not understand how the function works except for the point that it is assigning mean value to the variable m in that particular environment.

Body:
This answer is an excerpt from an article I originally wrote in 2016 as a Community Mentor in the Johns Hopkins University R Programming course: Demystifying makeVector().

Overall Design of makeVector() and cachemean()

The cachemean.R file contains two functions, makeVector() and cachemean(). The first function in the file, makeVector() creates an R object that stores a vector and its mean. The second function, cachemean() requires an argument that is returned by makeVector() in order to retrieve the mean from the cached value that is stored in the makeVector() object's environment.

What's going on in makeVector()?

The key concept to understand in makeVector() is that it builds a set of functions and returns the functions within a list to the parent environment. That is,

    myVector <- makeVector(1:15)

results in an object, myVector, that contains four functions: set(), get(), setmean(), and getmean().  It also includes the two data objects, x and m.

Due to lexical scoping, myVector contains a complete copy of the environment for makeVector(), including any objects that are defined within makeVector() at design time (i.e., when it was coded). A diagram of the environment hierarchy makes it clear what is accessible within myVector.

Illustrated as a hierarchy, the global environment contains the makeVector() environment. All other content is present in the makeVector() environment, as illustrated below.

Since each function has its own environment in R, the hierarchy illustrates that the objects x and m are siblings of the four functions, get(), set(), getmean(), and setmean().

Once the function is run and an object of type makeVector() is instantiated (that is, created), the environment containing myVector looks like:

Notice that the object x contains the vector 1:15, even though myVector$set() has not been executed. This is the case because the value 1:15 was passed as an argument into the makeVector() function.  What explains this behavior?

When an R function returns an object that contains functions to its parent environment (as is the case with a call like myVector <- makeVector(1:15)), not only does myVector have access to the specific functions in its list, but it also retains access to the entire environment defined by makeVector(), including the original argument used to start the function.

Why is this the case? myVector contains pointers to functions that are within the makeVector() environment after the function ends, so these pointers prevent the memory consumed by makeVector() from being released by the garbage collector. Therefore, the entire makeVector() environment stays in memory, and myVector can access its functions as well as any data in that environment that is referenced in its functions.

This feature explains why x (the argument initialized on the original function call) is accessible by subsequent calls to functions on myVector such as myVector$get(), and it also explains why the code works without having to explicitly issue myVector$set() to set the value of x.

makeVector() step by step

Now, let's break the behavior of the function down, step by step.

Step 1: Initialize objects

The first thing that occurs in the function is the initialization of two objects, x and m.

makeVector(x = numeric()) {
  m <- NULL
  ...
}

Notice that x is initialized as a function argument, so no further initialization is required within the function. m is set to NULL, initializing it as an object within the makeVector() environment to be used by later code in the function.

Furthermore, the formals part of the function declaration define the default value of x as an empty numeric vector. Initialization of the vector with a default value is important because without a default value, data <- x$get() generates the following error message.

 Error in x$get() : argument "x" is missing, with no default

Step 2: Define the "behaviors" or functions for objects of type makeVector()

After initializing key objects that store key information within makeVector(), the code provides four basic behaviors that are typical for data elements within an object-oriented program. They're called "getters and settters," and more formally known as mutator and accessor methods.  As one might expect, "getters" are program modules that retrieve (access) data within an object, and "setters" are program modules that set (mutate) the data values within an object.

First makeVector() defines the set() function. Most of the "magic" in makeVector() takes place in the set() function.

set <- function(y) {
    x <<- y
    m <<- NULL
}

set() takes an argument that is named as y. It is assumed that this value is a numeric vector, but is not stated directly in the function formals. For the purposes of the set() function, it doesn't matter whether this argument is called y, aVector or any object name other than x. Why? Since there is an x object already defined in the makeVector() environment, using the same object name would make the code more difficult to understand.

Within set() we use the <<- form of the assignment operator, which assigns the value on the right side of the operator to an object in the parent environment named by the object on the left side of the operator.

When set() is executed, it does two things:

Assign the input argument to the x object in the parent environment, and

Assign the value of NULL to the m object in the parent environment. This line of code clears any value of m that had been cached by a prior execution of cachemean().

Therefore, if there is already a valid mean cached in m, whenever x is reset, the value of m cached in the memory of the object is cleared, forcing subsequent calls to cachemean() to recalculate the mean rather than retrieving the wrong value from cache.

Notice that the two lines of code in set() do exactly the same thing as the first two lines in the main function: set the value of x, and NULL the value of m.

Second, makeVector() defines the getter for the vector x.

get <- function() x

Again, this function takes advantage of the lexical scoping features in R. Since the symbol x is not defined within get(), R retrieves it from the parent environment of makeVector().

Third, makeVector() defines the setter for the mean m.

setmean <- function(mean) m <<- mean

Since m is defined in the parent environment and we need to access it after setmean() completes, the code uses the <<- form of the assignment operator to assign the input argument to the value of m in the parent environment.

Finally, makeVector() defines the getter for the mean m. Just like the getter for x, R takes advantage of lexical scoping to find the correct symbol m to retrieve its value.

getmean <- function() m

At this point we have getters and setters defined for both of the data objects within our makeVector() object.

Step 3: Create a new object by returning a list()

Here is the other part of the "magic" in the operations of the makeVector() function. The last section of code assigns each of these functions as an element within a list(), and returns it to the parent environment.

list(set = set, get = get,
     setmean = setmean,
     getmean = getmean)

When the function ends, it returns a fully formed object of type makeVector() to be used by downstream R code. One other important subtlety about this code is that each element in the list is named. That is, each element in the list is created with a elementName = value syntax, as follows:

    list(set = set,          # gives the name 'set' to the set() function defined above
         get = get,          # gives the name 'get' to the get() function defined above
         setmean = setmean,  # gives the name 'setmean' to the setmean() function defined above
         getmean = getmean)  # gives the name 'getmean' to the getmean() function defined above

Naming the list elements is what allows us to use the $ form of the extract operator to access the functions by name rather than using the [[ form of the extract operator, as in myVector[[2]](), to get the contents of the vector.

Here it's important to note that the cachemean() function REQUIRES an input argument of type makeVector(). If one passes a regular vector to the function, as in

 aResult <- cachemean(1:15)

the function call will fail with an error explaining that cachemean() was unable to access $getmean() on the input argument because $ does not work with atomic vectors. This is accurate, because a primitive vector is not a list, nor does it contain a $getmean() function, as illustrated below.

> aVector <- 1:10
> cachemean(aVector)
Error in x$getmean : $ operator is invalid for atomic vectors

Explaining cachemean()

Without cachemean(), the makeVector() function is incomplete. Why? As designed, cachemean() is required to populate or retrieve the mean from an object of type makeVector().

cachemean <- function(x, ...) {
     ...

Like makeVector(), cachemean() starts with a single argument, x, and an ellipsis that allows the caller to pass additional arguments into the function.

Next, the function attempts to retrieve a mean from the object passed in as the argument. First, it calls the getmean() function on the input object.

     m <- x$getmean()

Then it checks to see whether the result is NULL. Since makeVector() sets the cached mean to NULL whenever a new vector is set into the object, if the value here is not equal to NULL, we have a valid, cached mean and can return it to the parent environment

     if(!is.null(m)) {
          message("getting cached data")
          return(m)
     }

If the result of !is.null(m) is FALSE, cachemean() gets the vector from the input object, calculates a mean(), uses the setmean() function on the input object to set the mean in the input object, and then returns the value of the mean to the parent environment by printing the mean object.

     data <- x$get()
     m <- mean(data, ...)
     x$setmean(m)
     m

Note that cachemean() is the only place where the mean() function is executed, which is why makeVector() is incomplete without cachemean().

Putting the Pieces Together: How the functions work at runtime

Now that we've explained the design of each of these functions, here is an illustration of how they work when used in an R script.

  aVector <- makeVector(1:10)
  aVector$get()               # retrieve the value of x
  aVector$getmean()           # retrieve the value of m, which should be NULL
  aVector$set(30:50)          # reset value with a new vector
  cachemean(aVector)          # notice mean calculated is mean of 30:50, not 1:10
  aVector$getmean()           # retrieve it directly, now that it has been cached

Conclusion: what makes cachemean() work?

To summarize, the lexical scoping assignment in R Programming takes advantage of lexical scoping and the fact that functions that return objects of type list() also allow access to any other objects defined in the environment of the original function. In the specific instance of makeVector() this means that subsequent code can access the values of x or m through the use of getters and setters. This is how cachemean() is able to calculate and store the mean for the input argument if it is of type makeVector(). Because list elements in makeVector() are defined with names, we can access these functions with the $ form of the extract operator.

For additional commentary that explains how the assignment uses features of the S3 object system, please review makeCacheMatrix() as an Object.

Appendix A: What's the Point of this Assignment?

Once students get through the assignment, they frequently ask questions about its value and purpose. A good article explaining the value of lexical scoping in statistical computing is Lexical Scoping and Statistical Computing, written by Robert Gentleman and Ross Ihaka at the University of Auckland.

Appendix B: cachemean.R

Here is the entire listing for cachemean.R.

makeVector <- function(x = numeric()) {
     m <- NULL
     set <- function(y) {
          x <<- y
          m <<- NULL
     }
     get <- function() x
     setmean <- function(mean) m <<- mean
     getmean <- function() m
     list(set = set, get = get,
          setmean = setmean,
          getmean = getmean)
}
cachemean <- function(x, ...) {
     m <- x$getmean()
     if(!is.null(m)) {
          message("getting cached data")
          return(m)
     }
     data <- x$get()
     m <- mean(data, ...)
     x$setmean(m)
     m
}

Appendix C: Frequently Asked Questions

Q: Why doesn't cachemean() return the cached value? My code looks like:

 cachemean(makeVector(1:100))
 cachemean(makeVector(1:100))

A: Code written this way creates two different objects of type makeVector(), so the two calls to cachemean() initialize the means of each instance, rather than caching and retrieving from a single instance. Another way of illustrating how the above code operates is as follows.

Notice how the first call to cachemean() sets the cache, and the second call retrieves data from it.

Q: Why is set() never used in the code?

A: set() is included so that once an object of type makeVector() is created, its value can be changed without initializing another instance of the object. It is unnecessary the first time an object of type makeVector() is instantiated. Why? First, the value of x is set as a function argument, as in makeVector(1:30). Then, the first line of code in the function sets m <- NULL, simultaneously allocating memory for m and setting it to NULL. When a reference to this object is passed to the parent environment when the function ends, both x and m are available to be accessed by their respective get and set functions.

The following code illustrates the use of set().

Q: Why is x set with a default value in makeVector()?

A: Since x is an argument, the only place where one can set a default for it is in the formals. The type of error returned by cachemean() when a default value is not set,

  Error in x$get() : argument "x" is missing, with no default

is undesirable. Our code should directly handle error conditions rather than relying on the underlying error handling in R.

It's perfectly valid to create an object of type makeVector() without populating its value during initialization. makeVector() includes a setter function so one can set its value after the object is created. However, the object must have valid data, a numeric vector, prior to executing cachemean().

Ideally, cachemean() would include logic to validate that x is not empty prior to calculating a mean. The default setting of x enables cachemean() to return NaN, which is a reasonable result.

References

Chi, Yau -- R-Tutor Named List Members, retrieved July 20, 2016.

Wickham, Hadley -- Advanced-R Functions, retrieved July 17, 2016.

Wickham, Hadley -- Advanced-R Scoping Issues, retrieved July 17, 2016.


问:
TypeError: this.sendHandshake is not a function
Im trying to create a simple class (wrapper) for a nodejs & socket.io game.

```<code>module.exports = class client {
constructor(socket) {
    this.socket = socket;
    this.createEvents();
}

createEvents() {
    console.log('creating events');
    this.socket.on('handshake', this.onHandshake);
    this.socket.on('disconnect', this.onDisconnect);
}

sendHandshake() { // <------------ sendHandshake is there?
    console.log('sending handshake');
    this.socket.emit('handshake');
}

onHandshake() {
    console.log('handshake received');
    this.sendHandshake(); // <----- TypeError: this.sendHandshake is not a function
}

onDisconnect() {
    console.log('client disconnected');
}
}
</code>```

it should give me this output

```<code>creating events
handshake received
sending handshake
</code>```

but instead it gives me this error

```<code>creating events
handshake received
TypeError: this.sendHandshake is not a function
</code>```

答:
When you pass a function it is not automatically bound to the object that owns the function. A simpler example would be:

```<code>const EventEmitter = require('events');
class client {
    constructor() {
        this.ev = new EventEmitter;
        this.ev.on('handshake', this.onHandshake);
        this.ev.emit('handshake');
    }

    onHandshake() {
        console.log(this); // EventEmitter
    }
}
</code>```

Instead you must bind the function to client which you can do pretty easily just by using this.onHandshake.bind(this) or () => this.onHandshake(). The former binds this explicitly. The latter binds this lexically, i.e. whatever this is in the function where it's defined.

I'll also point out that you respond to handshake by emitting handshake -- not sure if that's intended or needed.

Body:
Im trying to create a simple class (wrapper) for a nodejs & socket.io game.

module.exports = class client {
constructor(socket) {
    this.socket = socket;
    this.createEvents();
}

createEvents() {
    console.log('creating events');
    this.socket.on('handshake', this.onHandshake);
    this.socket.on('disconnect', this.onDisconnect);
}

sendHandshake() { // <------------ sendHandshake is there?
    console.log('sending handshake');
    this.socket.emit('handshake');
}

onHandshake() {
    console.log('handshake received');
    this.sendHandshake(); // <----- TypeError: this.sendHandshake is not a function
}

onDisconnect() {
    console.log('client disconnected');
}
}

it should give me this output

creating events
handshake received
sending handshake

but instead it gives me this error

creating events
handshake received
TypeError: this.sendHandshake is not a function

Body:
When you pass a function it is not automatically bound to the object that owns the function. A simpler example would be:

const EventEmitter = require('events');
class client {
    constructor() {
        this.ev = new EventEmitter;
        this.ev.on('handshake', this.onHandshake);
        this.ev.emit('handshake');
    }

    onHandshake() {
        console.log(this); // EventEmitter
    }
}

Instead you must bind the function to client which you can do pretty easily just by using this.onHandshake.bind(this) or () => this.onHandshake(). The former binds this explicitly. The latter binds this lexically, i.e. whatever this is in the function where it's defined.

I'll also point out that you respond to handshake by emitting handshake -- not sure if that's intended or needed.


问:
Privileged scopes are not accessible from my own account
First of all everything worked three days ago. But today I found that each call to https://api.uber.com/v1.2/requests/current gives me {"message":"This endpoint requires at least one of the following scopes: all_trips_lite, request, all_trips","code":"unauthorized"}

I'm testing with my PERSONAL ACCESS TOKEN and also I have checked ALL scopes from the list (check this screen)

I'm using this code:

```<code>$api_url = "https://api.uber.com/v1.2/requests/current";

//Manually generated in Dashboard
$access_token = ".........................";

$header[0] = "Accept-Language: en_US";
$header[] = "Content-Type: application/json";
$header[]  = "Authorization: Bearer {$access_token}";

$ch = curl_init();

curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 120 );
curl_setopt( $ch, CURLOPT_TIMEOUT, 140 );

curl_setopt( $ch, CURLOPT_URL, $api_url );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $header);

curl_setopt( $ch, CURLOPT_VERBOSE, true );
$strData = curl_exec($ch);
</code>```

How I can test Requests endpoint with my own generated access token?

答:
Investigated the issue and this is indeed a bug, but only with the "TEST WITH A PERSONAL ACCESS TOKEN" tool on the Uber API developer dashboard (see screenshot):

A bug has been filed to fix this issue, but the workaround in the meantime is to auth your Uber developer account using the steps outlined in the guide here (instead of the easier dashboard tool):
https://developer.uber.com/docs/riders/guides/authentication/user-access-token

I will follow up and edit this answer when the dashboard access token tool bug is fixed, hopefully sometime next week. Thanks!

Body:
First of all everything worked three days ago. But today I found that each call to https://api.uber.com/v1.2/requests/current gives me {"message":"This endpoint requires at least one of the following scopes: all_trips_lite, request, all_trips","code":"unauthorized"}

I'm testing with my PERSONAL ACCESS TOKEN and also I have checked ALL scopes from the list (check this screen)

I'm using this code:

$api_url = "https://api.uber.com/v1.2/requests/current";

//Manually generated in Dashboard
$access_token = ".........................";

$header[0] = "Accept-Language: en_US";
$header[] = "Content-Type: application/json";
$header[]  = "Authorization: Bearer {$access_token}";

$ch = curl_init();

curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 120 );
curl_setopt( $ch, CURLOPT_TIMEOUT, 140 );

curl_setopt( $ch, CURLOPT_URL, $api_url );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $header);

curl_setopt( $ch, CURLOPT_VERBOSE, true );
$strData = curl_exec($ch);

How I can test Requests endpoint with my own generated access token?


问:
git branch: gh-pages
I have a repo on GitHub. Recently I have discovered GitHub's pages and I want to use them.

I would like to create this new branch and then, when I need to, either commit on master branch or on gh-pages branch.

How can I do this? Do I have to create another folder inside my repo?

答:
More recent versions of git have an alternative to the git symbolic-ref method that Chandru explained. This avoids having to use the lower level commands.

```<code>git checkout --orphan gh-pages
git rm -rf .
</code>```

Title: git branch: gh-pages

Body:
More recent versions of git have an alternative to the git symbolic-ref method that Chandru explained. This avoids having to use the lower level commands.

git checkout --orphan gh-pages
git rm -rf .


问:
Umbraco 7 Upload File - Check if remove file is ticked
I have an Upload file option in Umbraco 7, the problem I have is if the remove checkbox is ticked and you click publish to remove the file, my code below catches the upload field as empty and display my custom error message.

```<code>if (string.IsNullOrEmpty(urlForFileUpload))
                {
                    e.CancelOperation(new EventMessage("Error", "Please select an Excel file before publishing",EventMessageType.Error));
                }
</code>```

Does anyone know what gets passed to the server so that I can check for it and not display my error message if the checkbox is ticked?

--------------------CancelOperation---------------

答: You don't need an event handler to check that. Just make the field mandatory:

Body:
I have an Upload file option in Umbraco 7, the problem I have is if the remove checkbox is ticked and you click publish to remove the file, my code below catches the upload field as empty and display my custom error message.

if (string.IsNullOrEmpty(urlForFileUpload))
                {
                    e.CancelOperation(new EventMessage("Error", "Please select an Excel file before publishing",EventMessageType.Error));
                }

Does anyone know what gets passed to the server so that I can check for it and not display my error message if the checkbox is ticked?

--------------------CancelOperation---------------


问:
How to access struct field value in a map of that struct with a specific key
I have "FormError" struct. I pass this struct to my template. So how to access InputError struct field value with specific key in the template?

```<code>type InputError struct {
    Val string
    Has bool
}

type FormError struct {
    Errs map[string]InputError
}
</code>```

This doesn't work.

```<code><input name="Name" type="text" value="{{index .Errs.Val `Name`}}">
</code>```

答:
Errs.Val isn't valid, you need to separate the lookup and field access:

```<code>{{ $myval := index .Errs "key" }} {{ $myval.Val }}
</code>```

Or if you only need to use the value once:

```<code>{{ (index .Errs "key").Val }}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have "FormError" struct. I pass this struct to my template. So how to access InputError struct field value with specific key in the template?

type InputError struct {
    Val string
    Has bool
}

type FormError struct {
    Errs map[string]InputError
}

This doesn't work.

<input name="Name" type="text" value="{{index .Errs.Val `Name`}}">

Body:
Errs.Val isn't valid, you need to separate the lookup and field access:

{{ $myval := index .Errs "key" }} {{ $myval.Val }}

Or if you only need to use the value once:

{{ (index .Errs "key").Val }}


答:
Use {{.Errs.Name.Val}}.  There's no need to use index.

playground example

Title: How to access struct field value in a map of that struct with a specific key


问:
Convert unicode codepoint to UTF8 hex in python
I want to convert a number of unicode codepoints read from a file to their UTF8 encoding.

e.g I want to convert the string 'FD9B' to the string 'EFB69B'.

I can do this manually using string literals like this:

```<code>u'\uFD9B'.encode('utf-8')
</code>```

but I cannot work out how to do it programatically.

答:
Because you might encounter an error while using unichr with wide unicode characters:

```<code>>>> n = int('0001f600', 16)
>>> unichr(n)
ValueError: unichr() arg not in range(0x10000) (narrow Python build)
</code>```

Here is another approach for wide unicode on narrow python builds:

```<code>>>> n = int('0001f600', 16)
>>> s = '\\U{:0>8X}'.format(n)
>>> s = s.decode('unicode-escape')
>>> s.encode("utf-8")
'\xf0\x9f\x98\x80'
</code>```

And using the original question's value:

```<code>>>> n = int('FD9B', 16)
>>> s = '\\u{:0>4X}'.format(n)
>>> s = s.decode('unicode-escape')
>>> s.encode("utf-8")
'\xef\xb6\x9b'
</code>```

Body:
I want to convert a number of unicode codepoints read from a file to their UTF8 encoding.

e.g I want to convert the string 'FD9B' to the string 'EFB69B'.

I can do this manually using string literals like this:

u'\uFD9B'.encode('utf-8')

but I cannot work out how to do it programatically.

Body:
Because you might encounter an error while using unichr with wide unicode characters:

>>> n = int('0001f600', 16)
>>> unichr(n)
ValueError: unichr() arg not in range(0x10000) (narrow Python build)

Here is another approach for wide unicode on narrow python builds:

>>> n = int('0001f600', 16)
>>> s = '\\U{:0>8X}'.format(n)
>>> s = s.decode('unicode-escape')
>>> s.encode("utf-8")
'\xf0\x9f\x98\x80'

And using the original question's value:

>>> n = int('FD9B', 16)
>>> s = '\\u{:0>4X}'.format(n)
>>> s = s.decode('unicode-escape')
>>> s.encode("utf-8")
'\xef\xb6\x9b'


问:
pass multiple variables to module
I can't seem to get to figure out how to pass hashrefs to a module correctly.

```<code>#module helper.pm

my %helpers;

sub import {
    shift @_; #returns "helper"
    %SOME_CONFIG = %{shift @_};
    foreach my $hashref (%{@_}){
        $helpers{$hashref->{key}} = $hashref->{value};
    }
}

#main

use helper(
    \%SOME_CONFIG,
    "first_helper" => (
        sub {
            return do_something();
        },
        sub {
            return do_something_else();
        }
    ),
    "second_helper" => (
        sub {
            return something_else();
        }
    )
);
</code>```

I'm not sure how to convert the array to a hash correctly. I thought it work because the anonymous function are passed as references. However it still indexes over @_ as if it is an array and the keys become the indexes of @_.

答:
If your module is not a pragma, i.e. it doesn't change how the code is parsed, use a capitalized name.

Values of hashes mush be scalars, so if you want to assign several subroutines to a key, you must use an array reference.

```<code>#! /usr/bin/perl
use warnings;
use strict;

{
    package Helper;
    my %helpers;

    sub import {
        my $class = shift;
        my %SOME_CONFIG = %{ shift; };
        for my $hashref (@_){
            @helpers{keys %$hashref} = values %$hashref;
        }
        use Data::Dumper;
        $Data::Dumper::Deparse = 1;  # To show the code, as well.
        warn Dumper \%SOME_CONFIG, \%helpers;
    }
}

my %SOME_CONFIG = ( field => 'and its value' );

sub do_something {
    warn "Doing something";
}

sub do_something_else {
    warn "Doing something else";
}

Helper->import(
    \%SOME_CONFIG,
    { first_helpers => [
        \&do_something,
        \&do_something_else,
    ] },
    { second_helpers => [
        sub {
            warn "Inside the 2nd helper";
        },
    ] },
);
</code>```

If you put Helper into a file of its own, Helper.pm, you can then just

```<code>use Helper (
    \%SOME_CONFIG,
    ....
</code>```

BUT, use clauses are processed at compile time, when %SOME_CONFIG still hasn't been populated, so you need to define it in a BEGIN block. You still need to declare it outside the block, though, to make it accessible in the use clause:

```<code>my %SOME_CONFIG;
BEGIN {
    %SOME_CONFIG = ( field => 'and its value' );
}
</code>```

Simplified as ikegami suggested:

In Helper.pm, just do

```<code>%helpers = @_;
</code>```

instead of the for my $hashref. In the main program, use

```<code>use Helper(
    \%SOME_CONFIG,
    first_helpers => [
        \&do_something,
        \&do_something_else,
    ],
    second_helpers => [
        sub {
            warn "Inside the 2nd helper";
        },
    ],
);
</code>```

Title: pass multiple variables to module

Body:
I can't seem to get to figure out how to pass hashrefs to a module correctly.

#module helper.pm

my %helpers;

sub import {
    shift @_; #returns "helper"
    %SOME_CONFIG = %{shift @_};
    foreach my $hashref (%{@_}){
        $helpers{$hashref->{key}} = $hashref->{value};
    }
}

#main

use helper(
    \%SOME_CONFIG,
    "first_helper" => (
        sub {
            return do_something();
        },
        sub {
            return do_something_else();
        }
    ),
    "second_helper" => (
        sub {
            return something_else();
        }
    )
);

I'm not sure how to convert the array to a hash correctly. I thought it work because the anonymous function are passed as references. However it still indexes over @_ as if it is an array and the keys become the indexes of @_.

Body:
If your module is not a pragma, i.e. it doesn't change how the code is parsed, use a capitalized name.

Values of hashes mush be scalars, so if you want to assign several subroutines to a key, you must use an array reference.

#! /usr/bin/perl
use warnings;
use strict;

{
    package Helper;
    my %helpers;

    sub import {
        my $class = shift;
        my %SOME_CONFIG = %{ shift; };
        for my $hashref (@_){
            @helpers{keys %$hashref} = values %$hashref;
        }
        use Data::Dumper;
        $Data::Dumper::Deparse = 1;  # To show the code, as well.
        warn Dumper \%SOME_CONFIG, \%helpers;
    }
}

my %SOME_CONFIG = ( field => 'and its value' );

sub do_something {
    warn "Doing something";
}

sub do_something_else {
    warn "Doing something else";
}

Helper->import(
    \%SOME_CONFIG,
    { first_helpers => [
        \&do_something,
        \&do_something_else,
    ] },
    { second_helpers => [
        sub {
            warn "Inside the 2nd helper";
        },
    ] },
);

If you put Helper into a file of its own, Helper.pm, you can then just

use Helper (
    \%SOME_CONFIG,
    ....

BUT, use clauses are processed at compile time, when %SOME_CONFIG still hasn't been populated, so you need to define it in a BEGIN block. You still need to declare it outside the block, though, to make it accessible in the use clause:

my %SOME_CONFIG;
BEGIN {
    %SOME_CONFIG = ( field => 'and its value' );
}

Simplified as ikegami suggested:

In Helper.pm, just do

%helpers = @_;

instead of the for my $hashref. In the main program, use

use Helper(
    \%SOME_CONFIG,
    first_helpers => [
        \&do_something,
        \&do_something_else,
    ],
    second_helpers => [
        sub {
            warn "Inside the 2nd helper";
        },
    ],
);


问:
Click All Javascript Jquery
When I run:

javascript:

```<code>var inputs = document.getElementsByClassName('subscribe_follow');

for(var i=0;i<inputs.length;i++) {
   inputs[i].click();
}
</code>```

to click all buttons with the class class="subscribe_follow",
it also clicks all buttons with the class class="subscribe_follow ng-hide".

How do I only click the exact class?

答:
You can use the not operator.

```<code>document.querySelectorAll('.subscribe_follow:not(.ng-hide)');
</code>```

.subscribe_follow:not(.ng-hide) selector selects all the elements with the class subscribe_fellow but which do not have the ng-hide class.

jQuery

```<code>$('.subscribe_follow:not(.ng-hide)');
</code>```

Title: Click All Javascript Jquery

Body:
When I run:

javascript:

var inputs = document.getElementsByClassName('subscribe_follow');

for(var i=0;i<inputs.length;i++) {
   inputs[i].click();
}

to click all buttons with the class class="subscribe_follow",
it also clicks all buttons with the class class="subscribe_follow ng-hide".

How do I only click the exact class?

Body:
You can use the not operator.

document.querySelectorAll('.subscribe_follow:not(.ng-hide)');

.subscribe_follow:not(.ng-hide) selector selects all the elements with the class subscribe_fellow but which do not have the ng-hide class.

jQuery

$('.subscribe_follow:not(.ng-hide)');


问:
Fragment IllegalStatexception on getResources()
I have this line inside SubCategoryFragment:

```<code>s.group_name = SubCategoryFragment.this.getResources().getString(R.string.everything_else); // line 315 in stacktrace
</code>```

My understanding was that by adding SubCategoryFragment.this to this would prevent the IllegalStatexception.

This is a ListFragment.  This occurs when someone clicks on a list item in this fragment, and goes to another; then hits the back button and returns to SubCategoryFragment.  onActivityCreated() where this line above ultimately resides.

I don't do anything inside onDetach() related to this.

```<code>java.lang.IllegalStateException:
  at android.support.v4.app.Fragment.getResources (Fragment.java:608)
  at ---.---.com.--.SubCategoryFragment.buildSubcategories (SubCategoryFragment.java:315)
  at ---.---.com.---.SubCategoryFragment$2.onResponse (SubCategoryFragment.java:287)
  at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run (ExecutorCallAdapterFactory.java:70)
  at android.os.Handler.handleCallback (Handler.java:751)
  at android.os.Handler.dispatchMessage (Handler.java:95)
  at android.os.Looper.loop (Looper.java:154)
  at android.app.ActivityThread.main (ActivityThread.java:6776)
  at java.lang.reflect.Method.invoke (Native Method)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1520)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1410)
</code>```

答:
Fragment.getResources() is a convenience call that fetches the Resources object from whatever Activity your fragment is currently attached to. If your fragment isn't attached to any activity, it will throw IllegalStateException.

Calling SubCategoryFragment.this.getResources() vs just getResources() won't make any difference.

There are two possible solutions to this problem. The first is to move the call to a place where you are guaranteed that your fragment will be attached to some activity. The other is to get a Resources object from somewhere other than the fragment (and therefore the fragment's activity). If you have access to some other Context object (perhaps by having a View you can call View.getContext() on), you can call Context.getResources() instead.

Body:
I have this line inside SubCategoryFragment:

s.group_name = SubCategoryFragment.this.getResources().getString(R.string.everything_else); // line 315 in stacktrace

My understanding was that by adding SubCategoryFragment.this to this would prevent the IllegalStatexception.

This is a ListFragment.  This occurs when someone clicks on a list item in this fragment, and goes to another; then hits the back button and returns to SubCategoryFragment.  onActivityCreated() where this line above ultimately resides.

I don't do anything inside onDetach() related to this.

java.lang.IllegalStateException:
  at android.support.v4.app.Fragment.getResources (Fragment.java:608)
  at ---.---.com.--.SubCategoryFragment.buildSubcategories (SubCategoryFragment.java:315)
  at ---.---.com.---.SubCategoryFragment$2.onResponse (SubCategoryFragment.java:287)
  at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run (ExecutorCallAdapterFactory.java:70)
  at android.os.Handler.handleCallback (Handler.java:751)
  at android.os.Handler.dispatchMessage (Handler.java:95)
  at android.os.Looper.loop (Looper.java:154)
  at android.app.ActivityThread.main (ActivityThread.java:6776)
  at java.lang.reflect.Method.invoke (Native Method)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1520)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1410)


问:
How to skip headers when we are reading data from a csv file in s3 and creating a table in aws athena.
I am trying to read csv data from s3 bucket and creating a table in AWS Athena. My table when created was unable to skip the header information of my CSV file.

Query Example :

```<code>CREATE EXTERNAL TABLE IF NOT EXISTS table_name (   `event_type_id`
     string,   `customer_id` string,   `date` string,   `email` string )
     ROW FORMAT SERDE  'org.apache.hadoop.hive.serde2.OpenCSVSerde'
     WITH
     SERDEPROPERTIES (   "separatorChar" = "|",   "quoteChar"     = "\"" )
     LOCATION 's3://location/'
     TBLPROPERTIES ("skip.header.line.count"="1");
</code>```

skip.header.line.count doesn't seem to work.
But this does not work out. I think Aws has some issue with this.Is there any other way that I could get through this?

答:
This is what works in Redshift:

You want to use table properties ('skip.header.line.count'='1')
Along with other properties if you want, e.g. 'numRows'='100'.
Here's a sample:

```<code>create external table exreddb1.test_table
(ID BIGINT
,NAME VARCHAR
)
row format delimited
fields terminated by ','
stored as textfile
location 's3://mybucket/myfolder/'
table properties ('numRows'='100', 'skip.header.line.count'='1');
</code>```

Body:
I am trying to read csv data from s3 bucket and creating a table in AWS Athena. My table when created was unable to skip the header information of my CSV file.

Query Example :

CREATE EXTERNAL TABLE IF NOT EXISTS table_name (   `event_type_id`
     string,   `customer_id` string,   `date` string,   `email` string )
     ROW FORMAT SERDE  'org.apache.hadoop.hive.serde2.OpenCSVSerde'
     WITH
     SERDEPROPERTIES (   "separatorChar" = "|",   "quoteChar"     = "\"" )
     LOCATION 's3://location/'
     TBLPROPERTIES ("skip.header.line.count"="1");

skip.header.line.count doesn't seem to work.
But this does not work out. I think Aws has some issue with this.Is there any other way that I could get through this?

Body:
This is what works in Redshift:

You want to use table properties ('skip.header.line.count'='1')
Along with other properties if you want, e.g. 'numRows'='100'.
Here's a sample:

create external table exreddb1.test_table
(ID BIGINT
,NAME VARCHAR
)
row format delimited
fields terminated by ','
stored as textfile
location 's3://mybucket/myfolder/'
table properties ('numRows'='100', 'skip.header.line.count'='1');


问:
Magnetize pen on custom grid

Hello,

I'm doing an illustration in pixel art mode.
I would like to be able to magnetize my pen tool on a custom grid.

I made a grid that cuts my image in 10px increments. But I can't make my 10px pen follow the grid.

Here's what I got:

Here's what I would like:

Is it possible to get this under Photoshop?

I tried to find out if anyone had ever wanted to do this but I didn't find any posts on it. If someone could tell me how to solve my problem.

Thank you.

PS: I'm on Photoshop CC 2015

答:
Fixed by disabling the spacing
It doesn't magnetize on the exact square but on the intersection but it's enough.

Title: Magnetize pen on custom grid


问:
Register an internal package on Pypi
I read somewhere that if you make an internal Python package for proprietary work, you should still register the name on PyPi to avoid potential future dependency issues.

How do I do this without posting my code publicly? This package contains code to be used internally at my work. Should I make an empty python package using the name I want to reserve and upload that to PyPi? And then install my package at work using git instead of PyPi?

Uploading an empty package seems like a silly thing to do that would just annoy other people. But I can't find a way to just register the name.

答:
Since the register command is deprecated and not supported anymore, you will have to perform the following steps:

Create a stub setup.py with empty package list, an initial version and the filled out metadata

Build and upload the package

Go to PyPI and delete the initial package version you just uploaded

This way, the package name will be reserved to you because you are registered as its owner now, but searching for the package will yield no results and any direct access will result in a 404.

Let's say you want to reserve the package name foo. Steps:

Create a new setup.py stub. Make sure packages list is empty so you don't upload some code by accident:

```<code>from setuptools import setup

setup(
    name='foo',
    version='0.0.1',
    description='',
    long_description='',
    url='https://www.example.com',
    author='me',
    author_email='me@example.com',
    packages=[],
    classifiers=['Development Status :: 1 - Planning'],
)
</code>```

Build and upload the package:

```<code>$ python setup.py bdist_wheel upload
running bdist_wheel
running build
...
running upload
Submitting /tmp/foo/dist/foo-0.0.1-py3-none-any.whl to https://upload.pypi.org/legacy/
Server response (200): OK
</code>```

Delete the uploaded wheel: go to the project page https://pypi.python.org/pypi?%3Aaction=pkg_edit&name=foo, where you will find the list of uploaded wheels - select one you uploaded and press Remove.

Now you have reserved the project name, since no one else will be able to upload a package foo unless you give them administrator permissions on PyPI:

```<code>$ python setup.py bdist_wheel upload
running bdist_wheel
running build
...
running upload
Submitting /tmp/foo/dist/foo-0.0.2-py3-none-any.whl to https://upload.pypi.org/legacy/
Upload failed (403): The user 'bar' is not allowed to upload to project 'foo'. See https://pypi.org/help#project-name for more information.
error: Upload failed (403): The user 'bar' is not allowed to upload to project 'foo'. See https://pypi.org/help#project-name for more information.

$ twine upload dist/foo-0.0.2-py3-none-any.whl
Uploading distributions to https://upload.pypi.org/legacy/
Uploading foo-0.0.2-py3-none-any.whl
HTTPError: 403 Client Error: The user 'bar' is not allowed to
upload to project 'foo'. See https://pypi.org/help#project-name for
more information. for url: https://upload.pypi.org/legacy/
</code>```

Any direct access attempts will end in a 404:

```<code>$ curl -I https://pypi.python.org/pypi/foo
HTTP/2 404
</code>```

Installing via pip will fail as expected:

```<code>$ pip install foo
Collecting foo
  Could not find a version that satisfies the requirement foo (from versions: )
No matching distribution found for foo
</code>```

PEP 541

Note that there is a PEP on Package Index Name Retention (PEP 541) that defines unreachable, abandoned, and invalid projects on the package index. In the section Name conflict resolution for active projects, it states:

None of the following qualify for package name ownership transfer:

...

User A owns a project X outside the Package Index. User B creates a package under the name X on the Index. After some time, User A wants to publish project X on the Index but realizes name is taken. This is true even if User A's project X gains notability and User B's project X is not notable.

So, although the PEP confirms that no one can take a name of an active project away from you, this is not guaranteed in the case of an inactive project which is a good countermeasure against name squatting. My understanding of this is that if you reserve a name now without developing anything and in the future, an open-source project emerges under that name and gets very popular, you can bet the project owner's rights will be taken away from you.

Also, note that empty packages or packages with no functionality can be qualified as an invalid package and be removed:

A project published on the Package Index meeting ANY of the following is considered invalid and will be removed from the Index:

...

project is name squatting (package has no functionality or is empty);

project name, description, or content violates the Code of Conduct; or

project is abusing the Package Index for purposes it was not intended.

Title: Register an internal package on Pypi

Body:
Since the register command is deprecated and not supported anymore, you will have to perform the following steps:

Create a stub setup.py with empty package list, an initial version and the filled out metadata

Build and upload the package

Go to PyPI and delete the initial package version you just uploaded

This way, the package name will be reserved to you because you are registered as its owner now, but searching for the package will yield no results and any direct access will result in a 404.

Let's say you want to reserve the package name foo. Steps:

Create a new setup.py stub. Make sure packages list is empty so you don't upload some code by accident:

from setuptools import setup

setup(
    name='foo',
    version='0.0.1',
    description='',
    long_description='',
    url='https://www.example.com',
    author='me',
    author_email='me@example.com',
    packages=[],
    classifiers=['Development Status :: 1 - Planning'],
)

Build and upload the package:

$ python setup.py bdist_wheel upload
running bdist_wheel
running build
...
running upload
Submitting /tmp/foo/dist/foo-0.0.1-py3-none-any.whl to https://upload.pypi.org/legacy/
Server response (200): OK

Delete the uploaded wheel: go to the project page https://pypi.python.org/pypi?%3Aaction=pkg_edit&name=foo, where you will find the list of uploaded wheels - select one you uploaded and press Remove.

Now you have reserved the project name, since no one else will be able to upload a package foo unless you give them administrator permissions on PyPI:

$ python setup.py bdist_wheel upload
running bdist_wheel
running build
...
running upload
Submitting /tmp/foo/dist/foo-0.0.2-py3-none-any.whl to https://upload.pypi.org/legacy/
Upload failed (403): The user 'bar' is not allowed to upload to project 'foo'. See https://pypi.org/help#project-name for more information.
error: Upload failed (403): The user 'bar' is not allowed to upload to project 'foo'. See https://pypi.org/help#project-name for more information.

$ twine upload dist/foo-0.0.2-py3-none-any.whl
Uploading distributions to https://upload.pypi.org/legacy/
Uploading foo-0.0.2-py3-none-any.whl
HTTPError: 403 Client Error: The user 'bar' is not allowed to
upload to project 'foo'. See https://pypi.org/help#project-name for
more information. for url: https://upload.pypi.org/legacy/

Any direct access attempts will end in a 404:

$ curl -I https://pypi.python.org/pypi/foo
HTTP/2 404

Installing via pip will fail as expected:

$ pip install foo
Collecting foo
  Could not find a version that satisfies the requirement foo (from versions: )
No matching distribution found for foo

PEP 541

Note that there is a PEP on Package Index Name Retention (PEP 541) that defines unreachable, abandoned, and invalid projects on the package index. In the section Name conflict resolution for active projects, it states:

None of the following qualify for package name ownership transfer:

...

User A owns a project X outside the Package Index. User B creates a package under the name X on the Index. After some time, User A wants to publish project X on the Index but realizes name is taken. This is true even if User A's project X gains notability and User B's project X is not notable.

So, although the PEP confirms that no one can take a name of an active project away from you, this is not guaranteed in the case of an inactive project which is a good countermeasure against name squatting. My understanding of this is that if you reserve a name now without developing anything and in the future, an open-source project emerges under that name and gets very popular, you can bet the project owner's rights will be taken away from you.

Also, note that empty packages or packages with no functionality can be qualified as an invalid package and be removed:

A project published on the Package Index meeting ANY of the following is considered invalid and will be removed from the Index:

...

project is name squatting (package has no functionality or is empty);

project name, description, or content violates the Code of Conduct; or

project is abusing the Package Index for purposes it was not intended.


问:
How to tweet with Twitterizer by using C#
i downloaded latest Twitterizer  . added these references.

```<code>using Twitterizer.Core;
using Twitterizer.Data;
using Twitterizer.Entities;
using Twitterizer.Streaming;
</code>```

now what do i need to do ? i searched internet but examples are old and probably not supported by twitter. can anbody explain me step by step ?

i just want to tweet via my account.

Edit: Problem solved by using TweetSharp. i suggest you to use TweetSharp instead of Twitterizer .

答:
You should include using Twitterizer; and not the others.

I have an example application posted on the downloads page: http://www.twitterizer.net/downloads/ It's an ASP.NET application, but the code and usage will be the same for desktop applications.

You can find access to methods by invoking methods on the main classes, such as:

TwitterUser

TwitterStatus (for tweets)

TwitterTimeline

You may also want to check out the code samples posted: http://www.twitterizer.net/category/code-sample/

Body:
i downloaded latest Twitterizer  . added these references.

using Twitterizer.Core;
using Twitterizer.Data;
using Twitterizer.Entities;
using Twitterizer.Streaming;

now what do i need to do ? i searched internet but examples are old and probably not supported by twitter. can anbody explain me step by step ?

i just want to tweet via my account.

Edit: Problem solved by using TweetSharp. i suggest you to use TweetSharp instead of Twitterizer .


问:
Spring Security for Hawt.io
I would like to configure Spring Security for Hawt.io with embedded tomcat. After custom login with (user and password) Hawt.io login is asking to authenticate.But Hawt.io authentication is disabled in code and in config. If I remove MvcConfig and WebSecurityConfig with security.basic.enable= false then without any authentication which works.But

I want to authenticate with custom username and password which is
  working after that Hawt.io is also asking the credentials though that
  part is disabled.

Please help me to resolve this.

application.properties

```<code>hawtio.authenticationEnabled = false
management.security.enabled=false
security.basic.enable= true
security.ignored= /**
</code>```

login.html

```<code><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
    <head>
        <title>Spring Security Example </title>
    </head>
    <body>
        <div th:if="${param.error}">
            Invalid username and password.
        </div>
        <div th:if="${param.logout}">
            You have been logged out.
        </div>
        <form th:action="@{/login}" method="post">
            <div><label> User Name : <input type="text" name="username"/> </label></div>
            <div><label> Password: <input type="password" name="password"/> </label></div>
            <div><input type="submit" value="Sign In"/></div>
        </form>
    </body>
</html>
</code>```

MvcConfig.java

```<code>@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/login").setViewName("login");
    }
}
</code>```

WebSecurityConfig.java

```<code>@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/","/hawtio").permitAll().anyRequest().authenticated().and()
                .formLogin().loginPage("/login")
                .permitAll().and().logout().permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
    }
}
</code>```

Application.java

```<code>@SpringBootApplication
@EnableHawtio
public class Application {
    public static void main(String[] args) {
        System.setProperty(AuthenticationFilter.HAWTIO_AUTHENTICATION_ENABLED, "false");
        SpringApplication.run(Application.class, args);
    }
}
</code>```

pom.xml

```<code>    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>io.hawt</groupId>
            <artifactId>hawtio-springboot</artifactId>
            <version>1.5.6</version>
        </dependency>
        <dependency>
            <groupId>io.hawt</groupId>
            <artifactId>hawtio-core</artifactId>
            <version>1.5.6</version>
        </dependency>
    </dependencies>
</code>```

Update:
Connect to dummy camel app like below login for again comes on giving credentials going to 404 error page.

答:
The following changes are required to make hawtio work with Spring Security and Spring Boot. You can find a working example here. However, I wasn't able to update the username in hawtio menubar.

Configure Spring Security

Configure Spring security for application in a standard way except for
a few changes specfic to hawtio:

Disable hawtio authentication,

```<code>@SpringBootApplication
@EnableHawtio
@ComponentScan(basePackages = {"com.basaki"})
public class Application {

    public static void main(String[] args) {
        System.setProperty(AuthenticationFilter.
            HAWTIO_AUTHENTICATION_ENABLED,"false");
        SpringApplication.run(Application.class, args);
    }
}
</code>```

Disable Cross-Site Request Forgery (CSRF) in your application.

Make sure the logout request URL matches the /hawtio/auth/logout/*.
This is the URL used by hawtio to invalidate a session.

```<code>@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    ...

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/").permitAll()
        .anyRequest().authenticated()
        .and().formLogin().loginPage("/login")
        .failureUrl("/login?error")
        .permitAll()
        .and().logout().logoutRequestMatcher(
        new AntPathRequestMatcher(
                "/hawtio/auth/logout/*"))
        .logoutSuccessUrl("/login?logout")
        .and().csrf().disable();
    }
    ...
}
</code>```

Login Page

Since you are using a form login, you will be needing a custom login page. In this example, a login.html is used.

Configure the /login request to match view login.html

```<code>@Configuration
public class SpringMvcConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/login").setViewName("login");
    }

    ...
}
</code>```

Updating hawtio's login.html

Once you log out from the hawtio page, it takes you to its own login page. Since it's a single page application with AngularJS, you need to replace this partial page with your own custom AngularJS based login page.

In this example, a login-hawtio.html page is used.

```<code><div ng-controller="LoginPlugin.LoginController">
    <h1 style="color: #78ab46;">Sign in</h1>

    <form action="/login" method="post">
        <div>
            <label style="font-weight: 700; padding-right: 15px;
                padding-left: 15px;">Username:
                <input id="username" type="text" name="username"
                     placeholder="Username"/>
            </label>
        </div>
        <div>
            <label style="font-weight: 700; padding-right: 15px;
                padding-left: 15px;">Password:
                <input id="password" type="password"
                    name="password" required
                    placeholder="Password"/>
            </label>
        </div>
        <div>
            <button type="submit" class="btn btn-default">Sign In</button>
        </div>
    </form>
</div>
</code>```

A controller to replace the existing hawtio login page.

```<code>@Controller
public class HawtioController {

    private ResourceLoader loader;

    @Autowired
    public HawtioController(ResourceLoader loader) {
        this.loader = loader;
    }

    @RequestMapping(value = "/hawtio/app/core/html/login.html", method = RequestMethod.GET,
        produces = "text/html;charset=UTF-8")
    public void getHawtioLoginHtml(HttpServletResponse response) {
        String location = "classpath:/templates/login-hawtio.html";
        try {
            String body = getResource(location);
            response.setStatus(HttpStatus.OK.value());
            response.getWriter().write(body);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            response.setStatus(HttpStatus.NOT_FOUND.value());
        }
    }
    ...
}
</code>```

hawtio Login Plugin

A custom hawtio plugin is needed to have your own AngularJS login controller, LoginPlugin.LoginController. It's used for redirecting to hawtio's home page after you are logged in from hawto's login page.

```<code>@Configuration
public class HawtioConfiguration {

    @Bean
    public HawtPlugin samplePlugin() {
        return new HawtPlugin("login-plugin",
            "/hawtio/plugins",
            "",
            new String[]{"plugin/js/login-plugin.js"});
    }
}
</code>```

The login-plugin.js is located under resources/app/webapp/plugin/js folder.

```<code>var LoginPlugin = (function(LoginPlugin) {

    LoginPlugin.pluginName = 'login-plugin';
    LoginPlugin.log = Logger.get('LoginPlugin');

    LoginPlugin.module = angular.module('login-plugin', ['hawtioCore'])
        .config(function($routeProvider) {
            $routeProvider.
            when('/home', {
                templateUrl: '/hawtio/index.html'
            });
         });

    LoginPlugin.module.run(function(workspace, viewRegistry, layoutFull) {

        LoginPlugin.log.info(LoginPlugin.pluginName, " loaded");
        viewRegistry["login-plugin"] = layoutFull;
        workspace.topLevelTabs.push({
            id: "LoginPlugin",
            content: "Login Plugin",
            title: "Login plugin loaded dynamically",
            isValid: function(workspace) { return true; },
            href: function() { return "#/login-plugin"; },
            isActive: function(workspace) {
                return workspace.isLinkActive("login-plugin"); }

        });
    });

    LoginPlugin.LoginController = function($scope, $rootScope, $http) {
        var fullUrl = "/hawtio/index.html";
        $http({method: 'GET', url: fullUrl});
    };

    return LoginPlugin;

})(LoginPlugin || {});

hawtioPluginLoader.addModule(LoginPlugin.pluginName);
</code>```

Title: Spring Security for Hawt.io

Body:
I would like to configure Spring Security for Hawt.io with embedded tomcat. After custom login with (user and password) Hawt.io login is asking to authenticate.But Hawt.io authentication is disabled in code and in config. If I remove MvcConfig and WebSecurityConfig with security.basic.enable= false then without any authentication which works.But

I want to authenticate with custom username and password which is
  working after that Hawt.io is also asking the credentials though that
  part is disabled.

Please help me to resolve this.

application.properties

hawtio.authenticationEnabled = false
management.security.enabled=false
security.basic.enable= true
security.ignored= /**

login.html

<!DOCTYPE html>

        <title>Spring Security Example </title>

            Invalid username and password.

            You have been logged out.

        <form th:action="@{/login}" method="post">

 User Name : <input type="text" name="username"/>

 Password: <input type="password" name="password"/>

<input type="submit" value="Sign In"/>

        </form>

MvcConfig.java

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/login").setViewName("login");
    }
}

WebSecurityConfig.java

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/","/hawtio").permitAll().anyRequest().authenticated().and()
                .formLogin().loginPage("/login")
                .permitAll().and().logout().permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
    }
}

Application.java

@SpringBootApplication
@EnableHawtio
public class Application {
    public static void main(String[] args) {
        System.setProperty(AuthenticationFilter.HAWTIO_AUTHENTICATION_ENABLED, "false");
        SpringApplication.run(Application.class, args);
    }
}

pom.xml

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>io.hawt</groupId>
            <artifactId>hawtio-springboot</artifactId>
            <version>1.5.6</version>
        </dependency>
        <dependency>
            <groupId>io.hawt</groupId>
            <artifactId>hawtio-core</artifactId>
            <version>1.5.6</version>
        </dependency>
    </dependencies>

Update:
Connect to dummy camel app like below login for again comes on giving credentials going to 404 error page.

Body:
The following changes are required to make hawtio work with Spring Security and Spring Boot. You can find a working example here. However, I wasn't able to update the username in hawtio menubar.

Configure Spring Security

Configure Spring security for application in a standard way except for
a few changes specfic to hawtio:

Disable hawtio authentication,

@SpringBootApplication
@EnableHawtio
@ComponentScan(basePackages = {"com.basaki"})
public class Application {

    public static void main(String[] args) {
        System.setProperty(AuthenticationFilter.
            HAWTIO_AUTHENTICATION_ENABLED,"false");
        SpringApplication.run(Application.class, args);
    }
}

Disable Cross-Site Request Forgery (CSRF) in your application.

Make sure the logout request URL matches the /hawtio/auth/logout/*.
This is the URL used by hawtio to invalidate a session.

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    ...

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/").permitAll()
        .anyRequest().authenticated()
        .and().formLogin().loginPage("/login")
        .failureUrl("/login?error")
        .permitAll()
        .and().logout().logoutRequestMatcher(
        new AntPathRequestMatcher(
                "/hawtio/auth/logout/*"))
        .logoutSuccessUrl("/login?logout")
        .and().csrf().disable();
    }
    ...
}

Login Page

Since you are using a form login, you will be needing a custom login page. In this example, a login.html is used.

Configure the /login request to match view login.html

@Configuration
public class SpringMvcConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/login").setViewName("login");
    }

    ...
}

Updating hawtio's login.html

Once you log out from the hawtio page, it takes you to its own login page. Since it's a single page application with AngularJS, you need to replace this partial page with your own custom AngularJS based login page.

In this example, a login-hawtio.html page is used.

<div ng-controller="LoginPlugin.LoginController">
    <h1 style="color: #78ab46;">Sign in</h1>

    <form action="/login" method="post">
        <div>
            <label style="font-weight: 700; padding-right: 15px;
                padding-left: 15px;">Username:
                <input id="username" type="text" name="username"
                     placeholder="Username"/>
            </label>
        </div>
        <div>
            <label style="font-weight: 700; padding-right: 15px;
                padding-left: 15px;">Password:
                <input id="password" type="password"
                    name="password" required
                    placeholder="Password"/>
            </label>
        </div>
        <div>
            <button type="submit" class="btn btn-default">Sign In</button>
        </div>
    </form>
</div>

A controller to replace the existing hawtio login page.

@Controller
public class HawtioController {

    private ResourceLoader loader;

    @Autowired
    public HawtioController(ResourceLoader loader) {
        this.loader = loader;
    }

    @RequestMapping(value = "/hawtio/app/core/html/login.html", method = RequestMethod.GET,
        produces = "text/html;charset=UTF-8")
    public void getHawtioLoginHtml(HttpServletResponse response) {
        String location = "classpath:/templates/login-hawtio.html";
        try {
            String body = getResource(location);
            response.setStatus(HttpStatus.OK.value());
            response.getWriter().write(body);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            response.setStatus(HttpStatus.NOT_FOUND.value());
        }
    }
    ...
}

hawtio Login Plugin

A custom hawtio plugin is needed to have your own AngularJS login controller, LoginPlugin.LoginController. It's used for redirecting to hawtio's home page after you are logged in from hawto's login page.

@Configuration
public class HawtioConfiguration {

    @Bean
    public HawtPlugin samplePlugin() {
        return new HawtPlugin("login-plugin",
            "/hawtio/plugins",
            "",
            new String[]{"plugin/js/login-plugin.js"});
    }
}

The login-plugin.js is located under resources/app/webapp/plugin/js folder.

var LoginPlugin = (function(LoginPlugin) {

    LoginPlugin.pluginName = 'login-plugin';
    LoginPlugin.log = Logger.get('LoginPlugin');

    LoginPlugin.module = angular.module('login-plugin', ['hawtioCore'])
        .config(function($routeProvider) {
            $routeProvider.
            when('/home', {
                templateUrl: '/hawtio/index.html'
            });
         });

    LoginPlugin.module.run(function(workspace, viewRegistry, layoutFull) {

        LoginPlugin.log.info(LoginPlugin.pluginName, " loaded");
        viewRegistry["login-plugin"] = layoutFull;
        workspace.topLevelTabs.push({
            id: "LoginPlugin",
            content: "Login Plugin",
            title: "Login plugin loaded dynamically",
            isValid: function(workspace) { return true; },
            href: function() { return "#/login-plugin"; },
            isActive: function(workspace) {
                return workspace.isLinkActive("login-plugin"); }

        });
    });

    LoginPlugin.LoginController = function($scope, $rootScope, $http) {
        var fullUrl = "/hawtio/index.html";
        $http({method: 'GET', url: fullUrl});
    };

    return LoginPlugin;

})(LoginPlugin || {});

hawtioPluginLoader.addModule(LoginPlugin.pluginName);


问:
Regex string match in c#
So, I'd like to check if a string of letters and digits is in correct format

Here's what it needs to look like:

```<code>123abc#456def#
</code>```

I've tried something like that:

```<code>Regex r = new Regex(@"^([0-9a-zA-Z]#)([0-9a-zA-Z]#)$");
</code>```

Didn't help me...

答:
Brief

As I mentioned in the comments you need to quantify your sets as such: [0-9a-zA-Z]{6}

Code

```<code>^([0-9a-zA-Z]{6}#)([0-9a-zA-Z]{6}#)$
</code>```

You can also do ^([0-9a-zA-Z]{6}#){2}$ since .net keeps multiple captures (not just the last one). See this shorter regex in use here. Click on Table and under the heading $1 expand 2 captures

For ensuring 3 numbers followed by 3 letters use either of the following patterns:

```<code>^(\d{3}[a-z]{3}#)(\d{3}[a-z]{3}#)$
^(\d{3}[a-z]{3}#){2}$
</code>```

And add IgnoreCase option

Title: Regex string match in c#

Body:
So, I'd like to check if a string of letters and digits is in correct format

Here's what it needs to look like:

123abc#456def#

I've tried something like that:

Regex r = new Regex(@"^([0-9a-zA-Z]#)([0-9a-zA-Z]#)$");

Didn't help me...

Body:
Brief

As I mentioned in the comments you need to quantify your sets as such: [0-9a-zA-Z]{6}

Code

^([0-9a-zA-Z]{6}#)([0-9a-zA-Z]{6}#)$

You can also do ^([0-9a-zA-Z]{6}#){2}$ since .net keeps multiple captures (not just the last one). See this shorter regex in use here. Click on Table and under the heading $1 expand 2 captures

For ensuring 3 numbers followed by 3 letters use either of the following patterns:

^(\d{3}[a-z]{3}#)(\d{3}[a-z]{3}#)$
^(\d{3}[a-z]{3}#){2}$

And add IgnoreCase option


问:
What response status code should I return?

I am having a simple shoppinglist app where users can create a shoppinglist, view a shopping list and even share a shopping list. My problem is given that a User has not created a shopping list lets say x but it has been created by another user and therefore it is in the database, what status code should I return to this User who didn't create this Shoppinglist? Should it be a 403 since it is in the database but this user has no permission to view it or should it be 404 since it does not exist in this user collection of shopping lists.

答:
You should return 404: the user shouldn't know about another cart with the same ID that is owned by a different user.

Returning 403 is considered a security flow because then a malicious hacker can start hitting your APIs with consecutive user-ids and until they find the user which owns the cart.


问:
ASP.NET MVC Adding records to related multiple tables from single view
I'm very new to MVC so i apologize if i haven't explained my requirement properly/haven't used correct terminology.

I have a simple database with item and detail entities. They have a one-to-many relationship so Item has many Details.

I'd like to add records to both these tables from a single view.

So far my understanding is that if i add a create action for 'item' it will get an 'item' object in the HTTPPost request. So does that mean i have to create a separate action/view for details?

Or is 'partial-view' what i should use here? Can someone please give me an example. Really appreciate it. Thanks.

答:
This is the best reference for this technique:

http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/


问:
How to return both an "id" and "text"
I am using AutoComplete to search by name. I'm able to output the names, but after submitting the form, I would like to pass the emp_id value, not the fullname. How can I modify it to get the emp_id value, not the fullname?

I would like it after I submit the form I get the emp_id not the fullname value.

search_employee.cfc

```<code><cfcomponent>
    <cffunction name="queryNames" access="remote">
        <cfargument name="searchPhrase" />

        <cfquery name="query_names"  datasource="">
            SELECT  fullname ,emp_id ....
        </cfquery>

        <cfset result = arrayNew(1) />

        <cfloop query="query_names">
            <cfset ArrayAppend(result, query_names.fullname) />

        </cfloop>

        <cfreturn result />
    </cffunction>
</cfcomponent>
</code>```

JavaScript

```<code><script>
    $(document).ready(function() {
        $('.gettingName').autocomplete({

            source: function(query, response) {
                $.ajax({
                    url: "test.cfc?method=queryNames&returnformat=json",
                    dataType: "json",
                    data: {
                        searchPhrase: query.term
                    },
                    success: function(result) {
                        response(result);
                    }
                });
            }
        });

</script>
</code>```

答:
Do you mean display the "FullName" selected, but store its ID in another form field?

Add a form field for storing the "id":

```<code>  <input id="gettingName">
  <input id="theValue">
</code>```

Modify the component to return an array of structures. Each structure containing two keys named "value" (id) and "label" (fullName).

```<code><cfloop query="local.query_names">
    <cfset local.data = {"value": emp_id, "label": fullName}>
    <cfset ArrayAppend(local.result, local.data) />
</cfloop>
</code>```

In the javascript, use the select event to update the values of the two fields.

```<code>select: function(event, ui) {
    $('#gettingName').val(ui.item.label);
    $('#theValue').val(ui.item.value);
    return false;
},
</code>```

Title: How to return both an "id" and "text"

Body:
I am using AutoComplete to search by name. I'm able to output the names, but after submitting the form, I would like to pass the emp_id value, not the fullname. How can I modify it to get the emp_id value, not the fullname?

I would like it after I submit the form I get the emp_id not the fullname value.

search_employee.cfc

<cfcomponent>
    <cffunction name="queryNames" access="remote">
        <cfargument name="searchPhrase" />

        <cfquery name="query_names"  datasource="">
            SELECT  fullname ,emp_id ....
        </cfquery>

        <cfset result = arrayNew(1) />

        <cfloop query="query_names">
            <cfset ArrayAppend(result, query_names.fullname) />

        </cfloop>

        <cfreturn result />
    </cffunction>
</cfcomponent>

JavaScript

Body:
Do you mean display the "FullName" selected, but store its ID in another form field?

Add a form field for storing the "id":

  <input id="gettingName">
  <input id="theValue">

Modify the component to return an array of structures. Each structure containing two keys named "value" (id) and "label" (fullName).

<cfloop query="local.query_names">
    <cfset local.data = {"value": emp_id, "label": fullName}>
    <cfset ArrayAppend(local.result, local.data) />
</cfloop>

In the javascript, use the select event to update the values of the two fields.

select: function(event, ui) {
    $('#gettingName').val(ui.item.label);
    $('#theValue').val(ui.item.value);
    return false;
},