text:
Q: how to change the format of graphique in ggplot to combine geom_col and geom_surface I'm trying to plot with ggplot my data frame by using the code bellow
p1 <- ggplot(dates2, aes(x=periode_ap, y=pourcentage_parc, fill=apport))+
        geom_col(position = position_stack(reverse = TRUE))+
        ylim(0,100)+
        scale_fill_manual(values=mycolors, name="")+
        theme_light()

i get this graphic

but what i want is this one ::

how can i change my code to get the right graphic please !!! or i must use another package not ggplot to do that !!

A: If you post your data, we can work with that.  Otherwise, here's an example of something that should work.  Use a combination of geom_area and geom_line with your data, and adjust fill= and color= aesthetics, respectively for each.
df <- data.frame(
  x=c(4,5,6,7,8:15,10,11,12,12,13,14,15),
  y=c(0,100,0,0,20,20,40,10,10,10,10,0,0,50,0,0,60,60,0),
  id=c(rep('Big Peak',3), rep('Other Thing',9),rep('Another Item',3),rep('At the end',4))
)

ggplot(df, aes(x,y)) + theme_bw() + xlim(0,20) +
  geom_area(aes(fill=id), alpha=0.2, position='identity') +
  geom_line(aes(color=id), size=0.8) +
  scale_y_continuous(expand=expansion(c(0,0.22))) +
  theme(legend.position=c(0.8,0.8), legend.background = element_rect(color='black'))

A potentially important aesthetic is to adjust the scale_y_continuous expansion to 0 for the bottom limit in order to avoid whitespace there.  Otherwise, your area geoms will be "floating" over the x axis line.


text:
Q: Does the equation $x^k+y^k-z^k-w^k=3\ (k>3)$ have a solution over $\mathbb N$? Clearly,
$$3=0^2+2^2-1^2-0^2\ \ \mbox{and}\ \ 3=4^3 +4^3-5^3-0^3.$$
Question. Let $k>3$ be an integer. Does the equation
$$ x^k+y^k-z^k-w^k=3\quad \ (x,y,z,w\in\mathbb N=\{0,1,2,\ldots\})\tag{1}$$
have a solution?
I have checked that the equation $(1)$ has no solution with $\max\{z,w\}\le 500$ for $k=4,5$. Also, for $k=6,7$, the equation $(1)$ has no solution with $\max\{z,w\}\le 300$. I conjecture that $(1)$ has no solution for each integer $k>3$.
By the way, I also conjecture that any integer can be written as $x^3+y^3-z^3-w^3$ with $x,y,z,w\in\mathbb N$ (see https://oeis.org/A351338). This is stronger than Sierpinski's conjecture that each integer is a sum of four integer cubes.
Your comments are welcome!

A: There are no solutions for $k>2$ even.
For $k$ even, $n^k$ is congruent to $1$ mod $8$ as soon as $n$ is odd. If $k>2$, then $n^k$ is conruent to $0$ mod $8$ as soon as $n$ is even.
So $x^k + y^k - z^k -w^k$ is congruent mod $8$ to a sum of two terms that are $0$ or $1$ and two terms that are $0$ or $-1$, i.e. to $-2, -1, 0,1$ or $2$.
Since none of these is $3$, there are no solutions modulo $8$, and thus no integer solutions.

redpajama_set_name: RedPajamaStackExchange


text:
Q: git: Make the work tree reflect only a subpath of the whole tree I would like to checkout a whole branch, but work only inside a specific directory of that branch. Therefore I would like to sort of "dive in" the whole tree and make my work tree reflect only the subdirectory that I chose. E.g.:
"master" tree
  dir1/
    file1
    file2
  dir2/
    file3

work-dir tree
  .git
  file1
  file2

My guess would be to do it like this:
git checkout master:dir1/

However, that doesn't work and reports the error:
fatal: Cannot switch branch to a non-commit 'master:dir1/'

Is this possible?
Note: I don't want to use submodules because I don't want to slice my repo into unrelated pieces. Subtree merge, as far as I can tell, only helps me to synchronize two separate directories with similar structures but different histories. I want to modify the original objects in the repo and be able to merge them back and forth and retain all the history.

A: It's not possible. You can however use cd dir1 and git will still work from there, allowing you to use git add file1 instead of git add dir1/file1 etc.


text:
Q: libpq-fe.h not found when running rake I'm currently having an issue raking a swift postgresql git submodule. The error is as follows:
 $ rake

    [19:38:19]
checking for uuid/uuid.h in /usr/include/uuid,/usr/include/postgresql,/usr/local/include/postgresql,/opt/local/include,/opt/local/include/postgresql90,/opt/local/include/postgresql85,/opt/local/include/postgresql84,/sw/include... yes
checking for libpq-fe.h in /usr/include/postgresql,/usr/local/include/postgresql,/opt/local/include,/opt/local/include/postgresql90,/opt/local/include/postgresql85,/opt/local/include/postgresql84,/sw/include... no
checking for main() in -luuid... yes
checking for main() in -lpq... yes
creating Makefile
compiling adapter.c
compiling common.c
In file included from adapter.c:6:
In file included from ./adapter.h:7:
./common.h:11:10: fatal error: 'libpq-fe.h' file not found
#include <libpq-fe.h>
         ^
In file included from common.c:5:
./common.h:11:10: fatal error: 'libpq-fe.h' file not found
#include <libpq-fe.h>
         ^
1 error generated.
make: *** [common.o] Error 1
make: *** Waiting for unfinished jobs....
1 error generated.
make: *** [adapter.o] Error 1
rake aborted!
unable to compile postgres
/Users/Dan/Dropbox/My Documents/Programming/Mash/mash-ios/swift-db-postgres/Rakefile:33:in `block (2 levels) in <top (required)>'
/Users/Dan/Dropbox/My Documents/Programming/Mash/mash-ios/swift-db-postgres/Rakefile:32:in `chdir'
/Users/Dan/Dropbox/My Documents/Programming/Mash/mash-ios/swift-db-postgres/Rakefile:32:in `block in <top (required)>'
Tasks: TOP => default => test => compile
(See full trace by running task with --trace)

I have checked that the file does exist at /usr/local/include/libpq-fe.h, and have tried including this in my build path, but the error persists. Uninstalling and reinstalling postgres has no effect. I'm thinking it may have to do with symlinks somewhere along the line, but have no idea how to tackle the issue. Can anyone help me out? Thanks!


text:
Q: How to merge one directory in Mercurial? I want to merge one directory from branch 'default' to 'A'. Currently I do merge and then revert all other directories. That's quite a lot of files.
Is there simpler way to do this?

A: Mercurial looks at the entire repository as being a 'unit'. As such, it's not possible to only merge a part of the repository. That wouldn't make sense, as you could then have a part of your repository on branch A and another part on branch B.
If that single directory can be considered a separate 'unit' from the rest of the repository, you could make it a subrepository. That way, you can merge the subrepository (which doesn't require merging the top-level repository).
However, keep in mind: subrepositories add complexity!


text:
Q: Type '(token: string) => Observable<{ headers: HttpHe aders; }>' is not assignable to type 'Observable' I've been going through rxjs and angular tutorials trying to understand Observables and how to chain them together. Based on everything I've read, the below code should work. But it doesn't and I don't understand why.
I'm trying to get a token from storage (faked that part out with getFakeToken method, because that compiles fine), then stuff that token in an httpHeaders object that should be wrapped in an observable that I can then chain together with another call to a web service and return that observable at the end of the day (which is why I'm not using a subscribe). I've taken the last call to the web service (that would use the http options built in the buildHttpOptions method) out, because the error is on the buildHttpOptions line.
I'm not sure I'm explaing everything properly, so here's another way of putting it: I'm trying to assynchronously get a token, insert that token into an httpOptions object, then (in the future iteration of the code that will be another ".pipe()" at the end of the return statement), use that to assynchronously call a web service and return the result wrapped in an observable. The first two parts (getting the token and inserting it into an object) are failing and I've included them in the code below.
Error message I'm getting:
[ng] ERROR in src/app/web-api/api.service.ts(57,50): error TS2322: Type '(token: string) => Observable<{ headers: HttpHe
aders; }>' is not assignable to type 'Observable<any>'.
[ng]   Property '_isScalar' is missing in type '(token: string) => Observable<{ headers: HttpHeaders; }>'.
[ng] src/app/web-api/api.service.ts(67,31): error TS2345: Argument of type 'Observable<any>' is not assignable to parame
ter of type 'OperatorFunction<string, any>'.
[ng]   Type 'Observable<any>' provides no match for the signature '(source: Observable<string>): Observable<any>'.

Code:
private getFakeToken(): Observable<string> {
    return of("123abc");
}

getGetData(): Observable<any> {
    let getToken$ = this.getFakeToken();

    let buildHttpOptions$: Observable<any> = (token: string) => { return of(
        {
            headers: new HttpHeaders({
                'Content-Type': 'application/json',
                'authorization': token
            })
        })};

    return getToken$.pipe(buildHttpOptions$);
}

A: You can use the map operator to convert an object in an Observable to a different object. Then use switchMap to chain your http request.
getGetData(): Observable<any> {
  return this.getFakeToken().pipe(
    map(token => ({
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'authorization': token
      })
    })),
    switchMap(headers => /* your http request that returns an Observable */)
  );
}


text:
Q: java : get distinct values from an elasticsearch index Currently I'm using this code which I had written to get the values from a field :
QueryBuilder qb = QueryBuilders.matchPhrasePrefixQuery("tagName", "june");
            SearchResponse response = esclient.prepareSearch(index).setTypes(type)
                    .setQuery(qb)
                    .execute().actionGet();

            SearchHit[] hits = response.getHits().getHits();
            System.out.println(hits.length);

            for (SearchHit hit : hits) {
                Map map = hit.getSource();
                System.out.println((String) map.get("tagName"));
                strings.add((String) map.get("tagName"));
            }

But is there an alternative to get distinct values from an index?
Or can the above can be modified?

A: You Can Use terms aggregation
This requires the field to be not analyzed.
    public static List<String> getDistinctAgg(TransportClient client, String indexName, String fieldName, int requiredSize) {
    List<String> values = new LinkedList<>();

    try {

        TermsAggregationBuilder aggregationBuilder = new TermsAggregationBuilder(fieldName + "_Agg", ValueType.STRING);
        aggregationBuilder.field(fieldName);
        aggregationBuilder.bucketCountThresholds(new TermsAggregator.BucketCountThresholds(1, 1, requiredSize, 5));

        QueryBuilder query = QueryBuilders.matchAllQuery();

        SearchResponse response = client.prepareSearch(indexName)
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(query).addAggregation(aggregationBuilder).setSize(0).get();
        if (response == null) return null;

        StringTerms terms = ((StringTerms) response.getAggregations().get(fieldName + "_Agg"));

        if (terms != null) {

            List<Terms.Bucket> buckets = terms.getBuckets();
            if (buckets != null && buckets.size() > 0) {

                for (Terms.Bucket bucket : buckets) {
                    values.add(bucket.getKeyAsString());
                }
            }
            return values;
        }

    } catch (Exception e) {
        return null;
    }
    return null;
}


text:
Q: Break if statement c++ error I'm writing linear and quadratic probing hash table program.
This is a for-loop I used for linear probing function and it works perfectly fine.
//when there's a collision increase i by 1 until finding empty slot
       for(i = (hashVal % tableSize+1) % tableSize; i <tableSize; i++)
           if(a[i] == -1){
               a[i] = hashVal;
               break;
           }

so I wrote a for loop again in quadratic probing function to deal with collision
//when there's a collision increase i by i^2
    j = 0;

    for(i=((hashVal % tableSize+1) % tableSize); i < tableSize; i++)
        j = i^2;
        if(a[j] == -1){
            a[j] = hashVal;
            break;
        }

But when I compile quadratic probing, I'm getting this error
error: 'break' statement not in loop or switch statement

I am really confused why it causes error in the second one while it is fine in linear probing. Could anyone explain why?

A: for(i=((hashVal % tableSize+1) % tableSize); i < tableSize; i++)
    j = i^2;

this is your cycle, since you didn't put curly braces around it.
fix is simple, put those braces:
for(i=((hashVal % tableSize+1) % tableSize); i < tableSize; i++)
{
    j = i^2;
    if(a[j] == -1){
        a[j] = hashVal;
        break;
    }
}

Rule of thumb - always put curly braces when you use cycle or if-statement, because it helps you to not make such errors as this.

A: Because only the immediately following statement is the for loop body, so
for(i=((hashVal % tableSize+1) % tableSize); i < tableSize; i++)
    j = i^2; // the body of for loop

// not for loop body from here (note the correct indent position)
if(a[j] == -1){
    a[j] = hashVal;
    break;
}

For your 1st code sample, the whole if statement is the for loop body, so it works fine.
To fix your code, you could use braces to make it a compound statement, which may consist of multiple statements.
for(i=((hashVal % tableSize+1) % tableSize); i < tableSize; i++) {
    j = i^2;

    if(a[j] == -1){
        a[j] = hashVal;
        break;
    }
}

A: You didn't put braces around the body of your for statement. This works in the first example because the body is just the if statement, but in your second example, only j = i^2; is parsed as part of the for. The code is equivalent to:
//when there's a collision increase i by i^2
j = 0;

for(i=((hashVal % tableSize+1) % tableSize); i < tableSize; i++) {
    j = i^2;
}

if(a[j] == -1){
    a[j] = hashVal;
    break;
}

You can fix this by adding braces in the correct place:
//when there's a collision increase i by i^2
j = 0;

for(i=((hashVal % tableSize+1) % tableSize); i < tableSize; i++) {
    j = i^2;
    if(a[j] == -1){
        a[j] = hashVal;
        break;
    }
}

A good rule of thumb is to put braces around any loop body which is more than a single line long. Many would recommend even putting braces around single lines in case you want to add more to the loop body at a later time.


text:
Q: I'm trying to create an Ad - Hoc bulid but failed So I'm trying to create an Ad - Hoc bulid but after trying to export this archive, I keep getting the following error:

A: First of try and edit the distribution profile and download it again then restart the xcode.
If that don't work then try this....
go to keychain access, -> Show Expired Certificates, and check your expired certificates and delete them from both the login and System keychains.
Then download a new one from https://developer.apple.com/certificationauthority/AppleWWDRCA.cer and add it to and add it to Keychain access -> certificates


text:
Q: How to free nodes in list of lists in C? (Game) I'm making a game, I put icons in the nodes of the mesh and I'm using this struct:
typedef struct node{
    int x,y; //coordinates for graphics.h
    struct node *right, *left, *up, *down;
}Node;

I read the file with the icon with this:
int** ReadPixelFile(int *width, int *height, char name[50])
{
    FILE *fp;
    char address[150];
    int i, j;
    int **mesh;

    strcpy(address, "./Sprites/");
    strcat(address, nombre);
    strcat(address, ".pix");

    fp = fopen( address, "rb" );

    if(fp == NULL)
    {
        printf("[Error]: cannot read .pix file\n");
        return 0;
    }

    //Read Width x Height
    fread(width, sizeof(int), 1, fp);
    fread(height, sizeof(int), 1, fp);

    AllocMemory(&mesh, *width, *height); //Here is when I allocate memory

    for(i = 0; i < *width; i++)
    {
        for(j = 0; j < *height; j++)
        {
            fread(*(mesh+ i) + j, sizeof(int), 1, fp);
        }
    }

    fclose(fp);

    return mesh;
}

and I'm allocating memory with this:
void AllocMemory(int ***mesh, int iWidth, int iHeight)
{
    int i;

    *mesh = (int**)malloc(sizeof(int*)*iWidth);

    for(i = 0; i < iWidth; i++)
        *(*mesh+ i) = (int*)malloc(sizeof(int)*iHeight);

    if(!**mesh)
    {
        settextstyle(1,1,5);
        setcolor(RED);
        outtextxy(1280/3, 720/2, "Error: NO memory.");
    }
}

The thing is that I could play and the icons won't have any problem, here is a screenshot from the game:
https://scontent-dft4-1.xx.fbcdn.net/v/t1.0-9/15391071_10154209405046985_8141714891735886530_n.jpg?oh=4208ce0da45b76bed3ea5b85c2fbccee&oe=58B7F3CB
(I uploaded it to Facebook because my school won't let me use Imgur and that kind of websites)
The rectangles represent the mesh and that every icon is one of the nodes, with the time I noticed that the game crashed way more often and then almost everytime I loaded the game, my teacher told me that I was running out of memory and he told me to free memory but I don't know how to free memory because he never told us how to do so and also in which part of the game to free the memory, I'm thinking about doing it everytime I call gameOver()
void gameOver()
{
    setbkcolor(BLACK);
    cleardevice();
    setcolor(RED);
    settextstyle(GOTHIC_FONT, HORIZ_DIR, 7);
    outtextxy(640-textwidth("Game Over")/2, 360-textheight("Game Over")/2, "Game Over");
    settextstyle(GOTHIC_FONT, HORIZ_DIR, 3);
    outtextxy(640-textwidth("Press any letter to try again")/2, 600-textheight("Press any letter to return")/2, "Press any letter to return");

    if(kbhit())
    {
        setactivepage(0);
        cleardevice();
        Core(LIVES); //This is like the main function of the game
    }
}

In Core() I call ReadPixelFile() and that is when I allocate memory... So should free the memory before I call Core() and run the game again? Please help, the game is complete and I just need to free up memory so it won't crash.
Thank you.

A: In many cases, this simple trick allows to deallocate memory in C quickly and prevent leaks:
Instead of using plain malloc or calloc, make a simple wrapper (call it MALLOC for example) which will add a link field to allocated blocks, and keep internal list of all blocks.
When you need to free the whole mess, go thru this list and call free() on every item.
Variant: when you know the maximum size, instead of a list, pre-allocate a large buffer and use just one pointer to allocate from this buffer. You can have several such pools for several purposes.
To free everything, just free the large buffer. Or keep it and reuse, if you want to run another iteration of the program.
It looks that in your situation this can work.
/* Teachers of C courses hate this trick because they think it promotes laziness. For me this is example of pragmatic engineering, targeted to prevent certain problem rather than letting it in and debugging later. */
Code example for a "big buffer" variant:

    /* somewhere in your main() */
    unsigned pool_size = 100000; /* maximum size */
    unsigned pool_allocated = 0;
    char *pool_ptr = (char*)malloc(pool_size);
    assert(pool_ptr);
    ....

    // Allocation function:
    void* my_alloc(unsigned size)
    {
       char *p;
       if (size == 0)
           return NULL;
       if ( (pool_allocated + size) > pool_size )
          return NULL;
       p = &pool_ptr[pool_allocated];
       pool_alocated += size;
       return (void*)p;
    }

    void recycle_memory(void)
    {
        pool_allocated = 0; //that's simple :)
    }


text:
Q: R pass argument when sourcing another file under foreach I wrote a program to_source.R which leaves some configuration parameters out. Now I want to run for different parameters in parallel. For example,
In to_source.R
cat(paste0(config, ' is finished')

and in main.R
config = 1
source("to_source.R")

This works. But running in parallel (with foreach/doParallel in windows)
In main_para.R
parallel_cluster = parallel::makeCluster(5)
doParallel::registerDoParallel(parallel_cluster)

configs = 6:10
foreach(config = configs, .combine = rbind, .packages = c("data.table", "foreach")) %dopar% {
  source("to_source.R")
}

parallel::stopCluster(parallel_cluster)

This fails because Error in { : task 1 failed - object 'config' not found
This is very close to the question How to pass command-line arguments when source() an R file, but the answer there does not work under foreach


text:
Q: codepage conversion support on linux I have two questions regarding codepages on linux.

*

*Is there any way to list out all the combination of codepages conversions possible on linux.

*If i have a file with data encoded in some format(say encode-1), i can use
"iconv -f encode-1 -t encode-2 file > file1.txt" to encode it into encode-2 format.
This way i can check conversion from encode-1 to encode-2 is possible. But for this to test i need to have some file already encoded in encode-1 format. Is there any way to test whether a particular conversion is possible without having any file already encoded with format encode-1.

A: You seem to be using iconv. To get the list of all possible encodings, just run
iconv -l

If you do not have any file in a given encoding, you can create one: take any file in a known encoding and use iconv to convert it into the given encoding. If you are worried the conversion can exit in the middle, use
iconv -c

It omits invalid characters in the output, but encodes everything it can.


text:
Q: Sum of the digits of the number 2^1000 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2 power of 1000 (2^1000)?
Can anyone provide the solution or algorithm for this problem in java?

A: Here is my solution:
public static void main(String[] args) {

    ArrayList<Integer> n = myPow(2, 100);

    int result = 0;
    for (Integer i : n) {
        result += i;
    }

    System.out.println(result);
}

public static ArrayList<Integer> myPow(int n, int p) {
    ArrayList<Integer> nl = new ArrayList<Integer>();
    for (char c : Integer.toString(n).toCharArray()) {
        nl.add(c - 48);
    }

    for (int i = 1; i < p; i++) {
        nl = mySum(nl, nl);
    }

    return nl;
}

public static ArrayList<Integer> mySum(ArrayList<Integer> n1, ArrayList<Integer> n2) {
    ArrayList<Integer> result = new ArrayList<Integer>();

    int carry = 0;

    int max = Math.max(n1.size(), n2.size());
    if (n1.size() != max)
        n1 = normalizeList(n1, max);
    if (n2.size() != max)
        n2 = normalizeList(n2, max);

    for (int i = max - 1; i >= 0; i--) {
        int n = n1.get(i) + n2.get(i) + carry;
        carry = 0;
        if (n > 9) {
            String s = Integer.toString(n);
            carry = s.charAt(0) - 48;
            result.add(0, s.charAt(s.length() - 1) - 48);
        } else
            result.add(0, n);
    }

    if (carry != 0)
        result.add(0, carry);

    return result;
}

public static ArrayList<Integer> normalizeList(ArrayList<Integer> l, int max) {
    int newSize = max - l.size();
    for (int i = 0; i < newSize; i++) {
        l.add(0, 0);
    }
    return l;
}

This code can be improved in many ways ... it was just to prove you can perfectly do it without BigInts.
The catch is to transform each number to a list. That way you can do basic sums like:
123456
+   45
______
123501

A: int result = 0;

String val = BigInteger.valueOf(2).pow(1000).toString();

for(char a : val.toCharArray()){
    result = result + Character.getNumericValue(a);
}
System.out.println("val ==>" + result);

It's pretty simple if you know how to use the biginteger.

A: I won't provide code, but java.math.BigInteger should make this trivial.

A: This problem is not simply asking you how to find the nearest big integer library, so I'd avoid that solution. This page has a good overview of this particular problem.

A: Create a vector of length 302, which is the length of 2^1000. Then, save 2 at index 0, then, double 1000 times. Just look at every index separetly and add 1 to the next index if the previous exeeds 10. Then just sum it up!

A: something like that sould do it bute force: - although there is a nice analytic solution (think pen& paper) using mathematics - that may also work for numbers greater than 1000.
    final String bignumber = BigInteger.valueOf(2).pow(1000).toString(10);
    long result = 0;
    for (int i = 0; i < bignumber.length(); i++) {
        result += Integer.valueOf(String.valueOf(bignumber.charAt(i)));
    }
    System.out.println("result: " + result);

A: How can 2^1000 be alternatively expressed?
I don't remember much from my maths days, but perhaps something like (2^(2^500))? And how can that be expressed?
Find an easy way to calculate 2^1000, put the result in a BigInteger, and the rest is perhaps trivial.

A: Here is my code... Please provide the necessary arguments to run this code.
import java.math.BigInteger;
public class Question1 {
    private static int SumOfDigits(BigInteger inputDigit) {
        int sum = 0;
        while(inputDigit.bitLength() > 0) {
            sum += inputDigit.remainder(new BigInteger("10")).intValue();
            inputDigit = inputDigit.divide(new BigInteger("10"));
        }
        return sum;
    }

    public static void main(String[] args) {
        BigInteger baseNumber = new BigInteger(args[0]);
        int powerNumber = Integer.parseInt(args[1]);
        BigInteger powerResult = baseNumber.pow(powerNumber);
        System.out.println(baseNumber + "^" + powerNumber + " = " + powerResult);
        System.out.println("Sum of Digits = " + Question1.SumOfDigits(powerResult));
    }

}

A: 2^1000 is a very large value, you would have to use BigIntegers. The algorithm would be something like:
import java.math.BigInteger;
BigInteger two = new BigInteger("2");
BigInteger value = two.pow(1000);
int sum = 0;
while (value > 0) {
  sum += value.remainder(new BigInteger("10"));
  value = value.divide(new BigInteger("10"));
}

A: Alternatively, you could grab a double and manipulate its bits. With numbers that are the power of 2, you won't have truncation errors. Then you can convert it to string.
Having that said, it's still a brute-force approach. There must be a nice, mathematical way to make it without actually generating a number.

A: In[1162] := Plus @@ IntegerDigits[2^1000]
Out[1162] = 1366


text:
Q: How to create a vector of 'alpha-shapes' in matlab? My objective is to change the parameters of different alpha-shapes in a vector, but first, I need to create this vector in a loop. However, if I write:
shp(1,1) = alphaShape(...); %with ... the vertices of an isosurface

It's okay, but in the second iteration, when it does:
shp(1,2) = alphaShape(...);

It gives me the error that Error using alphaShape/subsasgn. Invalid arguments in indexing operation.
I don't dive you any code because I tried separately to create a vector and it didn't work. I hope someone can help me.
Thank you in advance for your responses.

A: You can use a cell array to store more than one object:
%Empty cell creation:
shp    = cell(0);

%Add new objects into your cell
for ii = 1:2
  shp{ii} = alphaShape(...);
end

A: Indexing is not possible for object types. What could help you is constructing an Object Array. Have a look at this: https://www.mathworks.com/help/matlab/matlab_oop/creating-object-arrays.html


text:
Q: Regular expression to validate A123456 What is a suitable regular expression to validate that a string matches the format A123456
First letter must be a letter upper case or lower case then exactly 6 numeric numbers following it.
I'm using c# .net if that has any effect on the formatting.

A: Well, you need to search for the following pattern:

*

*((?i)) - [Modifiers] Case-insensitive

*(^) - Begin

*

*([a-z]) - A single letter

*(\d{6}) - Digits 0-9 with length of 6

*( $) - End

Resulting regular expression: (?i)^[a-z]\d{6}$
Regex alpha1numeric6Pattern = new Regex(@"(?i)^[a-z]\d{6}$");

See it in action: 3aaeea6ad8ce3e4ab9ac@csharppad.

A: Try this:
^[a-zA-Z]\d{6}$

You would benefit from a quick read at http://www.regularexpressions.info

A: This would do what you are after: ^[A-Za-z]\d{6}$. An example can be seen here.


text:
Q: Is a selector like *+* safe to use? I recently came across this CSS selector while trying to find a way to easily space out major blog elements such as paragraphs and images. An example of its use would be something like this:
.post *+* {margin-top: 15px;}
/* or... */
.post > *+* {margin-top: 15px;}
/* if you don't want the margin to apply to nested elements */

At first glance, it seemed pretty useful. So my question is: What downsides are there to using these selectors?
Specifically:

*

*What's the browser support like for this?

*Are there any cases you wouldn't want an even margin spacing between elements in an article and if not, is it easier to declare this first and then overwrite or simply declare each element individually?

*Does this have performance issues since you're selecting everything twice?

A: *

*
What's the browser support like for this?

Basically, IE7+ and any other modern browser.
There may be corner cases for each browser depending on what elements are actually being selected or queried with the sibling combinator +, but I wouldn't worry about those as much as the fact that the margin is being applied to just about any element that's a sibling for no practical reason.

*
Are there any cases you wouldn't want an even margin spacing between elements in an article and if not, is it easier to declare this first and then overwrite or simply declare each element individually?

It does seem pretty useful at first glance, but if you think about it, it'll probably be a much better idea to be more specific about what to apply the margin to. This is one rule that I can imagine will be overridden many, many times throughout the rest of the stylesheet by other specific selectors, making it quite redundant and even undesired in many cases. I can't think of any real-world use for a rule like your example.
Bear in mind that, in this specific case, vertical margins will collapse, so you only need to define vertical margins for a set of elements without having to resort to applying margin-top exclusively to all of an element's following siblings.

*
Does this have performance issues since you're selecting everything twice?

Actually, it's not selecting everything twice. The browser only looks at each element once, then determines whether each element follows another one under the same parent element. It doesn't care what kind of element it follows, as long as it follows another. It doesn't go around selecting every element again then compare to see if they're siblings of each other.
Now, people say that using the universal selector * in conjunction with just about any combinator causes rendering performance catastrophes, so people say that this kind of stuff should be avoided at all costs. But this stuff is hardly important at all (honestly, a selector like * + * is only a few microseconds slower than p + p), so you really don't need to worry about it. Consider the utility of the CSS rule itself first, then decide whether you really need the rule based on that.

Now with all that said (it's getting pretty late here), I would probably have rewritten the example like this, based on what I said above regarding collapsing margins:
.post > * { margin: 15px 0; }

It's probably only worth replacing the * with p if you know that the only children you want to space out are paragraphs:
.post > p { margin: 15px 0; }

Or any paragraphs within .post for that matter (e.g. within blockquotes):
.post p { margin: 15px 0; }

(* being used with the descendant selector is fair game, I'll admit; the child combinator, on the other hand, is limited to only one level of nesting, so for anyone obsessing about performance, this won't hurt at all.)

A: It's called the "Sibling Selector".
According to SitePoint, it's supported in all recent browsers and in IE8+.  IE7 has a few limitations explained on the SitePoint page, but will mostly work as well.
It's defined in the CSS2 spec.
About the performance: a lot of CSS is overriding other selectors.  That's part of the cascading nature of it.  Also, performance varies so much between render engines that it's not practical to worry about performance when it comes to CSS.

A: You should also consider IE7 bug related to ignoring adjacent-sibling combinator (as well as :first-child pseudoclass) if HTML comment is in place of where IE7 expects to see an element. There is a workaround that removes comments as DOM nodes after page is loaded in IE7.


text:
Q: SQL Query With In Operator returns data mentioned in IN clause, how to find that data doesnot exists for one param mentioned in IN SQL Query With In Operator returns data mentioned in IN clause, how to find that data doesnot exists for one param mentioned in IN
Example :
Select EmpName from Salary Where EmpID In (1,2,3,4,100)

Now there is no record by Id 100 in table but result does not reflect this,
Any Clue

A: I would probably create a temporary table and do a LEFT or RIGHT join to then always select the EmpID from my temp table and either have NULL or EmpName from Salary displayed.
you would then end up with a query like: -
SELECT
    T.EmpId,
    S.EmpName
FROM
   Salary S
LEFT OUTER JOIN
   TempTable T
ON
   T.EmpID = EmpID

A: This
Select EmpName
from Salary
Where EmpID In (1,2,3,4,100)

is equivalent to
Select EmpName
from Salary
Where EmpID = 1
  OR EmpID = 2
  OR EmpID = 3
  OR EmpID = 4
  OR EmpID = 100

And will return all the rows where the where condition is true.
It will not return a row with EmpID=100, if there is no such row...
This is a messy way of getting what you want achieved, in MySQL
select ids_to_get.id, EmpName from
from
(select 1 id
union all
select 2 id
union all
select 3 id
union all
select 4 id
union all
select 100 id) ids_to_get
left join Salary on ids_to_get.id = Salary.EmpID

This will return the ids in one column, and the eployee names in the other. if there is no such employee, it will have NULL as the name. (this is what the LEFT JOIN does)
However, this is ugly. Indeed, very ugly, not scalable, and generally something to avoid. I'd advise not to use such a construct... If there is no way to create a temp table, and the IDs don't come from another query, I'd advise to check it in the application rather than use this union-ed structure.


text:
Q: Puphpeteer - Get text and href-attribute from link I am using "@nesk/puphpeteer": "^2.0.0" Link to Github-Repo and want get the text and the href-attribute from a link.
I tried the following:
<?php

require_once '../vendor/autoload.php';

use Nesk\Puphpeteer\Puppeteer;
use Nesk\Rialto\Data\JsFunction;

$debug = true;

$puppeteer = new Puppeteer([
    'read_timeout' => 100,
    'debug' => $debug,
]);
$browser = $puppeteer->launch([
    'headless' => !$debug,
    'ignoreHTTPSErrors' => true,
]);

$page = $browser->newPage();
$page->goto('http://example.python-scraping.com/');

//get text and link
$links = $page->querySelectorXPath('//*[@id="results"]/table/tbody/tr/td/div/a', JsFunction::createWithParameters(['node'])
    ->body('return node.textContent;'));

// iterate over links and print each link and its text

// get single text
$singleText = $page->querySelectorXPath('//*[@id="pagination"]/a', JsFunction::createWithParameters(['node'])
    ->body('return node.textContent;'));

$browser->close();

When I run the above script I get the nodes from the page, BUT I cannot access the attributes or the text?
Any suggestions how to do this?
I appreciate your replies!

A: querySelectorXPath return array of ElementHandle. one more thing querySelectorXPath does not support callback function.
first get all node ElementHandle
$links = $page->querySelectorXPath('//*[@id="results"]/table/tbody/tr/td/div/a');

then loop over links to access attributes or text of node
foreach($links as $link){
   // for text
    $text = $link->evaluate(JsFunction::createWithParameters(['node'])
    ->body('return node.innerText;'));

  // for link
  $link = $link->evaluate(JsFunction::createWithParameters(['node'])
    ->body('return node.href;'));
}

A: Disclaimer: This is just an intermediate answer - I would update once I've got more specific requests on HTML attrs or other expectations to be retrieved.
tl;dr: Mentioned composer package nesk/puphpeteer really is just a wrapper to underlying NodeJS based implementation of puppeteer. Thus, accessing data and structures has to be "similar" to their JavaScript counterparts...
Maybe Codeception (headless) or symfony/dom-crawler (raw markup) might be better and more mature alternatives.

Anyway, let's pick the example from above and go through it step by step:
$links = $page->querySelectorXPath(
  '//*[@id="results"]/table/tbody/tr/td/div/a',
  JsFunction::createWithParameters(['node'])->body('return node.textContent;')
);

*

*XPath query $x() would result in an array of ElementHandle items

*to access exported node.textContent (from JsFunction), corresponding data gets fetched via ElementHandle.getProperty(prop)

*exporting a scalar value (to PHP) is then done via ElementHandle.jsonValue()
Thus, after that we would have something like this:
$links = $page->querySelectorXPath(
  '//*[@id="results"]/table/tbody/tr/td/div/a',
  JsFunction::createWithParameters(['node'])->body('return node.textContent;')
);

/** @var \Nesk\Puphpeteer\Resources\ElementHandle $link */
foreach ($links as $link) {
  var_dump($link->getProperty('textContent')->jsonValue());
}

Which outputs the following raw data (as retrieved from http://example.python-scraping.com/):
string(12) " Afghanistan"
string(14) " Aland Islands"
string(8) " Albania"
string(8) " Algeria"
string(15) " American Samoa"
string(8) " Andorra"
string(7) " Angola"
string(9) " Anguilla"
string(11) " Antarctica"
string(20) " Antigua and Barbuda"


text:
Q: Spring/Hibernate and relational mapping I'm new to Spring MVC and Hibernate (and also databases in general), so would like some help.
Currently I have 2 tables in my database - Booking and Restaurant. Booking has a foreign key R_id that points to the primary key of Restaurant. Right now I'm trying to implement a drop-down menu which displays all the restaurants in the database and when the user chooses a restaurant, the value is set in that Booking database. I hope you understand what I mean.
My Booking class:
@Entity
@Table(name="booking")
public class Booking {

    @Id
    @Column(name="id")
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private Long id;

    @ManyToOne
    @JoinColumn(name="R_id")
    private Restaurant restaurant;

    @Column(name="date")
    @Type(type="date")
    private Date date;

    @Column(name="start")
    @Type(type="time")
    private Date start;

    @Column(name="duration")
    private float duration;

    @Column(name="amount_of_people")
    private int amountOfPeople;

    @Column(name="name")
    private String name;

    @Column(name="contact_preference")
    private String contactPreference;

    @Column(name="comments")
    private String comments;

    @Column(name="current_datetime")
    @Type(type="timestamp")
    private Date currentDatetime;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Restaurant getRestaurant() {
        return restaurant;
    }

    public void setRestaurant(Restaurant restaurant) {
        this.restaurant = restaurant;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public Date getStart() {
        return start;
    }

    public void setStart(Date start) {
        this.start = start;
    }

    public float getDuration() {
        return duration;
    }

    public void setDuration(float duration) {
        this.duration = duration;
    }

    public int getAmountOfPeople() {
        return amountOfPeople;
    }

    public void setAmountOfPeople(int amountOfPeople) {
        this.amountOfPeople = amountOfPeople;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getContactPreference() {
        return contactPreference;
    }

    public void setContactPreference(String contactPreference) {
        this.contactPreference = contactPreference;
    }

    public String getComments() {
        return comments;
    }

    public void setComments(String comments) {
        this.comments = comments;
    }

    public Date getCurrentDatetime() {
        return currentDatetime;
    }

    public void setCurrentDatetime(Date currentDatetime) {
        this.currentDatetime = currentDatetime;
    }

}

Restaurant class:
@Entity
@Table(name="restaurant")
public class Restaurant {

    @Id
    @Column(name="id")
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private Long id;

    @Column(name="restaurant_name")
    private String restaurantName;

    @Column(name="address")
    private String address;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getRestaurantName() {
        return restaurantName;
    }

    public void setRestaurantName(String restaurantName) {
        this.restaurantName = restaurantName;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String toString() {
        return restaurantName;
    }

}

Relevant methods in MainController:
    @RequestMapping(value = "booking/create", method = RequestMethod.GET)
    public String createBooking(Model model) {
        model.addAttribute("booking", new Booking());
        initModelList(model);
        return "newBooking";
    }

    @RequestMapping(value = "booking/create", method = RequestMethod.POST)
    public String createBookingAction(Booking booking) {
        bookingService.addBooking(booking);
        return "redirect:/bookings";
    }

     .....

    private void initModelList(Model model) {
    List<Restaurant> restaurantList = restaurantService.getRestaurants();
        model.addAttribute("restaurants", restaurantList);

    }

And here is my jsp file:
<%@ page contentType="text/html; charset=UTF-8" %>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<!DOCTYPE html>

<jsp:include page="../fragments/head.jsp"/>

<jsp:include page="../fragments/menu.jsp"/>

Create new booking

    <form:form method="POST" commandName="booking" class="bookingForm">

                Restaurant:
                <form:select path="restaurant">
                    <form:option value="NONE" label="--- Select ---" />
                    <form:options items="${restaurants}" />
                </form:select>

                <input type="submit" />

    </form:form>

        Back to List

<jsp:include page="../fragments/footer.jsp"/>

Right now the drop-down menu displays the restaurants but when I click submit it gives me this error: The request sent by the client was syntactically incorrect.
I think it's because there is something wrong with the mapping between Booking and Restaurant, but I don't know what it is. Sorry for the long post, any help is appreciated. Thanks!

A: Your controller booking/create POST is expecting a valid Booking object in the request you are sending from your JSP form.
You can try changing
<form:select path="restaurant">

to
<form:select path="restaurant.restaurantName">

Since the form itself will add the contents to a booking object so this field will effectively map to booking.restaurant.restaurantName, which makes it a valid Booking object.
Also note that your controller at this point will be getting a booking object with just one field having data. you need to fetch the rest of the data of related objects from db (like ids), before saving the data.

A: Consider to use dedicated Forms, it's a way good practice.
In your case it would be a dedicated user class named BookingAddForm with raw datatypes like Integer and String including collections that contain the only info you need for the operation, in your case the restaurant names list. So, the complex object list binding simple wouldn't be needed and would everything work fine.
After, you can easily handle it on the service layer. Create there your Hibernate entities from the data you've loaded and handle it however you need. The same story for data retrieving.

At the code you've specified you've missed @ModelAttribute annotation to associate the form with your controller. It should be like this:
@RequestMapping(value = "booking/create", method = RequestMethod.POST)
public String createBookingAction(@ModelAttribute @Valid BookingAddForm bookingAddForm, BindingResult br) {

    // validation required!
    bookingService.addBooking(bookingAddForm);

    return "redirect:/bookings";
}

... also note, you don't perform any validation. You have to, otherwise your app ain't  safe.
@Valid annotation


text:
Q: ggplot Stacked Barplot with Negative Values I've been perusing DOT airline data and am trying to create a stacked bar graph of the year over year (YOY) change in each airline's passengers from a specific airport to all other stations.
I also want to order the x-axis by the total number of people (market.ppd) traveling from the specified airport to each station (e.g. This set's origin airport is PHL, and its top destination is MCO. Next is Miami, LAS, etc.)
The x-axis stays ordered when the YOY data is solely positive or negative but defaults back to alphabetical order once I try to stack the bar with both. Some stations only experience a positive YOY change or a negative YOY change, whereas the example in this post has positive and negative values for each category.
My hunch is ggplot reverts the levels to alphabetical order once it finds that some of the stations don't have corresponding positive/negative values. Is there any way to retain the ordered levels once I append the negative values to the positive for each station?
Plot with only positive values

Plot with both positive and negative values

library(ggplot2)

OD <- data.frame(
      destination = c('MCO', 'MCO', 'MCO', 'MCO', 'MCO', 'MCO', 'MCO', 'Miami', 'Miami', 'Miami', 'Miami', 'Miami', 'Miami', 'LAS', 'LAS', 'LAS', 'LAS', 'Chicago', 'Chicago', 'Chicago', 'Chicago', 'Chicago', 'Chicago', 'Los Angeles', 'Los Angeles', 'Bay Area', 'Bay Area', 'Bay Area', 'Bay Area', 'Bay Area', 'BOS', 'BOS', 'BOS', 'ATL', 'ATL', 'ATL', 'ATL', 'ATL', 'ATL', 'TPA', 'TPA', 'TPA', 'TPA', 'Dallas', 'Dallas', 'Dallas', 'DEN', 'DEN', 'DEN', 'PHX', 'PHX', 'PHX', 'PHX', 'PHX', 'CUN', 'CUN', 'RSW', 'RSW', 'RSW', 'SAN', 'SAN', 'SJU', 'Houston', 'Houston', 'MSY', 'MSP', 'MSP', 'CLT', 'CLT', 'CLT', 'MBJ', 'MBJ', 'PUJ', 'PUJ', 'PUJ'),
      carrier = c('US', 'F9', 'WN', 'AA', 'FL', 'UA', 'DL', 'F9', 'US', 'DL', 'WN', 'UA', 'FL', 'AA', 'US', 'UA', 'NK', 'US', 'NK', 'F9', 'WN', 'UA', 'AA', 'WN', 'VX', 'US', 'DL', 'AA', 'VX', 'UA', 'US', 'B6', 'AA', 'US', 'WN', 'F9', 'DL', 'AA', 'FL', 'US', 'F9', 'WN', 'UA', 'DL', 'WN', 'US', 'US', 'WN', 'DL', 'US', 'WN', 'AA', 'DL', 'UA', 'US', 'F9', 'US', 'WN', 'UA', 'US', 'AA', 'AA', 'DL', 'WN', 'DL', 'F9', 'DL', 'F9', 'US', 'UA', 'AA', 'US', 'AA', 'F9', 'US'),
      market.ppd = c(1242, 1242, 1242, 1242, 1242, 1242, 1242, 1056, 1056, 1056, 1056, 1056, 1056, 645, 645, 645, 645, 641, 641, 641, 641, 641, 641, 526, 526, 498, 498, 498, 498, 498, 492, 492, 492, 482, 482, 482, 482, 482, 482, 478, 478, 478, 478, 399, 399, 399, 333, 333, 333, 298, 298, 298, 298, 298, 243, 243, 232, 232, 232, 213, 213, 205, 198, 198, 173, 163, 163, 160, 160, 160, 152, 152, 147, 147, 147),
      YOY = c(110, 96, 26, 15, -39, -23, -18, 52, 47, 11, -48, -22, -10, 8, -49, -11, -6, 15, 10, 8, 8, -12, -9, 9, -56, 35, 8, 6, -32, -12, 9, 7, 6, 47, 43, 16, 8, 7, -34, 44, 39, 8, -9, 13, 7, -28, 21, 7, 6, 37, 7, 6, -10, -7, 16, 9, 60, -37, -6, 19, -9, 6, 9, -6, -6, 16, -7, 20, 11, -6, 9, -24, 8, -11, -7),
      label.placement = c(55, 158, 219, 239, -20, -50, -71, 26, 75, 105, -24, -59, -75, 4, -25, -55, -63, 8, 20, 30, 38, -6, -17, 4, -28, 17, 39, 46, -16, -38, 4, 12, 19, 23, 68, 98, 110, 118, -17, 22, 64, 87, -5, 6, 17, -14, 10, 24, 31, 18, 40, 47, -5, -14, 8, 20, 30, -19, -40, 9, -5, 3, 4, -3, -3, 8, -4, 10, 26, -3, 5, -12, 4, -6, -15))

OD$destination <- factor(OD$destination, OD$destination)

ggplot() +
geom_bar(data = OD[OD$YOY > 0, ], aes(x = destination, y = YOY, fill = carrier), stat = 'identity') +
geom_text(data = OD[OD$YOY > 0, ], aes(x = destination, y = label.placement, label = carrier), size = 2) +
geom_bar(data = OD[OD$YOY < 0, ], aes(x = destination, y = YOY, fill = carrier), stat = 'identity') +
geom_text(data = OD[OD$YOY < 0, ], aes(x = destination, y = label.placement, label = carrier), size = 2) +
theme(axis.text.x = element_text(size = 10, vjust = .5, angle = 90), legend.position = 'none')

A: You can define an order and then tell ggplot to display the data accordingly:
library(ggplot2)

OD <- data.frame(
  destination = c('MCO', 'MCO', 'MCO', 'MCO', 'MCO', 'MCO', 'MCO', 'Miami', 'Miami', 'Miami', 'Miami', 'Miami', 'Miami', 'LAS', 'LAS', 'LAS', 'LAS', 'Chicago', 'Chicago', 'Chicago', 'Chicago', 'Chicago', 'Chicago', 'Los Angeles', 'Los Angeles', 'Bay Area', 'Bay Area', 'Bay Area', 'Bay Area', 'Bay Area', 'BOS', 'BOS', 'BOS', 'ATL', 'ATL', 'ATL', 'ATL', 'ATL', 'ATL', 'TPA', 'TPA', 'TPA', 'TPA', 'Dallas', 'Dallas', 'Dallas', 'DEN', 'DEN', 'DEN', 'PHX', 'PHX', 'PHX', 'PHX', 'PHX', 'CUN', 'CUN', 'RSW', 'RSW', 'RSW', 'SAN', 'SAN', 'SJU', 'Houston', 'Houston', 'MSY', 'MSP', 'MSP', 'CLT', 'CLT', 'CLT', 'MBJ', 'MBJ', 'PUJ', 'PUJ', 'PUJ'),
  carrier = c('US', 'F9', 'WN', 'AA', 'FL', 'UA', 'DL', 'F9', 'US', 'DL', 'WN', 'UA', 'FL', 'AA', 'US', 'UA', 'NK', 'US', 'NK', 'F9', 'WN', 'UA', 'AA', 'WN', 'VX', 'US', 'DL', 'AA', 'VX', 'UA', 'US', 'B6', 'AA', 'US', 'WN', 'F9', 'DL', 'AA', 'FL', 'US', 'F9', 'WN', 'UA', 'DL', 'WN', 'US', 'US', 'WN', 'DL', 'US', 'WN', 'AA', 'DL', 'UA', 'US', 'F9', 'US', 'WN', 'UA', 'US', 'AA', 'AA', 'DL', 'WN', 'DL', 'F9', 'DL', 'F9', 'US', 'UA', 'AA', 'US', 'AA', 'F9', 'US'),
  market.ppd = c(1242, 1242, 1242, 1242, 1242, 1242, 1242, 1056, 1056, 1056, 1056, 1056, 1056, 645, 645, 645, 645, 641, 641, 641, 641, 641, 641, 526, 526, 498, 498, 498, 498, 498, 492, 492, 492, 482, 482, 482, 482, 482, 482, 478, 478, 478, 478, 399, 399, 399, 333, 333, 333, 298, 298, 298, 298, 298, 243, 243, 232, 232, 232, 213, 213, 205, 198, 198, 173, 163, 163, 160, 160, 160, 152, 152, 147, 147, 147),
  YOY = c(110, 96, 26, 15, -39, -23, -18, 52, 47, 11, -48, -22, -10, 8, -49, -11, -6, 15, 10, 8, 8, -12, -9, 9, -56, 35, 8, 6, -32, -12, 9, 7, 6, 47, 43, 16, 8, 7, -34, 44, 39, 8, -9, 13, 7, -28, 21, 7, 6, 37, 7, 6, -10, -7, 16, 9, 60, -37, -6, 19, -9, 6, 9, -6, -6, 16, -7, 20, 11, -6, 9, -24, 8, -11, -7),
  label.placement = c(55, 158, 219, 239, -20, -50, -71, 26, 75, 105, -24, -59, -75, 4, -25, -55, -63, 8, 20, 30, 38, -6, -17, 4, -28, 17, 39, 46, -16, -38, 4, 12, 19, 23, 68, 98, 110, 118, -17, 22, 64, 87, -5, 6, 17, -14, 10, 24, 31, 18, 40, 47, -5, -14, 8, 20, 30, -19, -40, 9, -5, 3, 4, -3, -3, 8, -4, 10, 26, -3, 5, -12, 4, -6, -15))

OD$destination <- factor(OD$destination, OD$destination)
neworder <- unique(levels(OD$destination))

ggplot() +
  geom_bar(data = OD[OD$YOY > 0, ], aes(x = destination, y = YOY, fill = carrier), stat = 'identity') +
  geom_text(data = OD[OD$YOY > 0, ], aes(x = destination, y = label.placement, label = carrier), size = 2) +
  geom_bar(data = OD[OD$YOY < 0, ], aes(x = destination, y = YOY, fill = carrier), stat = 'identity') +
  geom_text(data = OD[OD$YOY < 0, ], aes(x = destination, y = label.placement, label = carrier), size = 2) +
  theme(axis.text.x = element_text(size = 10, vjust = .5, angle = 90), legend.position = 'none')+
  scale_x_discrete(limits=c(neworder))


text:
Q: Recurrence Relation Quicksort I've been looking into reccurence relations for quicksort, and I can follow how they get to the final recurrence relation, but then they jump to a time order. For example:
T(N) = T(N-1) + T(0)+ Theta(sqrt(N))

Then they jump to the time order of: O(Nsqrt(N))
I don't follow how they got from the recurrence relation to the time order...

A: The recurrence relation is not well-defined. You need a boundary condition. Let's assume that T(1)=1=sqrt(1) and that T(0)=0.
The proof of the fact that T(N)=O(N*sqrt(N)) is very easy:
T(N) = T(N-1) + Theta(sqrt(N)) = T(N-2) + sqrt(N-1) + sqrt(N)
     = ... = sqrt(N) + sqrt(N-1) + ... + sqrt(1)
     <= N * sqrt(N).

The bound <= N*sqrt(N) obviously holds because sqrt(1)<...<sqrt(N-1)<sqrt(N).
Thus T(N)=O(N*sqrt(N)).


text:
Q: Local HTML file not loading CSS file in browser I am trying to run an HTML file from my computer in Google Chrome.
    <!DOCTYPE html>

        <title>Fighting Program</title>
        <link rel=¨stylesheet¨ href="styles.css" type="text/css"></link>
    script src="..\JavaScript\script.js"></script>

Test

And here is my CSS
    body {
        background-image: linear-gradient(red,black);

        margin: 0;
        height: 100vh;

        border-style: solid;
        border-color: red;
    }

I know my CSS works because I put it in a


text:
Q: Reclassifying raster values in Google Earth Engine? I need to reclassify slope raster (val: 0-90) to 9 classes (1-9). I used this code but the output raster cannot be displayed. What did I do wrong?
// Add features
var sumatera = ee.FeatureCollection("users/putraditama/sumatera");

// Add raster
var elev = ee.Image("USGS/SRTMGL1_003")

// Clip elev to Sumatera boundary
var elevsmrt = elev.clip(sumatera);

// Get slope
var slopesmrt = ee.Terrain.slope(elevsmrt);

// Remap values
var slopereclass = slopesmrt
.remap([0-10,11-20,21-30,31-40,41-50,51-60,61-70,71-80,81-90],
       [1,2,3,4,5,6,7,8,9]);

// Display the result.
Map.addLayer(slopesmrt, {min: 0, max :90, palette: ['black', 'white']},'slope');
Map.addLayer(slopereclass, {min: 1, max :9}, 'slopereclass');

A: The accepted solution addresses the very specific case at hand, and while admirably clever (kudos for that), does not answer the question, which is "How to reclass ranges in GEE".
A more general case of reclassification of ranges into user specific classes would be with conditional assignment using where
// Add features.
var feature = ee.FeatureCollection("USDOS/LSIB_SIMPLE/2017")
             .filter(ee.Filter.eq('country_na', 'Switzerland'));

// Add raster.
var elev = ee.Image("USGS/SRTMGL1_003");

// Get slope.
var slopesmrt = ee.Terrain.slope(elev);

// Remap values.
var slopereclass = ee.Image(1)
      .where(slopesmrt.gt(10).and(slopesmrt.lte(20)), 1)
      .where(slopesmrt.gt(20).and(slopesmrt.lte(30)), 2)
      .where(slopesmrt.gt(30).and(slopesmrt.lte(40)), 3)
      .where(slopesmrt.gt(40).and(slopesmrt.lte(50)), 4)
      .where(slopesmrt.gt(50).and(slopesmrt.lte(90)), 5)

// create colors for those classifications
var visparams = {
   "opacity": 1,
    "min": 1,
    "max": 5,
    "palette": ["147218", "7cb815", "f2fe2a", "ffac18", "fe3c19"]
}

Map.addLayer(slopereclass, visparams)

...and so on. Clearly, more to write but now I could specify any class range I want.

A: ee.Image.remap() operates on individual values, not ranges of numbers like your example shows.
Given that you are trying to convert the slope values to a set of bins with equal spacing, you can just divide and set it next highest integer using ee.Image.ceil().
// Add features.
var feature = ee.FeatureCollection("USDOS/LSIB_SIMPLE/2017")
             .filter(ee.Filter.eq('country_na', 'Switzerland'));

// Add raster.
var elev = ee.Image("USGS/SRTMGL1_003");

// Get slope.
var slopesmrt = ee.Terrain.slope(elev);

// Remap values.
var slopereclass = slopesmrt.divide(10).ceil();

// Display the result.
Map.addLayer(slopesmrt.clip(feature), {min: 0, max: 90, palette: ['black', 'white']},'slope');
Map.addLayer(slopereclass.clip(feature), {min: 1, max: 9, palette: ['black', 'red']}, 'slopereclass');


text:
Q: How to block new incoming messages on a Kafka topic? As mentioned in the title, is there a way to block new incoming new messages on a Kafka topic? I would like to still be able to read from it, but I don't want it to receive any new messages anymore.
I'm expecting here that existing behaviours on other Kafka topics remain unaffected.

A: You would need to setup ACL policies on your entire Kafka cluster, then deny produce requests or set quotas to disallow production into the topic from any authenticated and authorized client.
Without authorization (by using PLAINTEXT listeners), you cannot prevent any client from producing into a topic.


text:
Q: highcharter markdown presentation I'm trying to build some Highchart (package HighCharter) in a reveal.js presentation.
Now I'm adapting a spiderweb chart from this page.
this is my code:
 ```{r, echo=FALSE, message=FALSE, results = 'asis', comment = NA}
library("highcharter")
library(magrittr)

gg<- highchart() %>%
  hc_chart(polar = TRUE, type = "line") %>%
  hc_title(text = "Where do you usually buy solar protection products? (%)") %>%
  hc_subtitle(text = "Move the mouse pointer on the spiderweb chart to view the data") %>%
  hc_xAxis(categories = c('Supermarket',
                      'Department Store',
                      'Pharmacy',
                      'Perfumery',
                      'Herbalist',
                      'Internet',
                      'Shop for Personal Care'
  ),
  tickmarkPlacement = 'on',
  lineWidth = 0) %>%
hc_yAxis(gridLineInterpolation = 'polygon',
       lineWidth = 0,
       min = 0) %>%
  hc_series(
    list(
      name = "Male (%)",
      data = c(14.3,
           9.1,
           35.8,
           26.3,
           4.9,
           4.6,
           4.1
  ),
  pointPlacement = 'on', color="#88C425"
  ),
 list(
  name = "Female (%)",
  data = c(17.0,
           7.0,
           40.2,
           28.8,
           18.3,
           2.2,
           3.6
  ),
  pointPlacement = 'on', color="#A8DBA8"
  )
  )

gg$show("inline", include_assets = TRUE)

```

Well,  the code works proprelly in the normal sintax, but then I include it in the RMarkdown sintax the result is an error:
Error in eval(expr, envir, enclos) :
tentativo di applicare una non-funzione
Calls: <Anonymous> ... handle -> withCallingHandlers -> withVisible -> eval -> eval

Could someone help?

A: Okey my friend! This work (In my envoirment).
result here http://jkunst.com/highcharter/presentation/
First of all you must use the next function which instead of print the htmlwidget save it in a html file and then put an iframe html tag calling this html.
knit_print.htmlwidget <- function(x, ..., options = NULL){

  options(pandoc.stack.size = "2048m")

  wdgtclass <- setdiff(class(x), "htmlwidget")[1]
  wdgtrndnm <- paste0(sample(letters, size = 7), collapse = "")
  wdgtfname <- sprintf("wdgt_%s_%s.html", wdgtclass, wdgtrndnm)

  htmlwidgets::saveWidget(x, file = wdgtfname, selfcontained = TRUE, background = "transparent")

  iframetxt <- sprintf("<iframe  frameBorder=\"0\" src=\"%s\" width=\"100%%\"   height=\"600\"></iframe>", wdgtfname)

  knitr::asis_output(iframetxt)
}

Basically implement the  partials solution metioned here https://github.com/ramnathv/slidify/issues/429 and here https://github.com/ramnathv/slidify/issues/414


text:
Q: Java error Consuming WCF Service I'm started to develop a Web Service with WCF and created a WCF Service poject. I let all as it was and imported the service in netbeans as JAX WS service. All seems to be fine.
Service1 test= new Service1();
CompositeType ct=new CompositeType();
ct.setBoolValue(Boolean.TRUE);
ObjectFactory factory=new ObjectFactory();
ct.setStringValue(factory.createString("StringValue"));
CompositeType result= test.getBasicHttpBindingIService1().getDataUsingDataContract(ct);

I can send the request. I can break in Visual studio and see the CompositeType object. But the object is not as it should be:

*

*The bool value is set as expected to true.

*The string value is still null.

*When i manipulate the string value in the WCF Service and give the change object back the string is set correct and i can read it in java.

Why can't i post the CompositeType to java but can consume it?

A: It's hard to tell from just the detail you've provided.
Here is what I suggest:

*

*Enable tracing on the service side, generate tracing logs, and analyze with SvcTraceViewer. To do this, follow the instructions at this MSDN article on using the service trace viewer. Notice what's different between the first and second time.

*Turn on debug exceptions. This is done by turning in includeExceptionDetailInFaults, which you can do by following the instructions here. Notice what's different between the first and second time.

*Use Fiddler to monitor the wire traffic on both the client side and the service side.
Generally, once you do this, you should plenty of more info on what's going funky at the service side and can diagnose the issue pretty quickly. Try it, and please report back! :)

A: I also lost 2 hours in this!
The problem is in java code :)
Instead of this
ct.setStringValue(factory.createString("StringValue"));

use this
ct.setStringValue(factory.createCompositeTypeStringValue("StringValue"));


text:
Q: Black screen for several seconds during startup A colleague of mine tried to build the JavaFXPorts application of mine on his machine. The good thing is: after some minor updates to the forceLinkClasses part in the build.gradle file, it worked.
But...
While we can see one of the the white Default*.png images briefly, we are confronted with a black screen for about 5 seconds.
On the console, he could see the following output (amongst others):
[WARN] java.lang.Class: Class.forName() failed to load 'ch.cnlab.disentis.resource.strings_en'. Use the -forcelinkclasses command line option or add <forceLinkClasses><pattern>ch.cnlab.disentis.resource.strings_en</pattern></forceLinkClasses> to your robovm.xml file to link it in.
[WARN] java.lang.Class: Class.forName() failed to load 'ch.cnlab.disentis.resource.strings_de_CH'. Use the -forcelinkclasses command line option or add <forceLinkClasses><pattern>ch.cnlab.disentis.resource.strings_de_CH</pattern></forceLinkClasses> to your robovm.xml file to link it in.
[WARN] java.lang.Class: Class.forName() failed to load 'ch.cnlab.disentis.resource.strings_de'. Use the -forcelinkclasses command line option or add <forceLinkClasses><pattern>ch.cnlab.disentis.resource.strings_de</pattern></forceLinkClasses> to your robovm.xml file to link it in.
[WARN] java.lang.Class: Class.forName() failed to load 'ch.cnlab.disentis.resource.strings'. Use the -forcelinkclasses command line option or add <forceLinkClasses><pattern>ch.cnlab.disentis.resource.strings</pattern></forceLinkClasses> to your robovm.xml file to link it in.
[WARN] java.lang.Class: Class.forName() failed to load 'com.fasterxml.jackson.databind.ext.Java7SupportImpl'. Use the -forcelinkclasses command line option or add <forceLinkClasses><pattern>com.fasterxml.jackson.databind.ext.Java7SupportImpl</pattern></forceLinkClasses> to your robovm.xml file to link it in.
Nov 4, 2016 11:32:44 AM com.fasterxml.jackson.databind.ext.Java7Support <clinit>
WARNING: Unable to load JDK7 types (annotations, java.nio.file.Path): no Java7 support added
[WARN] java.lang.Class: Class.forName() failed to load 'javax.xml.stream.FactoryFinder$ClassLoaderFinderConcrete'. Use the -forcelinkclasses command line option or add <forceLinkClasses><pattern>javax.xml.stream.FactoryFinder$ClassLoaderFinderConcrete</pattern></forceLinkClasses> to your robovm.xml file to link it in.
[WARN] java.lang.Class: Class.forName() failed to load 'javax.xml.stream.FactoryFinder$ClassLoaderFinderConcrete'. Use the -forcelinkclasses command line option or add <forceLinkClasses><pattern>javax.xml.stream.FactoryFinder$ClassLoaderFinderConcrete</pattern></forceLinkClasses> to your robovm.xml file to link it in.
[WARN] java.lang.Class: Class.forName() failed to load 'javax.xml.stream.FactoryFinder$ClassLoaderFinderConcrete'. Use the -forcelinkclasses command line option or add <forceLinkClasses><pattern>javax.xml.stream.FactoryFinder$ClassLoaderFinderConcrete</pattern></forceLinkClasses> to your robovm.xml file to link it in.
[WARN] java.lang.Class: Class.forName() failed to load 'javax.xml.stream.FactoryFinder$ClassLoaderFinderConcrete'. Use the -forcelinkclasses command line option or add <forceLinkClasses><pattern>javax.xml.stream.FactoryFinder$ClassLoaderFinderConcrete</pattern></forceLinkClasses> to your robovm.xml file to link it in.
[WARN] java.lang.Class: Class.forName() failed to load 'com.sun.javafx.font.t2k.T2KFactory'. Use the -forcelinkclasses command line option or add <forceLinkClasses><pattern>com.sun.javafx.font.t2k.T2KFactory</pattern></forceLinkClasses> to your robovm.xml file to link it in.
[WARN] java.lang.Class: Class.forName() failed to load 'com.sun.javafx.tk.quantum.QuantumMessagesBundle_de_CH'. Use the -forcelinkclasses command line option or add <forceLinkClasses><pattern>com.sun.javafx.tk.quantum.QuantumMessagesBundle_de_CH</pattern></forceLinkClasses> to your robovm.xml file to link it in.
[WARN] java.lang.Class: Class.forName() failed to load 'com.sun.javafx.tk.quantum.QuantumMessagesBundle_de'. Use the -forcelinkclasses command line option or add <forceLinkClasses><pattern>com.sun.javafx.tk.quantum.QuantumMessagesBundle_de</pattern></forceLinkClasses> to your robovm.xml file to link it in.
[WARN] java.lang.Class: Class.forName() failed to load 'com.sun.javafx.tk.quantum.QuantumMessagesBundle'. Use the -forcelinkclasses command line option or add <forceLinkClasses><pattern>com.sun.javafx.tk.quantum.QuantumMessagesBundle</pattern></forceLinkClasses> to your robovm.xml file to link it in.
[WARN] java.lang.Class: Class.forName() failed to load 'com.oracle.jrockit.jfr.FlightRecorder'. Use the -forcelinkclasses command line option or add <forceLinkClasses><pattern>com.oracle.jrockit.jfr.FlightRecorder</pattern></forceLinkClasses> to your robovm.xml file to link it in.
[WARN] java.lang.Class: Class.forName() failed to load 'com.sun.javafx.scene.control.skin.resources.controls_de_CH'. Use the -forcelinkclasses command line option or add <forceLinkClasses><pattern>com.sun.javafx.scene.control.skin.resources.controls_de_CH</pattern></forceLinkClasses> to your robovm.xml file to link it in.
[WARN] java.lang.Class: Class.forName() failed to load 'com.sun.javafx.scene.control.skin.resources.controls_de'. Use the -forcelinkclasses command line option or add <forceLinkClasses><pattern>com.sun.javafx.scene.control.skin.resources.controls_de</pattern></forceLinkClasses> to your robovm.xml file to link it in.
[WARN] java.lang.Class: Class.forName() failed to load 'com.sun.javafx.scene.control.skin.resources.controls'. Use the -forcelinkclasses command line option or add <forceLinkClasses><pattern>com.sun.javafx.scene.control.skin.resources.controls</pattern></forceLinkClasses> to your robovm.xml file to link it in.
setSwapInterval(1)
max rectangle texture cell size = 89
wrap rectangle texture = 2 x 2
ES2ResourceFactory: Prism - createStockShader: AlphaTexture_Color.frag
ES2ResourceFactory: Prism - createStockShader: FillRoundRect_Color.frag
ES2ResourceFactory: Prism - createStockShader: DrawRoundRect_Color.frag
ES2ResourceFactory: Prism - createStockShader: Texture_Color.frag
ES2ResourceFactory: Prism - createStockShader: Solid_TextureRGB.frag
Loading Prism common native library ...
        succeeded.
setSwapInterval(0)
setSwapInterval(1)
setSwapInterval(0)
setSwapInterval(1)
setSwapInterval(0)
setSwapInterval(1)
setSwapInterval(0)

The delay seems to happen after the RoboVM warnings.
Does any one have any idea, what the cause for this might be?
Thanks and regards,
Daniel
PS: I needed to ask this, because he has no account on StackOverflow... So there might be some roundtrip time, if I need to ask him to test again.

A: Typically a black screen during a few seconds implies that there is some heavy load at startup.
Before going any further, make sure the load is strictly necessary, and check if doing it on a background task solves the issue.
If that doesn't help, there are several options to avoid the long black screen:
One, using a JavaFX preloader. Create your preloader class extending from Preloader, and provide a light weight scene (i.e. an image). In your build.gradle script add preloaderClassName = 'full.preloader.class.name'.
When the heavy load ends (this should be done in the init method), the application will be loaded, and you can hide the preloader stage.
You can read about preloaders here and here.
Using Gluon Mobile (Charm 4.0.1), use a light weight Home View that loads fast enough, and start loading on the background those heavy tasks. The user will have to use some navigation button or the Navigation Drawer to switch to the secondary view, but the black screen, if any, will be shorter.
And finally using a Splash View (already included in Charm 4+), it will allow showing an image or some label for a short while, while a task can be executed to load those heavy components. After that, the splash
can be dismissed, and the home view will be loaded.
Try any of these solutions and check if the problem goes away.

A: Thanks to @JoséPereda we found the issue: It was the iPhone used for the test. This is an older phone often used for developing. And obviously, it is in a "near-dead" state.
After we switched to another phone (iPhone 6S of another colleague :-D ) the application behaved like expected: being lightning fast during the test.


text:
Q: Binomial expansion of matrix with negative indices Suppose, I have a matrix $(A-\lambda B)^{-1}$, Where $A$,$B$ are matrices and $\lambda$ is constant.  It could be expanded via the following expression:
$(A(I-\lambda A^{-1}B))^{-1}$ = $(I-\lambda A^{-1}B)^{-1}$$A^{-1}$
So my question is, under what condition,
$(I-\lambda A^{-1}B)^{-1}$ could be approximated as $I+\lambda A^{-1}B  + ...$ ?
Thanks a lot :)


text:
Q: paypal android sdk bad currency error On sandbox I am getting this error when I try to charge with card
11-02 11:19:48.577  24102-24840/com.. E/paypal.sdk﹕ request failure with http statusCode:400,exception:Bad Request
11-02 11:19:48.585  24102-24840/com.. E/paypal.sdk﹕ request failed with server response:{"name":"VALIDATION_ERROR","details":[{"field":"transactions[0].amount.currency","issue":"Value is not supported at this time"}],"message":"Invalid request - see details","information_link":"https://developer.paypal.com/webapps/developer/docs/api/#VALIDATION_ERROR","debug_id":"1b3357f0964d3"}
11-02 11:19:48.587  24102-24102/com.. E/paypal.sdk﹕ pp_service_error_bad_currency

A: I know  it's been awhile since you made this question, but as per the official documentation of PayPal's SDKs, the only currencies that PayPal supports for credit card payments are USD, GBP, CAD, EUR, and JPY.
See the reference links:

*

*PayPal Currencies

*PayPal REST API Country and Currency Support


text:
Q: How to remove a bash command which has been placed as docker? There is a fake docker placed in my system (MacOS Big Sur) which I can't easily remove.
When I type docker --help in my terminal it says:
Options:
 -V, --version                output the version number
-i, --input_dir [dir]        Input directory (defaults to current dir) (default:
"/Users/djsicrip")
-o, --output_dir [dir]       Output directory (defaults to ./doc) (default:
 "/Users/djsicrip/doc")
 -u, --updated_files          Only process files that have been changed
-c, --colour_scheme [style]  Colour scheme to use (see
 https://github.com/isagalaev/highlight.js/tree/master/src/styles)
-I, --ignore_hidden          Ignore hidden files and directories (those starting with .
 or _)
-w, --watch                  Watch on the input directory for file changes
(experimental)
-s, --sidebar [state]        Whether the sidebar should be open or not by default
(default: "yes")
-x, --exclude [pattern]      Paths to exclude (default: false)
-n, --line-numbers           Whether to include line numbers in output
-m, --multi_line_only        Whether to process only multi-line comments
--js <files>                 Additional javascript files to include
--css <files>                Additional CSS files to include
--extras <extras>            Bundled extras to include, see extras dir
-h, --help                   output usage information

When I type in docker --version it says 1.0.0
So question is how I can remove that docker command?

A: It looks like this project, which is also called Docker but completely unrelated to Docker Engine:

A documentation generator built on the foundations of Docco and Docco-Husky.

Probably you can use npm uninstall -g docker to get rid of it.


text:
Q: Breeze.Sharp nullable int , when set to zero on client, is being changed back to null on SaveChanges() I'm using the 0.5.5.0 release of Breeze.Sharp, and one of my models has a Nullable<int>  property.
The first time I save the model using SaveChanges(), this value is null as expected. If, however, I try changing the value to 0 later in the process, the saveBundle passed up the the breeze service still shows the value as null.
Just prior to calling SaveChanges() in the client, I can confirm that the value is 0 and that the client entity is in a modified state, but the value is immediately set back to null after calling SaveChanges().
When reviewing the saveBundle Json being sent to the service, I see my Nullable<int> property in the originalValuesMap set to null, however the property itself is not listed in the entity properties.
In my scenario, I am tracking win32 process history, which initially has a value of null for the process exit code while the process executes, and if it finishes successfully, is updated with 0.
Do I need to do anything special to get the 0 to be passed up to the server and recorded, or is this just a bug in the Breeze.Sharp library?

A: Ok, this was a bug and is fixed in version 0.5.9.0 ( or greater) available now in the GitHub repo as well as via nuget.


text:
Q: How to dynamically add active class on wordpress category pages Am new to wordpress development and I want to add an active class on my category pages. I also need the All Article to have the active class by default on load. Here's my code.

  <?php
    global $wp;
    $catURI = basename(home_url( $wp->request ));
    $activeURI = basename($_SERVER['REQUEST_URI']);
    $categories = get_categories(); ?>
      Blog categories: <a href=" <?php echo site_url(); ?>" class="cat-link <?php if ($activePage == $activeURI) echo 'active'; ?>">All Articles
      <?php foreach($categories as $category) {
        echo $catURI == $activeURI
         ? 'term_id) . '">' . $category->name . ''
         : 'term_id) . '">' . $category->name . '';
      }
  ?>

This however does not add the active class to the All Articles link and adds it to all the other category links when I click on one of them.
Any assistance will be highly appreciated.
This could sound like a repetition, but most of the solutions I've gotten seem not to solve my challenge.

A: With the help of @ChrisHaas, I was able to get a workaround. This is the code that I finally used, and styled it accordingly.
<?php
  wp_list_categories(array(
  'show_option_all' => 'All Articles',
  'class' => 'post-category flex',
  'title_li' => 'Blog categories:'
  ));
?>


text:
Q: Control data type (or precison?) to limit memory usage I couldn't find the answer to my question, so here it is:
I have quite a large table, which I generate in Matlab (for some reasons i use both Matlab and Mathematica, I'd like to use only one of them, but plots look  better in Mathematica and programming is more clear for me in Matlab).
Matlab says that data I have is "121x121x181 double", I save it as *mat file - its size is only 1.4 KB. Then I import it in Mathematica and flatten, because of some wierd extra dimension:
data1 = Flatten[Import["file.mat"],1];
ByteCount[data1];

21200328

So, its over 20 MB already. After that I transform the table a little bit further, to make it appropriate for interpolation:
m = Max[data1];
data2 = Flatten[
Table[{{i1, i2, i3}, data1[[i3, i2, i1]]/m},
{i1, 1, 181}, {i2, 1, 121}, {i3, 1, 121}],
2];
ByteCount[data2]

508804112

Well, it is more than 500MB. Now things are getting slow. Not to say, I can't handle bigger tables. So, can anybody explain, how to work with such big tables safely? Because I really don't need this infinite precision, I believe Mathematica uses each time I do anything.

A: I generate some test data.
SeedRandom[42];
data1 = RandomReal[100., {5, 4, 3}];
ByteCount  @ data1

600

Then I calculate what I think you want.
m = Max @ data1

99.6966

Scale and reorder the data.
data2 = Transpose[data1/m, {3, 2, 1}]

ByteCount @ data2

600

I think data2 would all you need to make further computations in Mathematica, but if you insist on attaching the indices, then the following will do it.
data3 = Flatten[MapIndexed[{#2, #1} &, data2, {-1}], 2]

ByteCount @ data3

12576

Now your way of doing it.
data3 =
  Flatten[
    Table[{{i1, i2, i3}, data1[[i3, i2, i1]]/m}, {i1, 1, 3}, {i2, 1, 4}, {i3, 1, 5}],
    2]
data3 == data4

True

Naturally data3 and data4 are larger than data2, They contain the indices and have a much more complex list structure to accommodate them.


text:
Q: How to fill circle based on a value in CSS

.circle
{
  width: 100px;
  height: 100px;
  border-radius: 50%;
  border: 1px solid;
  }

30

If value is 30, I just want to fill the circle 30% with a color let it be red.
How do i do this using only css?
EDIT to answer @AMIT

.fullCircle
{
  width: 100px;
  height:100px;
  bordeR: 1px solid;
  border-radius: 50%;
  background-color: #f00;
  }

It is 100% filled circle. So I hope you clear now what I mean by 30% filled circle.
If it is possible by CSS, it will be compatible. Why not?
EDIT
A google Image to answer filled
link

A: Use the opacity. It is a value between 0 (=transparent) and 1 (=opaque), so 30% is 0.3.

.circle
{
  width: 100px;
  height: 100px;
  border-radius: 50%;
  border: 1px solid;
  background-color: #ff0000;
  opacity: 0.3;
}

30

EDIT based on your comment, you want 30% of the circle which is 360 degrees, so 360 x 30% = 108. To do so, use a background-image:

*

*Draw a vertical red linear-gradient, meaning with -90 degree. This will fill half of the circle with red.

*Draw a white linear-gradientwith the degree -18 (=108-90). This will cover the part of the red half that exceeds 108 (30%).

.circle
{
  width: 100px;
  height: 100px;
  border-radius: 50%;
  border: 1px solid;
  background-image:
    linear-gradient(18deg, white 50%, transparent 50%),
    linear-gradient(-90deg, red 50%, transparent 50%);
}

30


text:
Q: Loading XML/XSLT in IE using JavaScript I'm building a neat-looking logging system inspired by this article. My general setup is as follows:

*

*I have a Javascript enhanced html-page.

*I have a XML document that I use as a testlog for now.

*I have a XSLT file used for converting the XML to HTML (and prettifying it).

Because I want to dynamically load XML log files in my page I use the following code in the html doc:
function loadXMLDoc(dname) {
    if (window.ActiveXObject) {
        xhttp = new ActiveXObject("Msxml2.XMLHTTP.3.0");
    }
    else {
        xhttp = new XMLHttpRequest();
    }
    xhttp.open("GET", dname, false);
    xhttp.send("");
    return xhttp.responseXML;
}

function displayResult(name) {
    if(name == null)
        xml = loadXMLDoc("testlog.xml");
    else
        xml = loadXMLDoc(name);
    xsl = loadXMLDoc("layout.xsl");
    document.getElementById("logview").innerHTML = "";
    // code for IE
    if (window.ActiveXObject) {
        ex = xml.transformNode(xsl);
        document.getElementById("logview").innerHTML = ex;
    }
        // code for Mozilla, Firefox, Opera, etc.
    else if (document.implementation && document.implementation.createDocument) {
        xsltProcessor = new XSLTProcessor();
        xsltProcessor.importStylesheet(xsl);
        resultDocument = xsltProcessor.transformToFragment(xml, document);
        document.getElementById("logview").appendChild(resultDocument);
}

What it does: displayResult() is called when the user has selected a local file to load and is passed the name of the local file. The script will then try to load the XML file and the XSL file from the disc and transform the XML to HTML before it replaces the contents of a DIV by this new HTML.
My XML looks as follows:
<?xml version="1.0"?>
<RunTimeLog>
  <LogHeader>
    <StartDate>02-09-2013</StartDate>
    <StartTime>09:52</StartTime>
    <Platform>Windows 8</Platform>
    <MemoryTotal>1,048,576 kB</MemoryTotal>
  </LogHeader>
  <LogEvents>

    <LogEvent id="1">
      <Type>Warning</Type>
      <TimeIndex>00:01:34</TimeIndex>
      <File>application.cc</File>
      <Function>SomeFunction()</Function>
      <LineNumber>314</LineNumber>
      <Message>This is just a randum warning, nothing to worry about!</Message>
    </LogEvent>
    <LogEvent id="2">
      <Type>Debug</Type>
      <TimeIndex>00:01:34</TimeIndex>
      <File>application.cc</File>
      <Function>SomeFunction()</Function>
      <LineNumber>314</LineNumber>
      <Message>This is just a randum warning, nothing to worry about!</Message>
    </LogEvent>

  </LogEvents>
</RunTimeLog>

And my XSLT has the following structure:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">

      Run info:

    <xsl:apply-templates select="RunTimeLog/LogHeader"/>

      Log:

                    #
                    Time
                    File
                    Function
                    Line

                <xsl:apply-templates select="RunTimeLog/LogEvents"/>

  </xsl:template>

Now, the problem I'm having is the following: this all works nicely in Firefox, which uses the XMLHttpRequest() to load the files. But in IE ActiveX is used and the script errors on the line
  ex = xml.transformNode(xsl);

with the error
  SCRIPT16389: The stylesheet does not contain a document element.  The stylesheet may be empty, or it may not be a well-formed XML document.

I have tried multiple solutions given in other threads and forums: changing MIME type, using different root nodes, even replacing the XML and XSLT with different documents which work a 100% sure. Also, if I just use the XML and XSLT using an href in IE, it displays withouth a problem. This makes me belvieve the problem is in the loading functionality of the ActiveXObject. Is there someone here who can shed a light on what the problem is here?
Thanks in advance,
Yuri


text:
Q: 'make distcheck' target and the info/dir file I've added a new Info manual to my project, and added the requisite Makefile.am incantations:
info_TEXINFOS = manual.texi

Now when I run make distcheck, I get an error when verifying that make uninstall successfully uninstalls all files, because the $(infodir)/dir file isn't being removed correctly.
ERROR: files left after uninstall:
./share/info/dir
make[1]: *** [distuninstallcheck] Error 1

I searched the Internet, the Automake and Texinfo manuals for a solution, but came up blank. What is the idiomatic way to correct this and get make distcheck working again?

A: distuninstallcheck does not (or should not) fail when there is only ONE file left after uninstall, precisely because of the dir file.  It should fail only when there are more than one file left.
Did you edit the output?  If you didn't, it's an Automake bug you should report.  If you did, you need not worry about this dir file, and just fix the problem with the other files that are listed.
The fact that Automake unconditionally ignores one file can hide a bug when you are not using TEXINFO manuals.  This bug would then surface when you add a manual.  It's unfortunate.


text:
Q: Completing the Square No, it's not the Quadratic, algebraic sort that we're talking about here....Instead, consider this:
Imagine a 6 x 6 grid of 36 equal minisquares, or tiles. A "shape" consists of interconnected adjacent tiles on this grid. [Adjacent tiles must share an edge, not merely a vertex.]
Prove the number of discrete combinations of 4 congruent shapes (9 tiles each) that will complete the grid.
One obvious combination is 4 congruent "sub-squares" of 9 tiles each. But there are several other valid shapes which one can find graphically by experiment. Which method(s) of proof is best used to determine the precise number? How would this proof be constructed? Is this problem and its proof methodology generalizable to completing similar grids, matrices etc.?
Look forward to hearing your ideas on this,
Scott

A: You can find about 30 examples at Mike Reid's Rectifiable polyomino page. It would appear that for the 6x6 square there are two types of 9 cell tilers:

*

*Take the center edge of a 3X6 rectangle along with a path from one end of that edge to the boundary and the 180- degree rotation starting from the other end

and

*

*Take a path from the center of a 6x6 square and rotate it by 90,180 and 270 degrees.

So a method to do all this (which I have not done) would have these steps: Find all tiles of these two types. (One needs a path which does not intersect its 1 or 3 partner paths, there can only be so many so go about it systematically). Then show that a tiling must decompose into 2 3x6 rectangles or else have a 4-fold central rotational symmetry.
Most work I know starts with a tile and asks what rectangles it tiles. I would consider it pretty interesting to prove or disprove that any partition of a square into 4 congruent pieces is of one of these two types. Maybe that is already known one way or the other. I am not aware that anyone has looked systematically at dividing a checkerboard into 4 congruent pieces. Here is a decomposition of a 14x14 square into 16 7-cell tiles. It does have a 4-fold rotational symmetry.
further comments This is a fascinating field. Search the literature and you will find some contributions by well known names but you will also find that some of the best results come from "amateurs". I use the term only in the sense of someone who does it exclusively for the love of the subject. An easier problem than yours is: How many ways to split a $k$ by $2k$ rectangle into two congruent pieces? You would have to solve that to solve your problem. Already that is a difficult lattice path problem. For  particular small  $k$ you could do it but in general asymptotics might be the best one could expect.

A: To underscore my comments posted under another answer, here is a start of an enumeration which would be pretty messy when completed.
I will cover the case of 4-fold rotational symmetry.  I consider the lower left 3x3 squares which I label with coordinate pairs (1,1) through (3,3).  (3,3) is a central square which by symetry I assume to be part of any shape I count.  Since I am interested in connected shapes, one of (3,2) or (2,3) (squares below and/or to the left) must belong to the shape as well.  Suppose both are: then there are 64 cases to consider, where each of the remaining 6 squares of the lower left 3x3 square is part of the included shape or not.
Suppose square (2,2) is not part of the shape.  Then one of its three equivalent (under rotation) squares must be.  Some thought will show that it is not the (5,5) square.  Say it is the (5,2) square, then at least two more squares will be needed to connect it to the
squares in the lower left corner.  so at most 3 more squares are allowed in our shape from
the lower left corner.
I could go on using words; it would be easier to list the allowed shapes that I discovered by trial and error, and submit that as a list.  It is possible that an alternate categorization (counting those where (1,1) and/or (2,2) are part of the shape, for example) might lead to a more concise counting, but most people who would need the count would probably spend the time trying to derive it for themselves rather than read your derivation.  Again, I do not see a solution to this problem that is quick and easy with few cases to consider.
Gerhard "Ask Me About System Design" Paseman, 2011.05.21


text:
Q: Specifying variable size when passing one to the cursor in Oracle If I define the cursor that accepts 2 parameters like this:
CURSOR cur_det (var1 IN varchar2,var2 IN varchar2)  IS

Is it possible to specify their size? thanks

A: No, you cannot specify varchar2(100) or something similar. The varchar being passed is not constrained.

You can use the %Type to anchor the parameter to a database column, i.e., my_table.a_column%Type. But I don't think that actually constrains the parameter.


text:
Q: How do I write a function's output to a file using iofstream? I'm working on an assignment that:

*

*Prompts user for a year input no less than 1582.

*Produces a file (cal.dat) containing the calendar produced by the code I write.
I wrote the code that takes input, calculates whether or not it's a leap year, and then gives back the calendar for that year with cout.
When I try to output the calendar to the file Xcode gives me this error in compiling:
Invalid operands to binary expression ('ofstream' (aka 'basic_ofstream<char>') and 'void')

A part of the code is below:
#include <iostream>
#include <iomanip>
#include <fstream>

using namespace std;

void PrintMonth(int year, bool leap);
ofstream calendar("cal.dat");

int main()
{
    // Setting up the parameters for the PrintMonth function
    int year=0;
    bool leap=false;

    // Input for the year
    cout << "Enter a 4 digit year: ";
    cin >> year;

    // Loop for an incorrect entry
    while (year<1582)
        {
        cout << "Year too low, please re-enter: ";
        cin >> year;
        }

    // Calculate if the input year is a leap year or not
    if ((year%4==0 && year%100!=0) || year%400==0)
        leap=true;

    // Output the year and the calendar for the year requested
    calendar << setw(15) << year << endl << endl;
    calendar << PrintMonth(year, leap);

    return 0;
}

A: you write calendar << PrintMonth(year, leap), which would mean that you pass the return value of PrintMonth into calendar.
However, according to the signature void PrintMonth(int year, bool leap), this function does not return a value which could be printed out.
Did you mean PrintMonth(year,leap); instead of calendar << PrintMonth(year,leap)?
So you could copy your PrintMonth-function, change the signature to void PrintMonth(int year, bool leap, std::ostream& out), adapt its implementation to write to out instead of cout, and call PrintMonth(year,leap, calendar); instead of writing calendar << PrintMonth(year,leap).


text:
Q: Page-Break-Before: Right not working in Edge 84 browser I am trying to use page-break-after: right property in my HTML. It is working fine with IE but not working in Edge 84 browser. It is not adding blank page, to make second div to be printed in right side of pane.

Should print on Page1

Should print on Page3


text:
Q: reflection - Get enum that is inside a class I have a class with a enum in it and a constructor, that is using it as parameter.
public class Example {
  public enum ExampleEnum {WORK,IDLE};
  public Example(ExampleEnum e, String s){...}
  // Class body
}

But if I get enum value from it and pass it as argument to contstructor, I get java.lang.NoSuchMethodException
This is the code that I am using:
Object enumVal = Class.forName("Example$ExampleEnum").getField("WORK").get(null);
Object instance = Class.forName("Example").getConstructor(
        enumVal.getClass(),
        String.class).newInstance(
            enumVal,
            "test"
);

(The class exists)


text:
Q: Text pushed down after inserting images - need to vertically align text JS FIDDLE: http://jsfiddle.net/nick55555/7tfca64y/
I probably have a situation very easy to solve but cant work out how to do it. I have a simple div with some text inside, which was vertically in the centre, but when I inserted an image into the same div, the text is now lower than it was originally. How can I make the text the same vertical height as it was before i inserted the images? the images are vertically aligned perfectly but the text isn't...

  #header_Bi {
    height: 39px;
    width: 748px;
    margin: 0;
    float: left;
    border-left: 1px solid #191919;
    border-right: 1px solid #191919;
    border-bottom: 1px solid #191919;
    font-family: arial, verdana, helvetica, sans-serif;
    font-size: 15px;
    color: #fff;
    font-weight: 100;
    text-transform: uppercase;
    background: #2c2c2c;
    text-align: center;
  }
  #header_Bi1 {
    height: auto;
    width: auto;
    margin-top: 10px;
  }

    SALES & ADVICE EMAIL HERE

A: If you want to align the text in the middle with the images, add #header_Bi1 img { vertical-align:middle;} to your css


text:
Q: MySQL User Privileges - Restrict Users to some tables I have created a database with several tables, such as user, booking etc.
I have allocated privileges using the User tab within phpmyAdmin, wherein, Users are permitted View and Add privileges, Administrators have View, Add and Amend privileges and Managers have ALL privileges including Delete.
Using the MySQL database, is it possible to do some restrictions as below:
a) Restrict the User to View and Add to only certain tables.
b) Allow the User to view records solely for themselves and not those of any another user.
If so How?

A: You can give privileges to some users to some tables using mysql GRANT as below
GRANT SELECT, INSERT, UPDATE ON db.booking TO 'someuser'@'somehost';

For all privileges use ALL instead of SELECT, UPDATE etc.
GRANT ALL ON db.booking TO 'someuser'@'somehost';

For documentation please go through mysql GRANT


text:
Q: Изменение содержимого текстового файла Есть txt файлы. К примеру, путь одного из них C:\Users\user\Desktop\1.txt,
содержимое txt файла: 2014-08-23 07:31:14 + текст (не важно какой).
Мне надо прибавить к этой дате + 14 дней и результат (датой) в textbox или в listbox.
Так как файлов много и следовательно дат, надо упорядочить по времени.
Как это сделать? Спасибо.


text:
Q: React-router: How can props be passed down to child components? I'm not sure if I'm approaching this in the right way at all, so a bit of background first:
Let's say I have countries and cities in each country that I'm going to fetch from two stores, CountryStore and CityStore in the topmost route (view1). I'm trying to set up react-router so that I have nested routes like this:
<Route name="app" path="/" handler={App}>
   <DefaultRoute name="view2" handler={View2}/>
   <Route name="view1" path='country/:countryId'  handler={View1}>
        <DefaultRoute name="view3" handler={View3}/>
        <Route name="view4" path='city/:cityId'  handler={View4}/>
        < More nested routes />
   </Route>
</Route>

So from what I've been reading up on, I've understood that I should have state in my top view1 and pass everything down as props to view3, view4 and any others.
So here's a fiddle where I've got things working by passing down props with the route handler in view1, and from links I'm passing params based on which each view can filter out what they need. But I'm wondering if there's a smarter way of doing this by passing down the props I'm going to need with each link somehow. Meaning that if in my city list I'm already iterating through all the city objects, can I with the city link pass down the current city as props somehow, so the city view wouldn't need to filter out its city each time?
I hope the question is clear enough, I'm thankful for any advice!

A: Your question is a little confusing (maybe because of the very generic variable/view names), but I think I see what you're getting it.
I think there are two parts of the answer: can you do this, and should you do this.
I believe it's definitely possible that you can do what you're suggesting. If you look at the params in View1, you can see that when the url is country/1 the params are { countryId: "1" }, but when the url is country/1/city/2, the params are { countryId: "1", cityId: "2" }. So, based on this, View1 could see the cityId param and decide to pass an additional property to its child, for example:
// In View1
var props = {
  country: testCountry
}

if (this.props.params.cityId) {
  props.city = (get the city object here);
}

return (
  <div>View 1 wrapper: countryId {countryId}
    <RouteHandler {...this.props} {...props}/>
  </div>
);

However, I'm not really sure that you should. This is breaking the encapsulation provided by React Router; you're coupling two views by giving View1 direct knowledge about how one of its children, View4, works.
If you're really concerned about the performance hit of iterating over the cities more than once, it may be worthwhile to provide an ID-indexable data structure that View4 can use to look up the city directly (e.g. var city = this.props.whatever[this.props.params.cityId]).
Taking a step back, I personally thing the "get all the state and pass it down as props" that Bill describes in the answer you linked to might break down a bit in applications that rely on routing. I consider each view passed to the router via <Route handler={...} /> to be a view-controller—a miniature standalone app, as it were. Doing so, as Bill mentions, gives a better encapsulation of the domain that the route/route handler is dealing with, and I don't think that it makes debugging more difficult, as the routes declare exactly which view is acting as the top-level view-controller for any given URL (so if some data looks wrong you just go immediately to the view-controller for the current route).
If you use a nice composition strategy to connect your route handlers to flux stores (see the code at this Fluxxor issue as an example), it makes it even clearer how the data gets from the stores into the components.


text:
Q: full screen editor in Eclipse Juno There are a few plugins that allow full screen editing in Eclipse but I can't find any that I can install on Juno. Does anyone know whether such a thing exists?
When I search for "full screen" in the marketplace, for example, several examples show up but none of them are installable. (Why the marketplace shows plugins that can't be installed, I've no idea.)
Thanks.

A: Check this plugin:
http://marketplace.eclipse.org/content/fullscreen-mode
it works on eclipse juno. After installing choose Window Menu ->full screen to go fullscreen