问:
Is it possible to add and commit files outside of a git repository?
We have text files spreaded in all corner of the system, and we were planing to add all modifications made in these files to a git repository.

Every time a modification is made to these files, it is made by a script. So, we were planing to add new commands to that script to add the files to a git repository. But, these modifications are concurrent.

We could build a path to each file representing the original location from their original paths.

Is there possible to add these files to a git repository concurrently ?

Like an atomic operation joining add+commit and pointing to both: the external file path and its repository correspondent path. Something like:

git --user="Script1

答:
The answer is both no and yes.1

If you plan to use only Git "porcelain" commands, it's pretty clearly "no", as these work with the concept of a (single) work-tree that holds all the normal-format files, plus one index (holding the current state of that work-tree and building the next commit).  There is one HEAD file holding the notion of the current branch name.  You need at least two separate porcelain commands, in this sequence:

```<code>git add <path>
git commit <arguments>
</code>```

to update the (single) index from the (single) work-tree version of the file in <path>, then make a commit using that index and the current HEAD.  Git will do some locking of the things it updates whle making the commit, but you need the add-then-commit sequence to appear atomic, so you need to pile your own locking atop these.

(This remains true even if you use --work-tree and/or --git-dir arguments to redirect various parts of various steps: the shared index has to remain stable between the "add" and "commit" steps.)

On the other hand, if you are willing to step outside the comfort of pure porcelain, you can get the commit itself done as an atomic entity—but you're still looking at a race of sorts, so you need to resolve that before the answer really changes from "no" to "yes".  To see how this works we must take the git add and git commit steps apart.

First, git add is essentially git update-index.  We can create a new, temporary, private index and populate it from some specific commit we choose:

```<code>commit_id=...insert some magic here, see below...
export GIT_INDEX_FILE=$(mktemp) # remember to clean it up later too
git read-tree $commit_id
</code>```

Now we can replace any given file within that index using git update-index (or in fact, the more familiar and comfortable git add: the environment variable works there too).  Because this is our own private index, it is insulated from all other processes that may be modifying any other index.

Now we can do the steps that git commit does:

```<code>tree_id=$(git write-tree)
</code>```

This turns the index—which is now our temporary index—into a new top level tree, with sub-trees for any sub-directories, all based on what we read into the index earlier (with git read-tree) and updated (with git update-index or git add).  This top level tree, and any necessary sub-trees that were not already in the repository, is now stored in the repository.  The new object is safe from automatic git gc for the configured expiration time (default 14 days), so this is how long we have to finish our commit.  The command prints the new tree's ID to its standard output, which we capture in the $tree_id variable.

Next, we need to write a commit object, referring to the tree we just made, with an appropriate parent hash.  The correct parent hash is obviously $commit_id.  We must construct a commit message and then run:

```<code>new=$(git commit-tree -p $commit_id $tree_id < message_file)
</code>```

or similar.  This writes the commit object into the repository and, just like git write-tree, prints the new object's ID, which we capture into $new.  (Note that this step uses author and committer name and email, which you can supply as -c user.name=... and -c user.email=... arguments.)

Last, and most important, we're ready to record this new object somewhere.  This is where we must resolve our race (each of the object-writing steps did its own locking to make sure that that part was appropriately atomic).

I assume you would like to store these under some branch name(s), and that these branch names may be both read and updated by other processes.  (If they are read-only, never updated by anything else, we are now home free.)  We have an atomic update operation, in the form of git update-ref:

```<code>git update-ref [-m <reason>] <refname> <newvalue> <oldvalue>
</code>```

The optional -m <reason> part is stored in the reflog, if there is a reflog for this reference.  (This step also uses user.name and user.email, so supply them here if desired.)  The refname part is the full name of the reference, e.g., refs/heads/branch for branch branch.  The newvalue part is the hash ID we want to store, and the oldvalue part—which we will supply to check for races—is the value we expect that branch name to store right now.

Now, assuming we are racing some other process, there are two possible cases:

We won the race: the tree we read, back at the start, is the tree that goes with the commit that's currently at the tip of the branch.  Our commit is therefore ready to be added to the branch, in a straightforward linear fashion.

or:

We lost the race: the tree we read, back at the start, is valid, but the branch name now points to a newer commit.  Our commit is therefore worthless, or needs to be put on a side branch, or something.  We could start over and do the whole thing over again, if our commit is truly worthless: maybe this time we will win the race.

What to do about the "lost the race" case is up to you.  But now we see where the "magic" comes from: the commit ID we want, when we start this whole process, is the current commit hash associated with the reference.  So the "magic" is just:

```<code>commit_id=$(git rev-parse $refname)
</code>```

which reads the current value of the reference (if it's a branch name, we may assume that the type of the underlying object is commit).

Since the update-ref step has its own atomicity (enforced via locking), that's where we get our atomicity.  The question of what to do on failures, though, is the hard part.  Remember also to consider, and do something about, failures at each intermediate step, e.g., if git rev-parse fails, or any of git read-tree or git write-tree or git commit-tree fail, as well.

1Go not to the Elves for counsel, for they will say both no and yes.

Body:
The answer is both no and yes.1

If you plan to use only Git "porcelain" commands, it's pretty clearly "no", as these work with the concept of a (single) work-tree that holds all the normal-format files, plus one index (holding the current state of that work-tree and building the next commit).  There is one HEAD file holding the notion of the current branch name.  You need at least two separate porcelain commands, in this sequence:

git add <path>
git commit <arguments>

to update the (single) index from the (single) work-tree version of the file in <path>, then make a commit using that index and the current HEAD.  Git will do some locking of the things it updates whle making the commit, but you need the add-then-commit sequence to appear atomic, so you need to pile your own locking atop these.

(This remains true even if you use --work-tree and/or --git-dir arguments to redirect various parts of various steps: the shared index has to remain stable between the "add" and "commit" steps.)

On the other hand, if you are willing to step outside the comfort of pure porcelain, you can get the commit itself done as an atomic entity—but you're still looking at a race of sorts, so you need to resolve that before the answer really changes from "no" to "yes".  To see how this works we must take the git add and git commit steps apart.

First, git add is essentially git update-index.  We can create a new, temporary, private index and populate it from some specific commit we choose:

commit_id=...insert some magic here, see below...
export GIT_INDEX_FILE=$(mktemp) # remember to clean it up later too
git read-tree $commit_id

Now we can replace any given file within that index using git update-index (or in fact, the more familiar and comfortable git add: the environment variable works there too).  Because this is our own private index, it is insulated from all other processes that may be modifying any other index.

Now we can do the steps that git commit does:

tree_id=$(git write-tree)

This turns the index—which is now our temporary index—into a new top level tree, with sub-trees for any sub-directories, all based on what we read into the index earlier (with git read-tree) and updated (with git update-index or git add).  This top level tree, and any necessary sub-trees that were not already in the repository, is now stored in the repository.  The new object is safe from automatic git gc for the configured expiration time (default 14 days), so this is how long we have to finish our commit.  The command prints the new tree's ID to its standard output, which we capture in the $tree_id variable.

Next, we need to write a commit object, referring to the tree we just made, with an appropriate parent hash.  The correct parent hash is obviously $commit_id.  We must construct a commit message and then run:

new=$(git commit-tree -p $commit_id $tree_id < message_file)

or similar.  This writes the commit object into the repository and, just like git write-tree, prints the new object's ID, which we capture into $new.  (Note that this step uses author and committer name and email, which you can supply as -c user.name=... and -c user.email=... arguments.)

Last, and most important, we're ready to record this new object somewhere.  This is where we must resolve our race (each of the object-writing steps did its own locking to make sure that that part was appropriately atomic).

I assume you would like to store these under some branch name(s), and that these branch names may be both read and updated by other processes.  (If they are read-only, never updated by anything else, we are now home free.)  We have an atomic update operation, in the form of git update-ref:

git update-ref [-m <reason>] <refname> <newvalue> <oldvalue>

The optional -m <reason> part is stored in the reflog, if there is a reflog for this reference.  (This step also uses user.name and user.email, so supply them here if desired.)  The refname part is the full name of the reference, e.g., refs/heads/branch for branch branch.  The newvalue part is the hash ID we want to store, and the oldvalue part—which we will supply to check for races—is the value we expect that branch name to store right now.

Now, assuming we are racing some other process, there are two possible cases:

We won the race: the tree we read, back at the start, is the tree that goes with the commit that's currently at the tip of the branch.  Our commit is therefore ready to be added to the branch, in a straightforward linear fashion.

or:

We lost the race: the tree we read, back at the start, is valid, but the branch name now points to a newer commit.  Our commit is therefore worthless, or needs to be put on a side branch, or something.  We could start over and do the whole thing over again, if our commit is truly worthless: maybe this time we will win the race.

What to do about the "lost the race" case is up to you.  But now we see where the "magic" comes from: the commit ID we want, when we start this whole process, is the current commit hash associated with the reference.  So the "magic" is just:

commit_id=$(git rev-parse $refname)

which reads the current value of the reference (if it's a branch name, we may assume that the type of the underlying object is commit).

Since the update-ref step has its own atomicity (enforced via locking), that's where we get our atomicity.  The question of what to do on failures, though, is the hard part.  Remember also to consider, and do something about, failures at each intermediate step, e.g., if git rev-parse fails, or any of git read-tree or git write-tree or git commit-tree fail, as well.

1Go not to the Elves for counsel, for they will say both no and yes.


来源: stackexchange

问:
How can you print out a tree in a nicely formatted way?
What is the easiest way to print out a tree in it's tree-structure?  Such as...

```<code>                  some root
              /     |         \
          child1   child2     child 3
           /
      anotherchild               / \
                             yup     another
</code>```

Even formatting it by hand is hard.  How can you make a program print a tree this way?

答:
The following answer is in java, but it is so simple that it can easily be transcribed to other languages:

```<code>public interface Function1<R, T1>
{
    R invoke( T1 argument1 );
}

public interface Procedure1<T1>
{
    void invoke( T1 argument1 );
}

public static <T> void dump( T node, Function1<List<T>,T> breeder,
       Function1<String,T> stringizer, Procedure1<String> emitter )
{
    emitter.invoke( stringizer.invoke( node ) );
    dumpRecursive( node, "", breeder, stringizer, emitter );
}

private static final String[][] PREFIXES = { { " ├─ ", " │  " }, { " └─ ", "    " } };

private static <T> void dumpRecursive( T node, String parentPrefix,
        Function1<List<T>,T> breeder, Function1<String,T> stringizer,
        Procedure1<String> emitter )
{
    for( Iterator<T> iterator = breeder.invoke( node ).iterator(); iterator.hasNext(); )
    {
        T childNode = iterator.next();
        String[] prefixes = PREFIXES[iterator.hasNext()? 0 : 1];
        emitter.invoke( parentPrefix + prefixes[0] + stringizer.invoke( childNode ) );
        dumpRecursive( childNode, parentPrefix + prefixes[1], breeder, stringizer, emitter );
    }
}
</code>```

It produces the following output:

```<code>Automobile
 ├─ Passenger Vehicle
 │   ├─ Light Passenger Vehicle
 │   │   ├─ Two Wheeled
 │   │   │   ├─ Moped
 │   │   │   ├─ Scooter
 │   │   │   └─ Motorcycle
 │   │   ├─ Three Wheeled
 │   │   └─ Four Wheeled
 │   │       ├─ Car
 │   │       ├─ Station Wagon
 │   │       ├─ Pick-up Truck
 │   │       └─ Sports Utility Vehicle
 │   └─ Heavy Passenger Vehicle
 │       ├─ Bus
 │       │   ├─ Single-Deck Bus
 │       │   │   ├─ Mini Bus
 │       │   │   └─ Big Bus
 │       │   └─ Double-Deck Bus
 │       └─ Coach
 │           ├─ Deluxe
 │           └─ Air-Conditioned
 └─ Goods Vehicle
     ├─ Light Goods Vehicle
     │   ├─ Delivery Van
     │   ├─ Light Truck
     │   └─ Tempo
     │       ├─ Three Wheeler Tempo
     │       └─ Four Wheeler Tempo
     └─ Heavy Goods Vehicle
         ├─ Truck
         └─ Tractor Trailer
</code>```

...if you invoke it using the following sample program:

```<code>final class Scratch
{
    static class Node
    {
        String name;
        List<Node> children;

        Node( String name, Node... children )
        {
            this.name = name;
            this.children = Arrays.asList( children );
        }
    }

    public static void main( String[] args )
    {
        Node tree = new Node( "Automobile",
                new Node( "Passenger Vehicle",
                        new Node( "Light Passenger Vehicle",
                                new Node( "Two Wheeled",
                                        new Node( "Moped" ),
                                        new Node( "Scooter" ),
                                        new Node( "Motorcycle" ) ),
                                new Node( "Three Wheeled" ),
                                new Node( "Four Wheeled",
                                        new Node( "Car" ),
                                        new Node( "Station Wagon" ),
                                        new Node( "Pick-up Truck" ),
                                        new Node( "Sports Utility Vehicle" ) ) ),
                        new Node( "Heavy Passenger Vehicle",
                                new Node( "Bus",
                                        new Node( "Single-Deck Bus",
                                                new Node( "Mini Bus" ),
                                                new Node( "Big Bus" ) ),
                                        new Node( "Double-Deck Bus" ) ),
                                new Node( "Coach",
                                        new Node( "Deluxe" ),
                                        new Node( "Air-Conditioned" ) ) ) ),
                new Node( "Goods Vehicle",
                        new Node( "Light Goods Vehicle",
                                new Node( "Delivery Van" ),
                                new Node( "Light Truck" ),
                                new Node( "Tempo",
                                        new Node( "Three Wheeler Tempo" ),
                                        new Node( "Four Wheeler Tempo" ) ) ),
                        new Node( "Heavy Goods Vehicle",
                                new Node( "Truck" ),
                                new Node( "Tractor Trailer" ) ) ) );
        dump( tree, n -> n.children, n -> n.name, s -> System.out.println( s ) );
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
What is the easiest way to print out a tree in it's tree-structure?  Such as...

                  some root
              /     |         \
          child1   child2     child 3
           /
      anotherchild               / \
                             yup     another

Even formatting it by hand is hard.  How can you make a program print a tree this way?

Body:
The following answer is in java, but it is so simple that it can easily be transcribed to other languages:

public interface Function1<R, T1>
{
    R invoke( T1 argument1 );
}

public interface Procedure1<T1>
{
    void invoke( T1 argument1 );
}

public static <T> void dump( T node, Function1<List<T>,T> breeder,
       Function1<String,T> stringizer, Procedure1<String> emitter )
{
    emitter.invoke( stringizer.invoke( node ) );
    dumpRecursive( node, "", breeder, stringizer, emitter );
}

private static final String[][] PREFIXES = { { " ├─ ", " │  " }, { " └─ ", "    " } };

private static <T> void dumpRecursive( T node, String parentPrefix,
        Function1<List<T>,T> breeder, Function1<String,T> stringizer,
        Procedure1<String> emitter )
{
    for( Iterator<T> iterator = breeder.invoke( node ).iterator(); iterator.hasNext(); )
    {
        T childNode = iterator.next();
        String[] prefixes = PREFIXES[iterator.hasNext()? 0 : 1];
        emitter.invoke( parentPrefix + prefixes[0] + stringizer.invoke( childNode ) );
        dumpRecursive( childNode, parentPrefix + prefixes[1], breeder, stringizer, emitter );
    }
}

It produces the following output:

Automobile
 ├─ Passenger Vehicle
 │   ├─ Light Passenger Vehicle
 │   │   ├─ Two Wheeled
 │   │   │   ├─ Moped
 │   │   │   ├─ Scooter
 │   │   │   └─ Motorcycle
 │   │   ├─ Three Wheeled
 │   │   └─ Four Wheeled
 │   │       ├─ Car
 │   │       ├─ Station Wagon
 │   │       ├─ Pick-up Truck
 │   │       └─ Sports Utility Vehicle
 │   └─ Heavy Passenger Vehicle
 │       ├─ Bus
 │       │   ├─ Single-Deck Bus
 │       │   │   ├─ Mini Bus
 │       │   │   └─ Big Bus
 │       │   └─ Double-Deck Bus
 │       └─ Coach
 │           ├─ Deluxe
 │           └─ Air-Conditioned
 └─ Goods Vehicle
     ├─ Light Goods Vehicle
     │   ├─ Delivery Van
     │   ├─ Light Truck
     │   └─ Tempo
     │       ├─ Three Wheeler Tempo
     │       └─ Four Wheeler Tempo
     └─ Heavy Goods Vehicle
         ├─ Truck
         └─ Tractor Trailer

...if you invoke it using the following sample program:

final class Scratch
{
    static class Node
    {
        String name;
        List<Node> children;

        Node( String name, Node... children )
        {
            this.name = name;
            this.children = Arrays.asList( children );
        }
    }

    public static void main( String[] args )
    {
        Node tree = new Node( "Automobile",
                new Node( "Passenger Vehicle",
                        new Node( "Light Passenger Vehicle",
                                new Node( "Two Wheeled",
                                        new Node( "Moped" ),
                                        new Node( "Scooter" ),
                                        new Node( "Motorcycle" ) ),
                                new Node( "Three Wheeled" ),
                                new Node( "Four Wheeled",
                                        new Node( "Car" ),
                                        new Node( "Station Wagon" ),
                                        new Node( "Pick-up Truck" ),
                                        new Node( "Sports Utility Vehicle" ) ) ),
                        new Node( "Heavy Passenger Vehicle",
                                new Node( "Bus",
                                        new Node( "Single-Deck Bus",
                                                new Node( "Mini Bus" ),
                                                new Node( "Big Bus" ) ),
                                        new Node( "Double-Deck Bus" ) ),
                                new Node( "Coach",
                                        new Node( "Deluxe" ),
                                        new Node( "Air-Conditioned" ) ) ) ),
                new Node( "Goods Vehicle",
                        new Node( "Light Goods Vehicle",
                                new Node( "Delivery Van" ),
                                new Node( "Light Truck" ),
                                new Node( "Tempo",
                                        new Node( "Three Wheeler Tempo" ),
                                        new Node( "Four Wheeler Tempo" ) ) ),
                        new Node( "Heavy Goods Vehicle",
                                new Node( "Truck" ),
                                new Node( "Tractor Trailer" ) ) ) );
        dump( tree, n -> n.children, n -> n.name, s -> System.out.println( s ) );
    }
}

ContentLicense: CC BY-SA 3.0


问:
Text Spilling Outside of Div

The screenshot above shows the problem. Unlike the other similar question I don't need this to work for international text. I need this to work for varying screen sizes and varying amounts of text. The text will come from a databse in production, so I can't simply figure out the breakpoint at which the div needs to move down in advance.

The solution I am looking for would first  move the text block below the image, and then resize the text div vertically as necessary to accomidate all the text. JS or CSS solutions are fine.

HTML below:

```<code><div class="product">
    <img class="productImg" src="http://placehold.it/300x240">
    <div class="productTxt">
        <h1>Title</h1>
        <h3>Price</h3>
        <p>Suspendisse sed fermentum neque, vel rutrum velit. Curabitur eget dolor luctus, sodales felis sed, dapibus justo.
        Suspendisse in condimentum ante. Sed nec dui tristique, sollicitudin velit eget, ultricies dui.
        Ut rhoncus ornare urna, quis venenatis velit ornare eu. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
        Etiam ornare sem finibus lectus volutpat, in feugiat elit ultrices. In sed vulputate eros, quis volutpat elit.
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse nisi libero, posuere nec laoreet quis, viverra et lorem. Duis odio ante, efficitur et felis at, tincidunt interdum ante.
        Quisque vestibulum eu est a egestas. Nunc hendrerit rutrum dui at cursus. Aliquam mollis nec magna ac mattis.
        Nam nec est tincidunt leo facilisis finibus non nec mauris. Vestibulum rutrum tristique tincidunt. </p>
    </div>
</div>
</code>```

CSS:

```<code>.product {
    box-sizing: border-box;
    margin: 0px;
    padding: 10px;
    width: 100%;
    height: 330px;
    border-bottom: 2px solid #16A085;
}

.productImg {
    width: 240px;
    height: 300px;
    display: inline-block;
    position: relative;
}

.productTxt {
    box-sizing: border-box;
    vertical-align: top;
    display: inline-block;
    height: 100%;
    width: calc(100% - 270px);
    padding: 10px;
    text-align: center;
    position: relative;
    border: 2px solid blue;
 }
</code>```

I can't really remove the relative positioning from the productTxt div without breaking the positioning of another element that is within the same div (which I have removed for simplicity in this example)

答:
Remove the fixed height in of parent div .product and add a min-width to .productTxt. If you use 100% for width or height, it's relative to the parent div, and you must specifically set the parent's width or height. That's why your height: 100% on .productTxt was not changing based on your content and was fixed to parent div .product's height: 330px.

```<code>.product {
    box-sizing: border-box;
    margin: 0px;
    padding: 10px;
    width: 100%;
    border-bottom: 2px solid #16A085;
}

.productTxt {
    box-sizing: padding-box;
    vertical-align: top;
    display: inline-block;
    height: 100%;
    width: calc(100% - 270px);
    min-width: 220px; /* change this to what you want */
    padding: 10px;
    text-align: center;
    position: relative;
    border: 2px solid blue;
 }
</code>```

Title: Text Spilling Outside of Div

Body:
The screenshot above shows the problem. Unlike the other similar question I don't need this to work for international text. I need this to work for varying screen sizes and varying amounts of text. The text will come from a databse in production, so I can't simply figure out the breakpoint at which the div needs to move down in advance.

The solution I am looking for would first  move the text block below the image, and then resize the text div vertically as necessary to accomidate all the text. JS or CSS solutions are fine.

HTML below:

Title

Price

Suspendisse sed fermentum neque, vel rutrum velit. Curabitur eget dolor luctus, sodales felis sed, dapibus justo.
        Suspendisse in condimentum ante. Sed nec dui tristique, sollicitudin velit eget, ultricies dui.
        Ut rhoncus ornare urna, quis venenatis velit ornare eu. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
        Etiam ornare sem finibus lectus volutpat, in feugiat elit ultrices. In sed vulputate eros, quis volutpat elit.
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse nisi libero, posuere nec laoreet quis, viverra et lorem. Duis odio ante, efficitur et felis at, tincidunt interdum ante.
        Quisque vestibulum eu est a egestas. Nunc hendrerit rutrum dui at cursus. Aliquam mollis nec magna ac mattis.
        Nam nec est tincidunt leo facilisis finibus non nec mauris. Vestibulum rutrum tristique tincidunt.

CSS:

.product {
    box-sizing: border-box;
    margin: 0px;
    padding: 10px;
    width: 100%;
    height: 330px;
    border-bottom: 2px solid #16A085;
}

.productImg {
    width: 240px;
    height: 300px;
    display: inline-block;
    position: relative;
}

.productTxt {
    box-sizing: border-box;
    vertical-align: top;
    display: inline-block;
    height: 100%;
    width: calc(100% - 270px);
    padding: 10px;
    text-align: center;
    position: relative;
    border: 2px solid blue;
 }

I can't really remove the relative positioning from the productTxt div without breaking the positioning of another element that is within the same div (which I have removed for simplicity in this example)

Body:
Remove the fixed height in of parent div .product and add a min-width to .productTxt. If you use 100% for width or height, it's relative to the parent div, and you must specifically set the parent's width or height. That's why your height: 100% on .productTxt was not changing based on your content and was fixed to parent div .product's height: 330px.

.product {
    box-sizing: border-box;
    margin: 0px;
    padding: 10px;
    width: 100%;
    border-bottom: 2px solid #16A085;
}

.productTxt {
    box-sizing: padding-box;
    vertical-align: top;
    display: inline-block;
    height: 100%;
    width: calc(100% - 270px);
    min-width: 220px; /* change this to what you want */
    padding: 10px;
    text-align: center;
    position: relative;
    border: 2px solid blue;
 }


问:
Query-string encoding of a JavaScript object
Is there a fast and simple way to encode a JavaScript object into a string that I can pass via a GET request?

No jQuery, no other frameworks—just plain JavaScript :)

答:
Here's a concise & recursive version with Object.entries.  It handles arbitrarily nested arrays, but not nested objects.  It also removes empty elements:

```<code>const format = (k,v) => v !== null ? `${k}=${encodeURIComponent(v)}` : ''

const to_qs = (obj) => {
    return [].concat(...Object.entries(obj)
                       .map(([k,v]) => Array.isArray(v)
                          ? v.map(arr => to_qs({[k]:arr}))
                          : format(k,v)))
           .filter(x => x)
           .join('&');
}
</code>```

E.g.:

```<code>let json = {
    a: [1, 2, 3],
    b: [],              // omit b
    c: 1,
    d: "test&encoding", // uriencode
    e: [[4,5],[6,7]],   // flatten this
    f: null,            // omit nulls
    g: 0
};

let qs = to_qs(json)

=> "a=1&a=2&a=3&c=1&d=test%26encoding&e=4&e=5&e=6&e=7&g=0"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here's a concise & recursive version with Object.entries.  It handles arbitrarily nested arrays, but not nested objects.  It also removes empty elements:

const format = (k,v) => v !== null ? `${k}=${encodeURIComponent(v)}` : ''

const to_qs = (obj) => {
    return [].concat(...Object.entries(obj)
                       .map(([k,v]) => Array.isArray(v)
                          ? v.map(arr => to_qs({[k]:arr}))
                          : format(k,v)))
           .filter(x => x)
           .join('&');
}

E.g.:

let json = {
    a: [1, 2, 3],
    b: [],              // omit b
    c: 1,
    d: "test&encoding", // uriencode
    e: [[4,5],[6,7]],   // flatten this
    f: null,            // omit nulls
    g: 0
};

let qs = to_qs(json)

=> "a=1&a=2&a=3&c=1&d=test%26encoding&e=4&e=5&e=6&e=7&g=0"


问:
Pass another view as parameter in data binding
I am trying to pass a another view of my xml as a parameter of a method in Google data binding... like this:

```<code><LinearLayout
    android:id="@+id/faq_subject_about_ego"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/border_faq_btn"
    android:orientation="horizontal"
    android:layout_marginBottom="20dp"
    android:padding="4dp"
    android:gravity="center"
    android:onClick='@{(faq_title_about) -> viewModel.subjectRequest(faq_title_about.getText())}'>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/icon_faq"
        android:layout_marginRight="8dp"
        android:clickable="false" />

    <ebanx.com.ego.utils.custom_extension.CustomButtonBold
        android:id="@+id/faq_title_about"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="@style/Button_FAQ"
        android:text="@string/btn_about_ego"
        android:clickable="false" />
</LinearLayout>
</code>```

I need the text that is in my CustomButtonBold... But this is not working.

How can I pass the text of the button as a parameter?

Any help is appreciated!

答:
The member generated for the id-able has a CamelCase name format. Also the view provided to the OnClickListener is the view being clicked. So just name the parameter arbitrarily and use the correct "global" member.

```<code>android:onClick='@{(v) -> viewModel.subjectRequest(faqTitleAbout.getText())}'
</code>```

Body:
I am trying to pass a another view of my xml as a parameter of a method in Google data binding... like this:

<LinearLayout
    android:id="@+id/faq_subject_about_ego"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/border_faq_btn"
    android:orientation="horizontal"
    android:layout_marginBottom="20dp"
    android:padding="4dp"
    android:gravity="center"
    android:onClick='@{(faq_title_about) -> viewModel.subjectRequest(faq_title_about.getText())}'>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/icon_faq"
        android:layout_marginRight="8dp"
        android:clickable="false" />

    <ebanx.com.ego.utils.custom_extension.CustomButtonBold
        android:id="@+id/faq_title_about"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="@style/Button_FAQ"
        android:text="@string/btn_about_ego"
        android:clickable="false" />
</LinearLayout>

I need the text that is in my CustomButtonBold... But this is not working.

How can I pass the text of the button as a parameter?

Any help is appreciated!

Body:
The member generated for the id-able has a CamelCase name format. Also the view provided to the OnClickListener is the view being clicked. So just name the parameter arbitrarily and use the correct "global" member.

android:onClick='@{(v) -> viewModel.subjectRequest(faqTitleAbout.getText())}'


问:
Go importing vendor dependencies issue when building a Go 1.7 project using govendor, dh-make-golang
I've been looking into building a go project into a debian package.

I've looked into dh-make-golang and I have a nice and shiny debian folder set up in my repository. When I try to use gbp buildpackage --git-pbuilder though it errors out due to all of my dependencies not being found. It seems that dh-make-golang ignores the vendor folder when it copies everything from my project's git repository, and I use govendor so all of my dependencies are in there.

How can I resolve this dependency issue and build the project as a .deb package properly? For reference, the error I am getting is:

src/github.com/project/project/project.go:15:2: cannot find package "google.golang.org/grpc/grpclog" in any of:
    /usr/lib/go-1.7/src/google.golang.org/grpc/grpclog (from $GOROOT)
    /tmp/project/obj-x86_64-linux-gnu/src/google.golang.org/grpc/grpclog (from $GOPATH)

答:
Issue was a bug in dh-make-golang regarding importing vendor dependencies. It was just fixed today.

https://github.com/Debian/dh-make-golang/issues/46


问:
Call function for paired arguments
Here is simple script to generate greeting messages:

```<code>def greeting(event, person):
    print("Happy " + event + ", dear " + person + ".")

event = "Birthday"
person = "Emily"
greeting(event, person) # Happy Birtday, dear Emily.

event = "New Year"
person = "Mark"
greeting(event, person) # Happy New Year, dear Mark.
</code>```

Is there way to get the same result, but call the greeting function only once?

答:
If you can modify greeting:</p>

```<code>def greeting(info_pairs):
    for event, person in info_pairs:
         print("Happy " + event + ", dear " + person + ".")

greeting([("Birthday", "Emily"), ("New Year", "Mark")])
</code>```

Title: Call function for paired arguments

Body:
Here is simple script to generate greeting messages:

def greeting(event, person):
    print("Happy " + event + ", dear " + person + ".")

event = "Birthday"
person = "Emily"
greeting(event, person) # Happy Birtday, dear Emily.

event = "New Year"
person = "Mark"
greeting(event, person) # Happy New Year, dear Mark.

Is there way to get the same result, but call the greeting function only once?

Body:
If you can modify greeting:

def greeting(info_pairs):
    for event, person in info_pairs:
         print("Happy " + event + ", dear " + person + ".")

greeting([("Birthday", "Emily"), ("New Year", "Mark")])


问:
How to forward Hive UDTF output with the last input row
Hive UDTF process each row singly and forward output for each row.
I need to do some manipulations with all function output.
Is there way to forward all function output one time after all rows was processed?

Thanks in advance!

答:
Yes, such way exists.

To make some changes with all output of UDF, you have firstly to
store it. So, create the field in UDF class to collect the output in
it: private List<SomeClass> output = new ArrayList<>();

Then in your process() method you should use output.add() instead
of forward(). So in process() the output will be filled.

And finally you have the close() method. It is used for cleaning
up after all processing and usually it's not necessary to code
something in it. However in your case, close() is a good
possibility to process output collection and forward it.

The approximate code of close() is here:

```<code>@Override
public void close() throws HiveException {
    for(String record: output){
        forwardObjArray[0] = record.substring(3);
        forward(forwardObjArray);
    }
}
</code>```

forwardObjArray is another private field of UDF. It is used to optimize resource usage (to avoid creation array with 1 element before each forward() call).

But this way applicable only if you run UDTF on small dataset. Otherwise output collection will be extremely large.

If you're going to run UDTF on large input data, I recommend to use two UDTFs. As current Hive version dosn't allow to use nested UDTFs, you can use subqueries:

```<code>SELECT func2(processed)
FROM (
    SELECT func1(fiels) AS processed
    FROM table
) AS interm_table;
</code>```

In func2() you'll implement the logic used to manipulate the output of func1().

Body:
Yes, such way exists.

To make some changes with all output of UDF, you have firstly to
store it. So, create the field in UDF class to collect the output in
it: private List<SomeClass> output = new ArrayList<>();

Then in your process() method you should use output.add() instead
of forward(). So in process() the output will be filled.

And finally you have the close() method. It is used for cleaning
up after all processing and usually it's not necessary to code
something in it. However in your case, close() is a good
possibility to process output collection and forward it.

The approximate code of close() is here:

@Override
public void close() throws HiveException {
    for(String record: output){
        forwardObjArray[0] = record.substring(3);
        forward(forwardObjArray);
    }
}

forwardObjArray is another private field of UDF. It is used to optimize resource usage (to avoid creation array with 1 element before each forward() call).

But this way applicable only if you run UDTF on small dataset. Otherwise output collection will be extremely large.

If you're going to run UDTF on large input data, I recommend to use two UDTFs. As current Hive version dosn't allow to use nested UDTFs, you can use subqueries:

SELECT func2(processed)
FROM (
    SELECT func1(fiels) AS processed
    FROM table
) AS interm_table;

In func2() you'll implement the logic used to manipulate the output of func1().


问:
Copy a Template each time and replace using Excel Macro
I have the following data set in my sheet 1

And this template in sheet 3

I wish to

Copy the template from sheet 3 to sheet2

Read the city and name from row 1 in sheet1

Replace the City and Name in sheet 2

Repeat it for every row in sheet 1

So my ideal output will be:

As you can see because we have three rows in sheet 1 the template is copied three times.

I tried this code, but it doesn't go to loop for 'sheet1'

```<code>Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
Dim copySheet As Worksheet
Dim pasteSheet As Worksheet
Dim ii As Long

Set copySheet = Worksheets("Sheet3")
Set pasteSheet = Worksheets("Sheet2")

For ii = 1 To 10
 copySheet.Range("A1:E3").Copy
 pasteSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
 Application.CutCopyMode = False
 Application.ScreenUpdating = True

Dim j, k, L, b As String
   Dim i As Long
   Dim wb As Workbook
   Dim sht1 As Worksheet
   Dim sht2 As Worksheet

  Set wb = ThisWorkbook
  Set sht1 = wb.Sheets("Sheet1")
  Set sht2 = wb.Sheets("Sheet2")

   j = "Name"
   b = "City"

   For i = 1 To 3

    k = sht1.Range("A" & i)
    L = sht1.Range("B" & i)

    sht2.Cells.Replace what:=j, replacement:=k, lookat:=xlWhole, MatchCase:=False
    sht2.Cells.Replace what:=b, replacement:=L, lookat:=xlWhole, MatchCase:=False

   Next i

Next ii

 End Sub
</code>```

Any guidance is really appreciated.

答:
This isn't what you asked for, but you can accomplish this entirely with cell formulas.  It is a little complicated, and VBA is probably a better approach, but in case you're curious:

I am assuming your Name/City pairs are in Sheet1!$A$1:$B$9 **

On sheet 2, in column A, I will build a list that indicates which row to grab data from. (1,1,1,2,2,2,3,3,3,4,4,4, etc)

On sheet 2, column B, I will build a list that shows which type of result this destination row should have (Name - City Name is 1, Name City - City is 2, and Name - City is 3) There are various ways of doing this.  I filled Column A with =INT((ROW()-1)/3)+1 and column B with =MOD(ROW()-1,3)+1

Now my first two columns on Sheet 2 look like

Now I can use those to build indexed lookups against the original data.  Column C will have 2 different types of behavior.  It always starts with the Name, but if Column B is 2, it is followed by the City.

=INDEX(Sheet1!$A$1:$B$9,S A1,1)&IF(B1=2," " & INDEX(Sheet1!$A$1:$B$9, A1,2),"")

Column D will also have two types of entries.  Always start with the City, but if Column B is 1, follow with the name.

=INDEX(Sheet1!$A$1:$B$9,A1,2)&IF(B1=1," " & INDEX(Sheet1!$A$1:$B$9,A1,1),"")

Voila

If you wanted to, you could replace all of the references to Columns A & B with the actual formulas that are in them.

Then Column C would have:

```<code>=INDEX(Sheet1!$A$1:$B$9,INT((ROW()-1)/3)+1,1)&" "&IF(MOD(ROW()-1,3)+1=2,INDEX(Sheet1!$A$1:$B$9,INT((ROW()-1)/3)+1,2),"")
</code>```

Make the corresponding substitutions in Column D and you can leave out Columns A&B.

One small inconvenience with this approach is that because it relies on row(), it can't be moved to any other row without adjusting the two index formulas ( INT((ROW()-1)/3)+1 &MOD(ROW()-1,3)+1)

** In the real world, I would also give your source data table a name, like NameCityTable  Then your first result column could look like:

```<code>=INDEX(NameCityTable,INT((ROW()-1)/3)+1,1)&" "&IF(MOD(ROW()-1,3)+1=2,INDEX(NameCityTable,INT((ROW()-1)/3)+1,2),"")
</code>```

Body:
I have the following data set in my sheet 1

And this template in sheet 3

I wish to

Copy the template from sheet 3 to sheet2

Read the city and name from row 1 in sheet1

Replace the City and Name in sheet 2

Repeat it for every row in sheet 1

So my ideal output will be:

As you can see because we have three rows in sheet 1 the template is copied three times.

I tried this code, but it doesn't go to loop for 'sheet1'

Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
Dim copySheet As Worksheet
Dim pasteSheet As Worksheet
Dim ii As Long

Set copySheet = Worksheets("Sheet3")
Set pasteSheet = Worksheets("Sheet2")

For ii = 1 To 10
 copySheet.Range("A1:E3").Copy
 pasteSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
 Application.CutCopyMode = False
 Application.ScreenUpdating = True

Dim j, k, L, b As String
   Dim i As Long
   Dim wb As Workbook
   Dim sht1 As Worksheet
   Dim sht2 As Worksheet

  Set wb = ThisWorkbook
  Set sht1 = wb.Sheets("Sheet1")
  Set sht2 = wb.Sheets("Sheet2")

   j = "Name"
   b = "City"

   For i = 1 To 3

    k = sht1.Range("A" & i)
    L = sht1.Range("B" & i)

    sht2.Cells.Replace what:=j, replacement:=k, lookat:=xlWhole, MatchCase:=False
    sht2.Cells.Replace what:=b, replacement:=L, lookat:=xlWhole, MatchCase:=False

   Next i

Next ii

 End Sub

Any guidance is really appreciated.

Body:
This isn't what you asked for, but you can accomplish this entirely with cell formulas.  It is a little complicated, and VBA is probably a better approach, but in case you're curious:

I am assuming your Name/City pairs are in Sheet1!$A$1:$B$9 **

On sheet 2, in column A, I will build a list that indicates which row to grab data from. (1,1,1,2,2,2,3,3,3,4,4,4, etc)

On sheet 2, column B, I will build a list that shows which type of result this destination row should have (Name - City Name is 1, Name City - City is 2, and Name - City is 3) There are various ways of doing this.  I filled Column A with =INT((ROW()-1)/3)+1 and column B with =MOD(ROW()-1,3)+1

Now my first two columns on Sheet 2 look like

Now I can use those to build indexed lookups against the original data.  Column C will have 2 different types of behavior.  It always starts with the Name, but if Column B is 2, it is followed by the City.

=INDEX(Sheet1!$A$1:$B$9,S A1,1)&IF(B1=2," " & INDEX(Sheet1!$A$1:$B$9, A1,2),"")

Column D will also have two types of entries.  Always start with the City, but if Column B is 1, follow with the name.

=INDEX(Sheet1!$A$1:$B$9,A1,2)&IF(B1=1," " & INDEX(Sheet1!$A$1:$B$9,A1,1),"")

Voila

If you wanted to, you could replace all of the references to Columns A & B with the actual formulas that are in them.

Then Column C would have:

=INDEX(Sheet1!$A$1:$B$9,INT((ROW()-1)/3)+1,1)&" "&IF(MOD(ROW()-1,3)+1=2,INDEX(Sheet1!$A$1:$B$9,INT((ROW()-1)/3)+1,2),"")

Make the corresponding substitutions in Column D and you can leave out Columns A&B.

One small inconvenience with this approach is that because it relies on row(), it can't be moved to any other row without adjusting the two index formulas ( INT((ROW()-1)/3)+1 &MOD(ROW()-1,3)+1)

** In the real world, I would also give your source data table a name, like NameCityTable  Then your first result column could look like:

=INDEX(NameCityTable,INT((ROW()-1)/3)+1,1)&" "&IF(MOD(ROW()-1,3)+1=2,INDEX(NameCityTable,INT((ROW()-1)/3)+1,2),"")


问:
Loading Image in Kivy
I want an image to be displayed in the center of the layout. I could not figure it out. Is there any way to display the image on the center of the layout and be there till the animation is stopped?

Here is my code.

```<code>from kivy.app import App
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout
from kivy.animation import Animation
from kivy.properties import NumericProperty

Builder.load_string('''
<Loading>:
    canvas:
        Rotate:
            angle: root.angle
            origin: self.center
        Color:
            rgb: .0, 0, -.1
        Ellipse:
            size: min(self.size), min(self.size)
            pos: 0.5*self.size[0] - 0.5*min(self.size), 0.5*self.size[1] - 0.5*min(self.size)
        Color:
            rgb: .5, 0, 1
        Ellipse:
            size: 30, 30
            pos: 0.5*root.size[0]+25, 0.8*root.size[1]-25
''')

class Loading(FloatLayout):
    angle = NumericProperty(0)

    def __init__(self, **kwargs):
        super(Loading, self).__init__(**kwargs)
        anim = Animation(angle = 1009, duration=2.5)
        anim += Animation(angle = 1900, duration=2.5)
        anim.repeat = True
        anim.start(self)

    def on_angle(self, item, angle):
       if angle == 360:
           item.angle = 0

class TestApp(App):
    def build(self):

        return Loading()

TestApp().run()
</code>```

答:
I don't think your canvas should be "loose" like that. Place it inside of a Widget, this will let you use Kivy's various layouts to arrange things. It will also let you insert an Image above the widget and without making the image spin around.

A second thing, use rgba so you can specify transparencies for the background. This example below works for me, just replace the Builder string with this:

```<code>"""<Loading>:
FloatLayout:
    Image:
        source: 'logo.png'
    Widget:
        canvas:
            Rotate:
                angle: root.angle
                origin: self.center
            Color:
                rgba: 1, 1, 1, 0

            Ellipse:
                size: min(self.size), min(self.size)
                pos: 0.5*self.size[0] - 0.5*min(self.size), 0.5*self.size[1] - 0.5*min(self.size)
            Color:
                rgba: .5, 0, 1, 1

            Ellipse:
                size: 30, 30
                pos: 0.5*root.size[0]+25, 0.8*root.size[1]-25
            Color:
                rgba: 0.5, 0, 1"""
</code>```

I also attached our Departments logo that I used for the example. I leave it to you to tweak sizes and add the appropriate resizing calls.logo

Title: Loading Image in Kivy

Body:
I want an image to be displayed in the center of the layout. I could not figure it out. Is there any way to display the image on the center of the layout and be there till the animation is stopped?

Here is my code.

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout
from kivy.animation import Animation
from kivy.properties import NumericProperty

Builder.load_string('''
<Loading>:
    canvas:
        Rotate:
            angle: root.angle
            origin: self.center
        Color:
            rgb: .0, 0, -.1
        Ellipse:
            size: min(self.size), min(self.size)
            pos: 0.5*self.size[0] - 0.5*min(self.size), 0.5*self.size[1] - 0.5*min(self.size)
        Color:
            rgb: .5, 0, 1
        Ellipse:
            size: 30, 30
            pos: 0.5*root.size[0]+25, 0.8*root.size[1]-25
''')

class Loading(FloatLayout):
    angle = NumericProperty(0)

    def __init__(self, **kwargs):
        super(Loading, self).__init__(**kwargs)
        anim = Animation(angle = 1009, duration=2.5)
        anim += Animation(angle = 1900, duration=2.5)
        anim.repeat = True
        anim.start(self)

    def on_angle(self, item, angle):
       if angle == 360:
           item.angle = 0

class TestApp(App):
    def build(self):

        return Loading()

TestApp().run()

Body:
I don't think your canvas should be "loose" like that. Place it inside of a Widget, this will let you use Kivy's various layouts to arrange things. It will also let you insert an Image above the widget and without making the image spin around.

A second thing, use rgba so you can specify transparencies for the background. This example below works for me, just replace the Builder string with this:

"""<Loading>:
FloatLayout:
    Image:
        source: 'logo.png'
    Widget:
        canvas:
            Rotate:
                angle: root.angle
                origin: self.center
            Color:
                rgba: 1, 1, 1, 0

            Ellipse:
                size: min(self.size), min(self.size)
                pos: 0.5*self.size[0] - 0.5*min(self.size), 0.5*self.size[1] - 0.5*min(self.size)
            Color:
                rgba: .5, 0, 1, 1

            Ellipse:
                size: 30, 30
                pos: 0.5*root.size[0]+25, 0.8*root.size[1]-25
            Color:
                rgba: 0.5, 0, 1"""

I also attached our Departments logo that I used for the example. I leave it to you to tweak sizes and add the appropriate resizing calls.logo


问:
NEXT_DAY function works differently in SQL vs. PL/SQL?
Why does this SQL query work:

```<code>SELECT NEXT_DAY(SYSDATE, 7)
FROM DUAL;
</code>```

```<code>NEXT_DAY(SYSDATE,7)
-------------------
01-APR-17
1 row selected.
</code>```

...but this anonymous block of PL/SQL does not work?

```<code>DECLARE
  dteExpires DATE;
BEGIN
  dteExpires := NEXT_DAY(SYSDATE, 7);
END;
</code>```

```<code>Error at line 1
ORA-01846: not a valid day of the week
ORA-06512: at line 4
</code>```

I do not want to hard code the second parameter to the English name of a day ex. NEXT_DAY(SYSDATE, 'SATURDAY') or NEXT_DAY(SYSDATE, 'SUNDAY') etc.

For now, I will use the following work around, but I would really like to know why NEXT_DAY() behaves differently in PL/SQL than in SQL.

```<code>DECLARE
  dteExpires DATE;
BEGIN
  -- 2017-01-01 = SUNDAY
  dteExpires := NEXT_DAY(SYSDATE, TO_CHAR(TO_DATE('2017-01-01', 'YYYY-MM-DD'), 'DAY'));
END;
</code>```

This is my DEV environment:

```<code>SELECT *
FROM v$version;
</code>```

```<code>BANNER

--------------------------------------------------------------------------------
Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production
PL/SQL Release 12.1.0.2.0 - Production
CORE  12.1.0.2.0  Production
TNS for 64-bit Windows: Version 12.1.0.2.0 - Production
NLSRTL Version 12.1.0.2.0 - Production

5 rows selected.
</code>```

答:
If you check the documentation for the SQL version of NEXT_DAY, you will find that passing in a number to represent a day of the week is undocumented. It works, for whatever reason, but if you rely on it working, you are taking the risk that in the future Oracle will change the implementation to conform to the stated specification of this function. (The risk is small, since Oracle is not crazy.)

https://docs.oracle.com/database/121/SQLRF/functions118.htm#SQLRF00672

The PL/SQL implementation only works with the documented specification - it does not accept a numeric input to represent a day of the week.

I guess this is an indirect answer. I believe you are asking the wrong question. The question shouldn't be "why doesn't this work in PL/SQL"; rather, given the documentation, the question should be "why does it work in Oracle SQL". Only Oracle can answer that.

You may find this discussion at OTN useful: https://community.oracle.com/thread/4023654

And maybe this too: https://community.oracle.com/ideas/17257?tab=comment

Body:
Why does this SQL query work:

SELECT NEXT_DAY(SYSDATE, 7)
FROM DUAL;

NEXT_DAY(SYSDATE,7)
-------------------
01-APR-17
1 row selected.

...but this anonymous block of PL/SQL does not work?

DECLARE
  dteExpires DATE;
BEGIN
  dteExpires := NEXT_DAY(SYSDATE, 7);
END;

Error at line 1
ORA-01846: not a valid day of the week
ORA-06512: at line 4

I do not want to hard code the second parameter to the English name of a day ex. NEXT_DAY(SYSDATE, 'SATURDAY') or NEXT_DAY(SYSDATE, 'SUNDAY') etc.

For now, I will use the following work around, but I would really like to know why NEXT_DAY() behaves differently in PL/SQL than in SQL.

DECLARE
  dteExpires DATE;
BEGIN
  -- 2017-01-01 = SUNDAY
  dteExpires := NEXT_DAY(SYSDATE, TO_CHAR(TO_DATE('2017-01-01', 'YYYY-MM-DD'), 'DAY'));
END;

This is my DEV environment:

SELECT *
FROM v$version;

BANNER

--------------------------------------------------------------------------------
Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production
PL/SQL Release 12.1.0.2.0 - Production
CORE  12.1.0.2.0  Production
TNS for 64-bit Windows: Version 12.1.0.2.0 - Production
NLSRTL Version 12.1.0.2.0 - Production

5 rows selected.


问:
Javascript use variable to call another variable
I'm making something in React Native and there's a module where I have a variable called jorge

```<code>const jorge = "This is some output";
console.log(jorge);            //output: 'This is some output'
</code>```

I've passed props item to this module (I'm using the react-native-router-flux module, which also has a value of jorge:

```<code><Scene
    key="sceneTwo"
    component={componentItem}
    title={content.title}
    item="jorge"
 />
</code>```

I'd like to be able to do this:

```<code>console.log(this.props.item);  //output: 'This is some output'
</code>```

Whereas in reality, I get this:

```<code>console.log(this.props.item);  //output: 'jorge'
</code>```

I'm not sure what this technique is called hence the extremely vague title, but if anyone can suggest how I'd tackle this I'd be very grateful!

答:
Your are passing the string "jorge" rather than the variable jorge.  To pass a variable you need to wrap it in curly brackets:

```<code><Scene
    key="sceneTwo"
    component={componentItem}
    title={content.title}
    item={jorge}
 />
</code>```

Body:
I'm making something in React Native and there's a module where I have a variable called jorge

const jorge = "This is some output";
console.log(jorge);            //output: 'This is some output'

I've passed props item to this module (I'm using the react-native-router-flux module, which also has a value of jorge:

<Scene
    key="sceneTwo"
    component={componentItem}
    title={content.title}
    item="jorge"
 />

I'd like to be able to do this:

console.log(this.props.item);  //output: 'This is some output'

Whereas in reality, I get this:

console.log(this.props.item);  //output: 'jorge'

I'm not sure what this technique is called hence the extremely vague title, but if anyone can suggest how I'd tackle this I'd be very grateful!

Body:
Your are passing the string "jorge" rather than the variable jorge.  To pass a variable you need to wrap it in curly brackets:

<Scene
    key="sceneTwo"
    component={componentItem}
    title={content.title}
    item={jorge}
 />


问:
Attempt to invoke virtual method 'void android.nfc.tech.MifareClassic.connect()' on a null object reference
I've been developing an application in Android Studio to read and write NFC tags, specifically Mifare Classic tags. I managed to develop and test it on my smartphone (with S.O. KitKat) in early 2016 (a year ago).

As I mentioned, leave aside the application, and after having updated the version of Android Studio, the SDK and the S.O. From my smartphone to MarshMallow, this error appears when trying to write to the label: "java.lang.NullPointerException: Attempt to invoke virtual method 'void android.nfc.tech.MifareClassic.connect()' on a null object reference".

This error is apparently generated when trying to connect to MifareClassic tag.

Attached the code of my activity replacing some parts with ... that I consider are irrelevant.

```<code>import android.annotation.SuppressLint;
import android.app.Activity;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.os.Bundle;
import android.view.View.OnClickListener;
...

import java.io.IOException;
import java.io.UnsupportedEncodingException;

@SuppressLint("Escribir")
public class escribir extends Activity {
    NfcAdapter adapter;
    PendingIntent pendingIntent;
    IntentFilter writeTagFilters[];
    boolean writeMode;
    Tag myTag;
    MifareClassic mfc;
    Context context;
    ...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_datospropietario);
        context = this;
        ...

        Button btnWrite = (Button)findViewById(R.id.button);
        final String b = getIntent().getExtras().getString("datos");

        btnWrite.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                final String mensaje = (b + ...);

                if (first.getText().toString().isEmpty()) {
                    Toast.makeText(context, context.getString(R.string.missing_fields), Toast.LENGTH_SHORT).show();
                } else {
                    if (myTag == null) {
                        Toast.makeText(context, context.getString(R.string.error_notag), Toast.LENGTH_LONG).show();
                    } else {
                    MifareClassic tmpMFC = null;
                    try {
                        tmpMFC = MifareClassic.get(myTag);
                    } catch (Exception e) {
                        Toast.makeText(context, context.getString(R.string.error_notag), Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                    }
                    mfc = tmpMFC;

                    int sect;
                    if (mfc != null) {
                        sect = mfc.getSectorCount();
                    }
                    try {
                        mfc.connect();
                        ...
                    } catch (IOException e) {
                        Toast.makeText(context, context.getString(R.string.error_notag), Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                        myTag = null;
                    }
                }
            }
        });

        adapter = NfcAdapter.getDefaultAdapter(this);
        pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
        tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
        writeTagFilters = new IntentFilter[]{tagDetected};
    }

    private void write(String text, Tag tag, int sector) throws IOException, FormatException {

        NdefRecord[] records = {createRecord(text), NdefRecord.createApplicationRecord("my_app")};
        NdefMessage mensaje = new NdefMessage(records);

        NdefFormatable formatable = NdefFormatable.get(tag);

        if (formatable != null) {
            formatable.connect();
            formatable.format(mensaje);
            formatable.close();
        } else {
            Ndef ndef = Ndef.get(tag);
            ndef.connect();
            ndef.writeNdefMessage(mensaje);
            ndef.close();
        }

        MifareClassic mfc = MifareClassic.get(tag);
        ...
    }

    @SuppressLint("Escribir") private NdefRecord createRecord(String text) throws UnsupportedEncodingException{
        String lang = "es";
        byte[] textBytes = text.getBytes();
        byte[] langBytes = lang.getBytes("US-ASCII");
        int langLength = langBytes.length;
        int textLength = textBytes.length;
        byte[] payLoad = new byte[1 + langLength + textLength];

        payLoad[0] = (byte) langLength;

        System.arraycopy(langBytes, 0, payLoad, 1, langLength);
        System.arraycopy(textBytes, 0, payLoad, 1 + langLength, textLength);

        return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], payLoad);
    }

    @SuppressLint("Escribir") protected void onNewIntent(Intent intent){
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
            myTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        }
    }

    public void onPause(){
        super.onPause();
        WriteModeOff();
    }
    public void onResume(){
        super.onResume();
        WriteModeOn();
    }

    @SuppressLint("Escribir") private void WriteModeOn(){
        writeMode = true;
        adapter.enableForegroundDispatch(this, pendingIntent, writeTagFilters, null);
    }

    @SuppressLint("Escribir") private void WriteModeOff(){
        writeMode = false;
        adapter.disableForegroundDispatch(this);
    }
}
</code>```

答:
After researching the internet about this problem, I discovered that writing problems on NFC tags were presented on various devices, such as some HTC or Sony Xperia models. These issues were presented after upgrading the Android version to SDK 5.1 (Lollipop).

This problem originated because some of the manufacturers modified the stack order where the different Tag types were found causing conflicts when requesting TechExtras and returning SAK null or wrong values.

The detailed explanation I found for this is as follows:

HTC One: It seems, the reason for this bug is TechExtras of NfcA is null.
However, TechList contains MifareClassic.

Sony Xperia Z3 (+ emmulated MIFARE Classic tag): The buggy tag has two NfcA in the TechList with different SAK values and a MifareClassic (with the Extra of the second NfcA). Both, the second NfcA and the MifareClassic technique, have a SAK of 0x20. According to NXP's guidelines on identifying MIFARE tags (Page 11), this a MIFARE Plus or MIFARE DESFire tag. This method creates a new extra with the SAK values of both NfcA occurrences ORed (as mentioned in NXP's MIFARE type identification procedure guide) and replace the Extra of the first NfcA with the new one.

For more information please refer to https://github.com/ikarus23/MifareClassicTool/issues/52

And the patch proposed by the bildin user, who fixed my problem:

```<code>public Tag patchTag(Tag oTag)
{
    if (oTag == null)
        return null;

    String[] sTechList = oTag.getTechList();

    Parcel oParcel, nParcel;

    oParcel = Parcel.obtain();
    oTag.writeToParcel(oParcel, 0);
    oParcel.setDataPosition(0);

    int len = oParcel.readInt();
    byte[] id = null;
    if (len >= 0)
    {
        id = new byte[len];
        oParcel.readByteArray(id);
    }
    int[] oTechList = new int[oParcel.readInt()];
    oParcel.readIntArray(oTechList);
    Bundle[] oTechExtras = oParcel.createTypedArray(Bundle.CREATOR);
    int serviceHandle = oParcel.readInt();
    int isMock = oParcel.readInt();
    IBinder tagService;
    if (isMock == 0)
    {
        tagService = oParcel.readStrongBinder();
    }
    else
    {
        tagService = null;
    }
    oParcel.recycle();

    int nfca_idx=-1;
    int mc_idx=-1;

    for(int idx = 0; idx < sTechList.length; idx++)
    {
        if(sTechList[idx] == NfcA.class.getName())
        {
            nfca_idx = idx;
        }
        else if(sTechList[idx] == MifareClassic.class.getName())
        {
            mc_idx = idx;
        }
    }

    if(nfca_idx>=0&&mc_idx>=0&&oTechExtras[mc_idx]==null)
    {
        oTechExtras[mc_idx] = oTechExtras[nfca_idx];
    }
    else
    {
        return oTag;
    }

    nParcel = Parcel.obtain();
    nParcel.writeInt(id.length);
    nParcel.writeByteArray(id);
    nParcel.writeInt(oTechList.length);
    nParcel.writeIntArray(oTechList);
    nParcel.writeTypedArray(oTechExtras,0);
    nParcel.writeInt(serviceHandle);
    nParcel.writeInt(isMock);
    if(isMock==0)
    {
        nParcel.writeStrongBinder(tagService);
    }
    nParcel.setDataPosition(0);

    Tag nTag = Tag.CREATOR.createFromParcel(nParcel);

    nParcel.recycle();

    return nTag;
}
</code>```

This patch was provided by bildin (https://github.com/bildin).

Although the device on which I tested was not of the earlier brands, the patch worked perfectly on my Moto X (1st Gen), with a modified ROM Marshmallow, so I guess it will also work for a wide range of devices with The NXP chip PN544

Body:
I've been developing an application in Android Studio to read and write NFC tags, specifically Mifare Classic tags. I managed to develop and test it on my smartphone (with S.O. KitKat) in early 2016 (a year ago).

As I mentioned, leave aside the application, and after having updated the version of Android Studio, the SDK and the S.O. From my smartphone to MarshMallow, this error appears when trying to write to the label: "java.lang.NullPointerException: Attempt to invoke virtual method 'void android.nfc.tech.MifareClassic.connect()' on a null object reference".

This error is apparently generated when trying to connect to MifareClassic tag.

Attached the code of my activity replacing some parts with ... that I consider are irrelevant.

import android.annotation.SuppressLint;
import android.app.Activity;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.os.Bundle;
import android.view.View.OnClickListener;
...

import java.io.IOException;
import java.io.UnsupportedEncodingException;

@SuppressLint("Escribir")
public class escribir extends Activity {
    NfcAdapter adapter;
    PendingIntent pendingIntent;
    IntentFilter writeTagFilters[];
    boolean writeMode;
    Tag myTag;
    MifareClassic mfc;
    Context context;
    ...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_datospropietario);
        context = this;
        ...

        Button btnWrite = (Button)findViewById(R.id.button);
        final String b = getIntent().getExtras().getString("datos");

        btnWrite.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                final String mensaje = (b + ...);

                if (first.getText().toString().isEmpty()) {
                    Toast.makeText(context, context.getString(R.string.missing_fields), Toast.LENGTH_SHORT).show();
                } else {
                    if (myTag == null) {
                        Toast.makeText(context, context.getString(R.string.error_notag), Toast.LENGTH_LONG).show();
                    } else {
                    MifareClassic tmpMFC = null;
                    try {
                        tmpMFC = MifareClassic.get(myTag);
                    } catch (Exception e) {
                        Toast.makeText(context, context.getString(R.string.error_notag), Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                    }
                    mfc = tmpMFC;

                    int sect;
                    if (mfc != null) {
                        sect = mfc.getSectorCount();
                    }
                    try {
                        mfc.connect();
                        ...
                    } catch (IOException e) {
                        Toast.makeText(context, context.getString(R.string.error_notag), Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                        myTag = null;
                    }
                }
            }
        });

        adapter = NfcAdapter.getDefaultAdapter(this);
        pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
        tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
        writeTagFilters = new IntentFilter[]{tagDetected};
    }

    private void write(String text, Tag tag, int sector) throws IOException, FormatException {

        NdefRecord[] records = {createRecord(text), NdefRecord.createApplicationRecord("my_app")};
        NdefMessage mensaje = new NdefMessage(records);

        NdefFormatable formatable = NdefFormatable.get(tag);

        if (formatable != null) {
            formatable.connect();
            formatable.format(mensaje);
            formatable.close();
        } else {
            Ndef ndef = Ndef.get(tag);
            ndef.connect();
            ndef.writeNdefMessage(mensaje);
            ndef.close();
        }

        MifareClassic mfc = MifareClassic.get(tag);
        ...
    }

    @SuppressLint("Escribir") private NdefRecord createRecord(String text) throws UnsupportedEncodingException{
        String lang = "es";
        byte[] textBytes = text.getBytes();
        byte[] langBytes = lang.getBytes("US-ASCII");
        int langLength = langBytes.length;
        int textLength = textBytes.length;
        byte[] payLoad = new byte[1 + langLength + textLength];

        payLoad[0] = (byte) langLength;

        System.arraycopy(langBytes, 0, payLoad, 1, langLength);
        System.arraycopy(textBytes, 0, payLoad, 1 + langLength, textLength);

        return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], payLoad);
    }

    @SuppressLint("Escribir") protected void onNewIntent(Intent intent){
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
            myTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        }
    }

    public void onPause(){
        super.onPause();
        WriteModeOff();
    }
    public void onResume(){
        super.onResume();
        WriteModeOn();
    }

    @SuppressLint("Escribir") private void WriteModeOn(){
        writeMode = true;
        adapter.enableForegroundDispatch(this, pendingIntent, writeTagFilters, null);
    }

    @SuppressLint("Escribir") private void WriteModeOff(){
        writeMode = false;
        adapter.disableForegroundDispatch(this);
    }
}

Body:
After researching the internet about this problem, I discovered that writing problems on NFC tags were presented on various devices, such as some HTC or Sony Xperia models. These issues were presented after upgrading the Android version to SDK 5.1 (Lollipop).

This problem originated because some of the manufacturers modified the stack order where the different Tag types were found causing conflicts when requesting TechExtras and returning SAK null or wrong values.

The detailed explanation I found for this is as follows:

HTC One: It seems, the reason for this bug is TechExtras of NfcA is null.
However, TechList contains MifareClassic.

Sony Xperia Z3 (+ emmulated MIFARE Classic tag): The buggy tag has two NfcA in the TechList with different SAK values and a MifareClassic (with the Extra of the second NfcA). Both, the second NfcA and the MifareClassic technique, have a SAK of 0x20. According to NXP's guidelines on identifying MIFARE tags (Page 11), this a MIFARE Plus or MIFARE DESFire tag. This method creates a new extra with the SAK values of both NfcA occurrences ORed (as mentioned in NXP's MIFARE type identification procedure guide) and replace the Extra of the first NfcA with the new one.

For more information please refer to https://github.com/ikarus23/MifareClassicTool/issues/52

And the patch proposed by the bildin user, who fixed my problem:

public Tag patchTag(Tag oTag)
{
    if (oTag == null)
        return null;

    String[] sTechList = oTag.getTechList();

    Parcel oParcel, nParcel;

    oParcel = Parcel.obtain();
    oTag.writeToParcel(oParcel, 0);
    oParcel.setDataPosition(0);

    int len = oParcel.readInt();
    byte[] id = null;
    if (len >= 0)
    {
        id = new byte[len];
        oParcel.readByteArray(id);
    }
    int[] oTechList = new int[oParcel.readInt()];
    oParcel.readIntArray(oTechList);
    Bundle[] oTechExtras = oParcel.createTypedArray(Bundle.CREATOR);
    int serviceHandle = oParcel.readInt();
    int isMock = oParcel.readInt();
    IBinder tagService;
    if (isMock == 0)
    {
        tagService = oParcel.readStrongBinder();
    }
    else
    {
        tagService = null;
    }
    oParcel.recycle();

    int nfca_idx=-1;
    int mc_idx=-1;

    for(int idx = 0; idx < sTechList.length; idx++)
    {
        if(sTechList[idx] == NfcA.class.getName())
        {
            nfca_idx = idx;
        }
        else if(sTechList[idx] == MifareClassic.class.getName())
        {
            mc_idx = idx;
        }
    }

    if(nfca_idx>=0&&mc_idx>=0&&oTechExtras[mc_idx]==null)
    {
        oTechExtras[mc_idx] = oTechExtras[nfca_idx];
    }
    else
    {
        return oTag;
    }

    nParcel = Parcel.obtain();
    nParcel.writeInt(id.length);
    nParcel.writeByteArray(id);
    nParcel.writeInt(oTechList.length);
    nParcel.writeIntArray(oTechList);
    nParcel.writeTypedArray(oTechExtras,0);
    nParcel.writeInt(serviceHandle);
    nParcel.writeInt(isMock);
    if(isMock==0)
    {
        nParcel.writeStrongBinder(tagService);
    }
    nParcel.setDataPosition(0);

    Tag nTag = Tag.CREATOR.createFromParcel(nParcel);

    nParcel.recycle();

    return nTag;
}

This patch was provided by bildin (https://github.com/bildin).

Although the device on which I tested was not of the earlier brands, the patch worked perfectly on my Moto X (1st Gen), with a modified ROM Marshmallow, so I guess it will also work for a wide range of devices with The NXP chip PN544


问:
Excel concatenate with IF statement
What I am trying to do is concatenate two cells, then check that concatenated value against a column of values, and put an X in a cell if such a value exists.  The following equation is what I'm using:

```<code>{=IF(CONCATENATE(A2, " ", B2) = 'MasterList'!$C:$C, "x", "")}
</code>```

Column A is the name of the software and Column B the version number (A="Microsoft .NET Framework 4.5.1", B="4.5.50938", for example). I know that this concatenated value exists on the MasterList worksheet so I don't understand why I'm not getting the answer I expect.

Gurus, what's my flaw here?

答:
I just want to say that before seeing this question, I had no idea what array formulas were.

I have the following working example:

Sheet1:

```<code>A1: Microsoft .NET Framework 4.5.1
B1: 4.5.50938

// press control-shift-enter after typing formula
C4: =IF(CONCATENATE(A1," ",B1)=Sheet2!$A:$A,"YAY","NAY")
</code>```

Sheet2:

```<code>A1: Microsoft .NET Framework 4.5.1 4.5.50938
</code>```

Not sure what the issue is with your spreadsheet. Do the values in MasterList!$C:$C actually correspond to what you expect as the result of the concatenation?

Title: Excel concatenate with IF statement

Body:
What I am trying to do is concatenate two cells, then check that concatenated value against a column of values, and put an X in a cell if such a value exists.  The following equation is what I'm using:

{=IF(CONCATENATE(A2, " ", B2) = 'MasterList'!$C:$C, "x", "")}

Column A is the name of the software and Column B the version number (A="Microsoft .NET Framework 4.5.1", B="4.5.50938", for example). I know that this concatenated value exists on the MasterList worksheet so I don't understand why I'm not getting the answer I expect.

Gurus, what's my flaw here?

Body:
I just want to say that before seeing this question, I had no idea what array formulas were.

I have the following working example:

Sheet1:

A1: Microsoft .NET Framework 4.5.1
B1: 4.5.50938

// press control-shift-enter after typing formula
C4: =IF(CONCATENATE(A1," ",B1)=Sheet2!$A:$A,"YAY","NAY")

Sheet2:

A1: Microsoft .NET Framework 4.5.1 4.5.50938

Not sure what the issue is with your spreadsheet. Do the values in MasterList!$C:$C actually correspond to what you expect as the result of the concatenation?


问:
Checking Whether user input 3x3 multidimensional array is a Markov Matrix
I'm trying to write a java program that prints whether a user input 3x3 multidimensional array is a Markov matrix; the prompt is below.

-An n x n matrix is called a positive Markov matrix if each
-element is positive and the sum of the elements in each column is 1. Write the -following method to check whether a matrix is a Markov matrix.

public static boolean isMarkovMatrix(double [][] m)

-Write a test program (the main method) that prompts the user to enter a 3 x 3 --matrix of double
-values and tests whether it is a Markov matrix.

My output for the code prints out that it is not a Markov matrix no matter what I input, and can't figure out why it's doing that. As a side note, I don't know any complex java, and have only been in class for a few weeks so what is below is the extent of my java programming skills. Any help would be appreciated! Thank you in advance.

```<code>import java.util.Scanner;

public class Problem3 {

    public static void main(String[] args) {
        //declarations
        double[][] markov = new double[3][3];
        Scanner keyboard = new Scanner(System.in);

        //input
        System.out.print("Please enter numbers to fill up a 3x3 matrix: ");
        for (int i = 0; i < markov.length; i++) {
            for (int x = 0; x < markov.length; x++) {
                markov[i][x] = keyboard.nextDouble();
            }
        }

        //output
        if (isMarkov(markov) == true) {
            System.out.print("Your matrix is a Markov Matrix!");
        } else if (isMarkov(markov) == false) {
            System.out.print("Your matrix is not a Markov Matrix!");
        }

        //close keyboard
        keyboard.close();

    }

    //method to check whether the matrix is positive
    public static boolean isPositive(double[][] array) {
        //declarations
        boolean answer = true;

        //processing
        for (int i = 0; i < array.length; i++) {
            for (int x = 0; x < array.length; x++) {
                if (array[i][x] < 0) {
                    answer = false;
                }
            }
        }
        return answer;
    }

    //method to check whether the sum of the columns are 1
    public static boolean columnSum(double[][] array) {
        //declarations
        double sum = 0;
        boolean answer = true;

        //processing
        for (int i = 0; i < array.length; i++) {
            for (int x = 0; x < array.length; x++) {
                sum += array[i][x];
            }
            if (sum != 1) {
                answer = false;
            }
        }
        return answer;
    }

    //method to check whether the matrix is a Markov matrix
    public static boolean isMarkov(double[][] array) {
        //declarations
        boolean answer = false;

        //processing
        if ((isPositive(array) == true) && (columnSum(array) == true)) {
            answer = true;
        }
        return answer;

    }

}
</code>```

答:
Your problem is in columnSum(double[][] array) function. The sum value is not reset after every column. That means your code sums up all columns in the value sum. Simply resetting sum to zero in the outer for loop should prevent this. If there is another problem, please let me know, I'll look over it again.

```<code>//method to check whether the sum of the columns are 1
public static boolean columnSum (double[][] array)
{
    //declarations
    double sum = 0;
    boolean answer = true;

    //processing
    for (int i = 0; i < array.length; i++)
    {
        sum = 0; //-----------------added-----------------
        for (int x = 0; x < array.length; x++)
        {
            sum += array[i][x];
        }
        if (sum != 1)
        {
            answer = false;
        }
    }
    return answer;
}
</code>```

On another note, just a small nice thing since you are somewhat new to coding. when evaluating boolean values, you don't need to add the ==true or ==false. The value itself is boolean. Example given here:

```<code>//instead of
if (flag == false){}
//do
if (!flag){}
</code>```

In case you do not know, the "!" negates the expression. If you want to evaluate "true", just remove the "!".

Body:
I'm trying to write a java program that prints whether a user input 3x3 multidimensional array is a Markov matrix; the prompt is below.

-An n x n matrix is called a positive Markov matrix if each
-element is positive and the sum of the elements in each column is 1. Write the -following method to check whether a matrix is a Markov matrix.

public static boolean isMarkovMatrix(double [][] m)

-Write a test program (the main method) that prompts the user to enter a 3 x 3 --matrix of double
-values and tests whether it is a Markov matrix.

My output for the code prints out that it is not a Markov matrix no matter what I input, and can't figure out why it's doing that. As a side note, I don't know any complex java, and have only been in class for a few weeks so what is below is the extent of my java programming skills. Any help would be appreciated! Thank you in advance.

import java.util.Scanner;

public class Problem3 {

    public static void main(String[] args) {
        //declarations
        double[][] markov = new double[3][3];
        Scanner keyboard = new Scanner(System.in);

        //input
        System.out.print("Please enter numbers to fill up a 3x3 matrix: ");
        for (int i = 0; i < markov.length; i++) {
            for (int x = 0; x < markov.length; x++) {
                markov[i][x] = keyboard.nextDouble();
            }
        }

        //output
        if (isMarkov(markov) == true) {
            System.out.print("Your matrix is a Markov Matrix!");
        } else if (isMarkov(markov) == false) {
            System.out.print("Your matrix is not a Markov Matrix!");
        }

        //close keyboard
        keyboard.close();

    }

    //method to check whether the matrix is positive
    public static boolean isPositive(double[][] array) {
        //declarations
        boolean answer = true;

        //processing
        for (int i = 0; i < array.length; i++) {
            for (int x = 0; x < array.length; x++) {
                if (array[i][x] < 0) {
                    answer = false;
                }
            }
        }
        return answer;
    }

    //method to check whether the sum of the columns are 1
    public static boolean columnSum(double[][] array) {
        //declarations
        double sum = 0;
        boolean answer = true;

        //processing
        for (int i = 0; i < array.length; i++) {
            for (int x = 0; x < array.length; x++) {
                sum += array[i][x];
            }
            if (sum != 1) {
                answer = false;
            }
        }
        return answer;
    }

    //method to check whether the matrix is a Markov matrix
    public static boolean isMarkov(double[][] array) {
        //declarations
        boolean answer = false;

        //processing
        if ((isPositive(array) == true) && (columnSum(array) == true)) {
            answer = true;
        }
        return answer;

    }

}

Body:
Your problem is in columnSum(double[][] array) function. The sum value is not reset after every column. That means your code sums up all columns in the value sum. Simply resetting sum to zero in the outer for loop should prevent this. If there is another problem, please let me know, I'll look over it again.

//method to check whether the sum of the columns are 1
public static boolean columnSum (double[][] array)
{
    //declarations
    double sum = 0;
    boolean answer = true;

    //processing
    for (int i = 0; i < array.length; i++)
    {
        sum = 0; //-----------------added-----------------
        for (int x = 0; x < array.length; x++)
        {
            sum += array[i][x];
        }
        if (sum != 1)
        {
            answer = false;
        }
    }
    return answer;
}

On another note, just a small nice thing since you are somewhat new to coding. when evaluating boolean values, you don't need to add the ==true or ==false. The value itself is boolean. Example given here:

//instead of
if (flag == false){}
//do
if (!flag){}

In case you do not know, the "!" negates the expression. If you want to evaluate "true", just remove the "!".


问:
match url params with regex
Im trying to extract url params with regex.

here is an example string: param1=val1&param2=val2&adv=val3&param3=val4&param4=val5

This is the regex im using right now:

```<code>(\&)([^=]+)\=([^&]+)
</code>```

I can't figure out how to match the first param. I what to have param1 be in group 2 and val2 in group 3 like the rest of the param matches.

https://regex101.com/r/Qzxyyo/1

How can I do this?

edit:
So this seems to work (meaning param1 is in group 2 and val1 in is group3). But I dont understand why it works or if it is reliable:

```<code>(\&|^)([^=]+)\=([^&]+)
</code>```

答:
```<code>(\&)([^=]+)\=([^&]+)
</code>```

Break it down!

\& look for a & character

[^=]+ match characters up until it hits a =

\= match the = character

[^&]+ match characters up until &

() These define the groups!

Title: match url params with regex

Body:
Im trying to extract url params with regex.

here is an example string: param1=val1&param2=val2&adv=val3&param3=val4&param4=val5

This is the regex im using right now:

(\&)([^=]+)\=([^&]+)

I can't figure out how to match the first param. I what to have param1 be in group 2 and val2 in group 3 like the rest of the param matches.

https://regex101.com/r/Qzxyyo/1

How can I do this?

edit:
So this seems to work (meaning param1 is in group 2 and val1 in is group3). But I dont understand why it works or if it is reliable:

(\&|^)([^=]+)\=([^&]+)

Body:
(\&)([^=]+)\=([^&]+)

Break it down!

\& look for a & character

[^=]+ match characters up until it hits a =

\= match the = character

[^&]+ match characters up until &

() These define the groups!


问:
Docker Cloud and JHipster console
Is it possible to set up JHipster console on Docker Cloud? My application is deployed on Heroku.
If is there no option, please advise where can I set up docker in cloud.
Regards!</p>

答:
1) SSH on your server
2) Install docker and docker-compose
3) Get the docker-compose file from https://github.com/jhipster/jhipster-console/blob/master/bootstrap/docker-compose.yml
4) Run docker-compose up -d

The console will be available on port 5601.
Refer to the docs at : https://jhipster.github.io/monitoring/

More advanced setup are possible but this is the easiest way to go. Also note that it is perfectly possible to run the JHipster-Console without Docker but it requires some work. To do this, setup an ELK stack yourself usinh on simple logstash configuration and scripts to preload the dashboards.

Title: Docker Cloud and JHipster console


问:
Perl script to copy logs with timestamp for every hour and paste into different file
First of all, I'm very new to programming and so would need your help in writing a perl script to do the following on windows.

I have a big log file with timestamp (1gb) and its difficult to read the logs as it takes a lot of time to open. so my requirement is to copy the logs from the bigger log file for the last one hour and paste it to another file and then copy the next 1 hr of data to different file(so we will have 24 files for a day). The next day the data in these files needs to be over written or delete & create a new file.

Sample log :

```<code>09092016-00:02:00,..................
09092016-00:02:08,..................
09092016-00:02:15,..................
09092016-00:02:18,..................
</code>```

Please help me with this and thanks for your help in advance.

Thanks,

答:
A simpler solution would be to use the split command to split the files into manageable sizes.

```<code>split -l 1000 logfile
</code>```

Will split your logfile into smaller files of 1000 lines each.
You can then just use grep to find the files that contain the day you need.

```<code>grep 09092016 logfile*
</code>```

Body:
First of all, I'm very new to programming and so would need your help in writing a perl script to do the following on windows.

I have a big log file with timestamp (1gb) and its difficult to read the logs as it takes a lot of time to open. so my requirement is to copy the logs from the bigger log file for the last one hour and paste it to another file and then copy the next 1 hr of data to different file(so we will have 24 files for a day). The next day the data in these files needs to be over written or delete & create a new file.

Sample log :

09092016-00:02:00,..................
09092016-00:02:08,..................
09092016-00:02:15,..................
09092016-00:02:18,..................

Please help me with this and thanks for your help in advance.

Thanks,

Body:
A simpler solution would be to use the split command to split the files into manageable sizes.

split -l 1000 logfile

Will split your logfile into smaller files of 1000 lines each.
You can then just use grep to find the files that contain the day you need.

grep 09092016 logfile*


问:
How to add a check box column in Janus gridEX
I have a Janus GridEX that loaded from DataTable in SQL database, It have 8 column in my Grid. Now I want to add check box column list and ability to select multiple rows.
I'll be appreciate if some one help!</p>

答:
This is VB.NET code.
    Imports Janus.Windows.GridEX</p>

```<code>    grdEmail.RootTable.Columns("receive_email").ColumnType = ColumnType.CheckBox
    grdEmail.RootTable.Columns("receive_email").EditType = EditType.CheckBox
    grdEmail.RootTable.Columns("receive_email").CheckBoxTrueValue = "Yes"
    grdEmail.RootTable.Columns("receive_email").CheckBoxFalseValue = "No"
</code>```

Body:
This is VB.NET code.
    Imports Janus.Windows.GridEX

    grdEmail.RootTable.Columns("receive_email").ColumnType = ColumnType.CheckBox
    grdEmail.RootTable.Columns("receive_email").EditType = EditType.CheckBox
    grdEmail.RootTable.Columns("receive_email").CheckBoxTrueValue = "Yes"
    grdEmail.RootTable.Columns("receive_email").CheckBoxFalseValue = "No"


问:
Python While/for/if statements
I wrote a program that multiplies input number by 127. The input doesn't accept alpha as well as number 9.

Besides number 9, it doesn't allow any number that contains 9 e.g. 99, 19 etc. Can we overcome this?

Also, if I type "99", it prints "Banned number" two times. Is this co-related with the first statement?

```<code>banned_number = "9"
while True:
    number = input("number ")

    for items in number:
        if items in banned_number:
            print ("Banned number.")
        elif number.isalpha():
            print ("Sorry, numbers only.")
        elif number.isdigit():
            a = int(number)
            print(a* 127)
</code>```

I know this program is useless, which it clearly is - I went off track when exercising loops and this is the final shape. Is there any way to make this code shorter? Can we make both elif's obsolete with a simple code?

I would appreciate your patience as I've only started Python last week, thank you.

答:
Firstly, the lexical comparison will fetch you incorrect results in terms of numbers as strings.

So, if you are interested in specific types to be checked, you need to compare int with int and str with str to get correct results.

You can use isinstance(a,type) to check for datatypes of values, which is the canonical way of doing this. You can do something like this :

```<code>banned_number = [9, 1]

while True:
    input_num = input("number ")
    # This will work for both Python 2.x and Python 3.x
    try :
        number = int(input_num)
    except :
        number = input_num

    if number in banned_number:
        print ("Banned number.")
    elif isinstance(number, str):
        print ("Sorry, numbers only.")
    elif (isinstance(number, int) or isinstance(number, float)):
        a = int(number)
        print(a* 127)
</code>```

This will result in :

```<code># for input 9
Banned number.

# for input 'a'
Sorry, numbers only.

# for input 99
12573
</code>```

Also, the reason why it is printing twice for input '99' because this will be treated as two-character string '9' and '9' and hence was printing Banned number. twice while looping.

Title: Python While/for/if statements

Body:
I wrote a program that multiplies input number by 127. The input doesn't accept alpha as well as number 9.

Besides number 9, it doesn't allow any number that contains 9 e.g. 99, 19 etc. Can we overcome this?

Also, if I type "99", it prints "Banned number" two times. Is this co-related with the first statement?

banned_number = "9"
while True:
    number = input("number ")

    for items in number:
        if items in banned_number:
            print ("Banned number.")
        elif number.isalpha():
            print ("Sorry, numbers only.")
        elif number.isdigit():
            a = int(number)
            print(a* 127)

I know this program is useless, which it clearly is - I went off track when exercising loops and this is the final shape. Is there any way to make this code shorter? Can we make both elif's obsolete with a simple code?

I would appreciate your patience as I've only started Python last week, thank you.

Body:
Firstly, the lexical comparison will fetch you incorrect results in terms of numbers as strings.

So, if you are interested in specific types to be checked, you need to compare int with int and str with str to get correct results.

You can use isinstance(a,type) to check for datatypes of values, which is the canonical way of doing this. You can do something like this :

banned_number = [9, 1]

while True:
    input_num = input("number ")
    # This will work for both Python 2.x and Python 3.x
    try :
        number = int(input_num)
    except :
        number = input_num

    if number in banned_number:
        print ("Banned number.")
    elif isinstance(number, str):
        print ("Sorry, numbers only.")
    elif (isinstance(number, int) or isinstance(number, float)):
        a = int(number)
        print(a* 127)

This will result in :

# for input 9
Banned number.

# for input 'a'
Sorry, numbers only.

# for input 99
12573

Also, the reason why it is printing twice for input '99' because this will be treated as two-character string '9' and '9' and hence was printing Banned number. twice while looping.


问:
How to implement SMS and Email service in alexa?
I am trying to implement a SMS and email service in alexa and using PHP, Jquery to acheive the task. I am very new to the technology and after serching to lot of website, I am lost somewhere and unable to start. Please let me know any reference regarding the topic.</p>

答: you can use twilio which works pretty good with alexa https://github.com/krvarma/Amazon-Echo-and-Twilio Getting an email from the user by telling it to alexa in my opinion is impossible for now. Alexa doesnt convert all what you says to the right text, additional problem are special characters as - _ @</p>